Farseen0/scar-pairs huggingface dataset:
MEDIUM severity: The `_recipientBalance()` function in the code calculates the vested amount (balance) by multiplying. The `_recipientBalance()` function in the code calculates the vested amount (balance) by multiplying the elapsed time (`elapsedTime_`) with the product of `RATE_DECIMALS_MULTIPLIER`, `tokenAmount_`, and `duration`, and then dividing the result by `RATE_DECIMALS_MULTIPLIER`. This calculation, however...

Vulnerable code:
```\nbalance = elapsedTime_ * (RATE_DECIMALS_MULTIPLIER * tokenAmount_ / duration) / RATE_DECIMALS_MULTIPLIER\n```
MEDIUM severity: The vulnerability arises when an existing buyer, who has been regularly renewing their protection, i. The vulnerability arises when an existing buyer, who has been regularly renewing their protection, is denied the opportunity to renew their protection even when they are well within the renewal grace period. This occurs when the lending state is updated from "Active" to "LateWithinGracePeriod" just...

Vulnerable code:
```\nfunction _verifyLendingPoolIsActive(\n    IDefaultStateManager defaultStateManager,\n    address _protectionPoolAddress,\n    address _lendingPoolAddress\n) internal view {\n    LendingPoolStatus poolStatus = defaultStateManager.getLendingPoolStatus(\n        _protectionPoolAddress,\n        _lendingPoolAddress\n    );\n\n    if (\n        poolStatus == LendingPoolStatus.LateWithinGracePeriod ||\n        poolStatus == LendingPoolStatus.Late\n    ) {\n        revert IProtectionPool.LendingPoolHasLatePayment(_lendingPoolAddress);\n    }\n}\n```
MEDIUM severity: The `oracleSlippagePercentOrLimit` variable, which determines the maximum allowed slippage for a tra. The `oracleSlippagePercentOrLimit` variable, which determines the maximum allowed slippage for a trade, is not properly bounded in the `StrategyUtils._executeTradeExactIn` function. Specifically, when `useDynamicSlippage` is set to `false`, the function does not check if the `oracleSlippagePercentOr...

Vulnerable code:
```\nfunction _executeTradeExactIn(\n    TradeParams memory params,\n    ITradingModule tradingModule,\n    address sellToken,\n    address buyToken,\n    uint256 amount,\n    bool useDynamicSlippage\n) internal returns (uint256 amountSold, uint256 amountBought) {\n    require(\n        params.tradeType == TradeType.EXACT_IN_SINGLE || params.tradeType == TradeType.EXACT_IN_BATCH\n    );\n\n    if (useDynamicSlippage) {\n        require(params.oracleSlippagePercentOrLimit <= Constants.SLIPPAGE_LIMIT_PRECISION);\n    }\n\n    Trade memory trade = Trade(\n        params.tradeType,\n        sellToken,\n        buyToken,\n        amount,\n        useDynamicSlippage? 0 : params.oracleSlippagePercentOrLimit,\n        block.timestamp, // deadline\n        params.exchangeData\n    );\n}\n```
MEDIUM severity: The `SwapHelper.getCalldata()` function retrieves data for a swap operation based on user input and . The `SwapHelper.getCalldata()` function retrieves data for a swap operation based on user input and relies on the `whitelistedRouters` mapping to restrict the `_router` parameter. However, a critical issue arises when the `setWhitelistedRouters()` function sets the `_routers` state to `false`. Altho...

Vulnerable code:
```\nfor (uint i = 0; i < _statuses.length; ) {\n    whitelistedRouters[_routers[i]] = _statuses[i];\n    if (_statuses[i]) {\n        routerTypes[_routers[i]] = _types[i];\n        emit SetRouterType(_routers[i], _types[i]);\n    }\n    emit SetWhitelistedRouter(_routers[i], _statuses[i]);\n    unchecked {\n        i++;\n    }\n}\n```
MEDIUM severity: The `totalCoverTokens` variable is not being updated correctly when a claim is processed, resulting . The `totalCoverTokens` variable is not being updated correctly when a claim is processed, resulting in an inaccurate representation of the total available coverage. Specifically, when a policy is removed and the claim is processed, the `totalCoverTokens` should be decreased by the amount of coverage...

Vulnerable code:
```\nPolicyHolder storage holder = policyHolders[claimer];\n\nepochAmounts[holder.endEpochNumber] = \n    epochAmounts[holder.endEpochNumber].sub(holder.coverTokens);\n\ntotalLiquidity = totalLiquidity.sub(claimAmount);\n\ndaiToken.transfer(claimer, claimAmount);\n\ndelete policyHolders[claimer];\npolicyRegistry.removePolicy(claimer);\n```
MEDIUM severity: The `svTokenValue` function in the `GMXReader` contract is susceptible to returning an overestimated. The `svTokenValue` function in the `GMXReader` contract is susceptible to returning an overestimated value for each strategy vault share token due to the use of outdated `totalSupply` data. Specifically, the function calculates the share value based on the current `totalSupply`, which may not accoun...

Vulnerable code:
```\nfunction svTokenValue(GMXTypes.Store storage self) public view returns (uint256) {\n    uint256 equityValue_ = equityValue(self);\n    uint256 totalSupply_ = IERC20(address(self.vault)).totalSupply();\n    if (equityValue_ == 0 || totalSupply_ == 0) {\n        return SAFE_MULTIPLIER;\n    }\n    return equityValue_ * SAFE_MULTIPLIER / totalSupply_;\n}\n```
MEDIUM severity: This vulnerability is related to the inconsistent input validation in certain functions within the c. This vulnerability is related to the inconsistent input validation in certain functions within the codebase. Specifically, there are instances where input validation is not thoroughly implemented, potentially allowing malicious actors to manipulate the system.\n\nThe `Amp.transferWithData` function,...

Vulnerable code:
```\nrequire(_isOperator(msg.sender, _from), EC_58_INVALID_OPERATOR);\n```\n```\nrequire(\n    _operator!= msg.sender\n);\n```\n```\nrequire(\n    _operator!= msg.sender\n);\n```
MEDIUM severity: When a position is liquidated, the liquidator is required to pay a premium to the lender, which is a. When a position is liquidated, the liquidator is required to pay a premium to the lender, which is accumulated in the `sharingProfitTokenAmts` array along with the lender's profit. However, if the net PnL (profit and loss) of the position is less than or equal to zero (`netPnLE36 <= 0`), the `_share...

Vulnerable code:
```\n(\n    netPnLE36,\n    lenderProfitUSDValueE36,\n    borrowTotalUSDValueE36,\n    positionOpenUSDValueE36,\n    sharingProfitTokenAmts\n) = calcProfitInfo(_positionManager, _user, _posId);\n\n// 2. add liquidation premium to the shared profit amounts\nuint lenderLiquidationPremiumBPS = IConfig(config).lenderLiquidatePremiumBPS();\n\nfor (uint i = 0; i < sharingProfitTokenAmts.length; i++) {\n    sharingProfitTokenAmts[i] += (pos.openTokenInfos[i].borrowAmt * lenderLiquidationPremiumBPS) / BPS;\n}\n```\n```\nfunction _shareProfitsAndRepayAllDebts(\n    address _positionManager,\n    address _posOwner,\n    uint _posId,\n    int _netPnLE36,\n    uint[] memory _shareProfitAmts,\n    address[] memory _tokens,\n    OpenTokenInfo[] memory _openTokenInfos\n) internal {\n    // 0. load states\n    address _lendingProxy = lendingProxy;\n\n    // 1. if net pnl is positive, share profits to lending proxy\n    if (_netPnLE36 > 0) {\n        for (uint i = 0; i < _shareProfitAmts.length; i++) {\n            if (_shareProfitAmts[i] > 0) {\n                ILendingProxy(_lendingProxy).shareProfit(_tokens[i], _shareProfitAmts[i]);\n            }\n        }\n        unchecked {\n            i++;\n        }\n    }\n    emit ProfitShared(_posOwner, _posId, _tokens, _shareProfitAmts);\n}\n```\n```\nunderlyingAmts = new uint[](underlyingTokens.length);\n\nfor (uint i = 0; i < underlyingTokens.length; i++) {\n    underlyingAmts[i] = IERC20(underlyingTokens[i]).balanceOf(address(this));\n\n    if (underlyingAmts[i] < _params.minUnderlyingAmts[i]) {\n        revert TokenAmountLessThanExpected(\n            underlyingTokens[i],\n            underlyingAmts[i],\n            _params.minUnderlyingAmts[i]\n        );\n    }\n    _doRefund(underlyingTokens[i], underlyingAmts[i]);\n}\n```
MEDIUM severity: The `UPDATE_RESERVE_ROLE` permission allows an authorized entity to update the address of the pool/r. The `UPDATE_RESERVE_ROLE` permission allows an authorized entity to update the address of the pool/reserve contract in the `Tap` contract. However, this update is not propagated to other contracts that rely on the reserve, such as `MarketMaker` and `Controller`. This inconsistency can lead to issues...

Vulnerable code:
```\n/**\n * @notice Update reserve to `_reserve`\n * @param _reserve The address of the new reserve [pool] contract\n*/\nfunction updateReserve(Vault _reserve) external auth(UPDATE_RESERVE_ROLE) {\n    require(isContract(_reserve), ERROR_CONTRACT_IS_EOA);\n\n    _updateReserve(_reserve);\n}\n```
MEDIUM severity: The vulnerability in the `Borrower` contract's `modify`, `liquidate`, and `warn` functions allows an. The vulnerability in the `Borrower` contract's `modify`, `liquidate`, and `warn` functions allows an attacker to intentionally create bad debt in a single transaction. This is achieved by borrowing at the maximum leverage plus a safety margin, waiting for a period of market inactivity, and then with...

Vulnerable code:
```\npragma solidity 0.8.17;\n\nimport "forge-std/Test.sol";\nimport "src/libraries/constants/Constants.sol";\nimport "src/libraries/constants/Q.sol";\nimport "src/libraries/Positions.sol";\nimport "src/Borrower.sol";\nimport "src/Factory.sol";\nimport "src/Lender.sol";\nimport "src/RateModel.sol";\nimport "./Utils.sol";\n\ncontract RateModelMax is IRateModel {\n    uint256 private constant _A = 6.1010463348e20;\n    uint256 private constant _B = _A / 1e18;\n\n    function getYieldPerSecond(uint256 utilization, address) external pure returns (uint256) {\n        unchecked {\n            return (utilization < 0.99e18)? _A / (1e18 - utilization) - _B : MAX_RATE;\n        }\n    }\n}\n\ncontract ExploitTest is Test, IManager, ILiquidator {\n    IUniswapV3Pool constant pool = IUniswapV3Pool(0xC2e9F25Be6257c210d7Adf0D4Cd6E3E881ba25f8);\n    ERC20 constant asset0 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);\n    ERC20 constant asset1 = ERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);\n\n    Lender immutable lender0;\n    Lender immutable lender1;\n    Borrower immutable account;\n\n    constructor() {\n        vm.createSelectFork(vm.rpcUrl("mainnet"));\n        vm.rollFork(15_348_451);\n\n        Factory factory = new FatFactory(\n            address(0),\n            address(0),\n            VolatilityOracle(address(new VolatilityOracleMock())),\n            new RateModelMax()\n        );\n\n        factory.createMarket(pool);\n        (lender0, lender1, ) = factory.getMarket(pool);\n        account = factory.createBorrower(pool, address(this), bytes12(0));\n    }\n\n    function setUp() public {\n        // deal to lender and deposit (so that there are assets to borrow)\n        deal(address(asset0), address(lender0), 10000e18); // DAI\n        deal(address(asset1), address(lender1), 10000e18); // WETH\n```\n```\nUser borrow:: 10629296791890000000000\nUser stored borrow:: 10000000000000000000000\nBefore liquidation User borrow:: 10630197795010000000000\nBefore liquidation User stored borrow:: 10630197795010000000000\nBefore liquidation User assets:: 10051000000000000000000\nLiquidated User borrow:: 579197795010000000001\nLiquidated User assets:: 0\n```
MEDIUM severity: The vulnerability lies in the `AuctionHouse::claimProceeds()` function, where the protocol's handlin. The vulnerability lies in the `AuctionHouse::claimProceeds()` function, where the protocol's handling of tokens with ERC20 metadata and decimals between 6-18 can lead to funds being locked in the protocol. Specifically, the function processes a `prefundingRefund` calculation, which can result in a v...

Vulnerable code:
```\nuint96 prefundingRefund = routing.funding + payoutSent_ - sold_;\nunchecked {\n    routing.funding -= prefundingRefund;\n}\nTransfer.transfer(\n    routing.baseToken,\n    _getAddressGivenCallbackBaseTokenFlag(routing.callbacks, routing.seller),\n    prefundingRefund,\n    false\n);\n```
MEDIUM severity: The `getCErc20Price` function in the `CTokenOracle.sol` contract contains a critical mathematical er. The `getCErc20Price` function in the `CTokenOracle.sol` contract contains a critical mathematical error that significantly overvalues CTokens. This error occurs in the calculation of the cToken price, which is a critical component of the contract's functionality.\n\nThe issue arises in the multiplic...

Vulnerable code:
```\nfunction getCErc20Price(ICToken cToken, address underlying) internal view returns (uint) {\n    return cToken.exchangeRateStored()\n       .mulDivDown(1e8, IERC20(underlying).decimals())\n       .mulWadDown(oracle.getPrice(underlying));\n}\n```
MEDIUM severity: The NativeOptimismImpl vulnerability occurs when users attempt to utilize non-native tokens, which c. The NativeOptimismImpl vulnerability occurs when users attempt to utilize non-native tokens, which can lead to the failure of emitting the `SocketBridge` event. This event is crucial for bridging native tokens, and its absence can have significant implications for the functionality and security of t...

Vulnerable code:
```\nfunction bridgeAfterSwap(\n```\n```\nfunction swapAndBridge(\n```\n```\nfunction bridgeERC20To(\n    address tokenAddress,\n    uint256 amount,\n    address recipient,\n    bytes32 bridgeId,\n    bytes32[] calldata path,\n    bytes calldata data\n) public {\n    //... rest of the code\n}\n```
MEDIUM severity: This vulnerability occurs when attempting to swap an 18-decimal token for an 8-decimal token, allowi. This vulnerability occurs when attempting to swap an 18-decimal token for an 8-decimal token, allowing an attacker to purchase an 18-decimal token with an amount of 0 8-decimal tokens. This is achieved by exploiting a specific scenario where the `d3Proxy.buyTokens` function is called with a swap dat...

Vulnerable code:
```\nuint256 payFromToken = d3Proxy.buyTokens(\n    address(d3MM),\n    user1,\n    address(token1),\n    address(token2),\n    10000000,\n    0,\n    abi.encode(swapData),\n    block.timestamp + 1000\n);\nassert(payFromToken == 0);\n```
MEDIUM severity: The `Tranche.redeemWithYT()` function in the Tranche smart contract is vulnerable to a yield token (. The `Tranche.redeemWithYT()` function in the Tranche smart contract is vulnerable to a yield token (YT) allowance manipulation, which could potentially drain all unclaimed and unaccrued target tokens (TT) if users set any allowance greater than zero to others. This issue arises on line 283, where th...

Vulnerable code:
```\nfunction redeemWithYT(address from, address to, uint256 pyAmount) external nonReentrant returns (uint256) {\n    accruedInTarget += _computeAccruedInterestInTarget(\n        _gscales.maxscale,\n        _lscale,\n        _yt.balanceOf(from)\n    );\n\n    uint256 sharesRedeemed = pyAmount.divWadDown(_gscales.maxscale);\n\n    _target.safeTransfer(address(adapter), sharesRedeemed + accruedInTarget);\n\n    (uint256 amountWithdrawn, ) = adapter.prefundedRedeem(to);\n\n    return amountWithdrawn;\n}\n```\n```\n// SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\n\nimport {TestTranche} from "./Tranche.t.sol";\nimport "forge-std/console2.sol";\n\ncontract TrancheAllowanceIssue is TestTranche {\n    address bob = address(0x22);\n\n    function setUp() public virtual override {\n        super.setUp();\n    }\n\n    function testTrancheAllowanceIssue() public {\n        // 1. issue some PT and YT\n        deal(address(underlying), address(this), 1_000_000, true);\n        tranche.issue(address(this), 1_000_000);\n\n        // 2. generating some unclaimed yield\n        vm.warp(block.timestamp + 30 days);\n        _simulateScaleIncrease();\n\n        // 3. give bob any negligible allowance, could be as low as only 1wei\n        tranche.approve(bob, 1);\n        yt.approve(bob, 1);\n\n        // 4. all unclaimed and pending yield drained by bob\n        assertEq(0, underlying.balanceOf(bob));\n        vm.prank(bob);\n        tranche.redeemWithYT(address(this), bob, 1);\n        assertTrue(underlying.balanceOf(bob) > 494_000_000);\n    }\n}\n```\n```\n2024-01-napier\napier-v1> forge test --match-test testTrancheAllowanceIssue -vv\n\n[⠔] Compiling\n[⠊] Compiling 42 files with 0.8.19\n[⠔] Solc 0.8.19 finished in 82.11s\nCompiler run successful!\n[⠒] Solc 0.8.19 finished in 82.11s\n\nRunning 1 test for test/unit/TrancheAllowanceIssue.t.sol:TrancheAllowanceIssue\n[PASS] testTrancheAllowanceIssue() (gas: 497585)\nTest result: ok. 1 passed; 0 failed; 0 skipped; finished in 11.06ms\n\nRan 1 test suites: 1 tests passed, 0 failed, 0 skipped (1 total tests)\n```
MEDIUM severity: The `RocketDaoNodeTrusted` contract contains two unused events, `MemberJoined` and `MemberLeave`, wh. The `RocketDaoNodeTrusted` contract contains two unused events, `MemberJoined` and `MemberLeave`, which are defined but not utilized within the contract's logic. These events are declared with parameters `_nodeAddress`, `_rplBondAmount`, and `time`, indicating that they are intended to be triggered...

Vulnerable code:
```\nevent MemberJoined(address indexed _nodeAddress, uint256 _rplBondAmount, uint256 time);\n\nevent MemberLeave(address indexed _nodeAddress, uint256 _rplBondAmount, uint256 time);\n```
MEDIUM severity: The `changeStakeTime` and `changeStakeAmount` functions in the `Staking` contract are problematic du. The `changeStakeTime` and `changeStakeAmount` functions in the `Staking` contract are problematic due to their ability to modify the locking bonus. Any alteration to these values can lead to an imbalance in the voting system. Specifically, if the bonus is increased, existing stakers will be at a dis...

Vulnerable code:
```\nfunction _stakeToken(uint _tokenId, uint _unlockTime) internal returns (uint) {\n    if (_unlockTime > 0) {\n        unlockTime[_tokenId] = _unlockTime;\n        uint fullStakedTimeBonus = ((_unlockTime - block.timestamp) * stakingSettings.maxStakeBonusAmount) / stakingSettings.maxStakeBonusTime;\n        stakedTimeBonus[_tokenId] = _tokenId < 10000? fullStakedTimeBonus : fullStakedTimeBonus / 2;\n    }\n}\n```
MEDIUM severity: The LibMath and LibOrder libraries contain several functions that declare named return values but ex. The LibMath and LibOrder libraries contain several functions that declare named return values but explicitly return a value instead. This practice is considered a code smell, as it can lead to confusion and potential issues in the code's maintainability and scalability.\n\nIn the provided code, the...

Vulnerable code:
```\nfunction min(int256 x, int256 y) internal pure returns (int256 z) {\n    return x <= y? x : y;\n}\n\nfunction max(int256 x, int256 y) internal pure returns (int256 z) {\n    return x >= y? x : y;\n}\n```\n```\nfunction min(uint256 x, uint256 y) internal pure returns (uint256 z) {\n    return x <= y? x : y;\n}\n\nfunction max(uint256 x, uint256 y) internal pure returns (uint256 z) {\n    return x >= y? x : y;\n}\n```\n```\nfunction getOrderHash(Order memory order) internal pure returns (bytes32 orderHash) {\n    orderHash = LibEIP712.hashEIP712Message(hashOrder(order));\n    return orderHash;\n}\n```\n```\nfunction hashOrder(Order memory order) internal pure returns (bytes32 result) {\n    bytes32 orderType = EIP712_ORDER_TYPE;\n    assembly {\n        let start := sub(order, 32)\n        let tmp := mload(start)\n        mstore(start, orderType)\n        result := keccak256(start, 224)\n        mstore(start, tmp)\n    }\n    return result;\n}\n```
MEDIUM severity: When an insurance buyer attempts to increase their coverage amount by calling the `buy` function mul. When an insurance buyer attempts to increase their coverage amount by calling the `buy` function multiple times for the same policy and time frame, they will inadvertently lose their previously purchased coverage. This occurs because the `buy` function only updates the `coverageMap` with the latest...

Vulnerable code:
```\nfor (uint256 w = fromWeek_; w < toWeek_; ++w) {\n    incomeMap[policyIndex_][w] = \n    incomeMap[policyIndex_][w].add(premium);\n\n    coveredMap[policyIndex_][w] = \n    coveredMap[policyIndex_][w].add(amount_);\n\n    require(coveredMap[policyIndex_][w] <= maximumToCover, \n        "Not enough to buy");\n\n    coverageMap[policyIndex_][w][_msgSender()] = Coverage({\n        amount: amount_,\n        premium: premium,\n        refunded: false\n    });\n}\n```
MEDIUM severity: The `zNS` registrar contract, which inherits from `IRegistrar`, `OwnableUpgradeable`, and `ERC721Pau. The `zNS` registrar contract, which inherits from `IRegistrar`, `OwnableUpgradeable`, and `ERC721PausableUpgradeable`, has a critical flaw in its implementation. Although the contract is designed to be ownable and pausable, the functionality to pause the contract is not actually implemented. This me...

Vulnerable code:
```\ncontract Registrar is\n    IRegistrar,\n    OwnableUpgradeable,\n    ERC721PausableUpgradeable\n{\n```
MEDIUM severity: The `GeoEmaAndCumSmaPump` contract assumes that each well will ensure that the `update` call is made. The `GeoEmaAndCumSmaPump` contract assumes that each well will ensure that the `update` call is made with a non-zero reserve value. However, there is no actual requirement in the `Well` contract to enforce this assumption. This lack of enforcement can lead to unintended consequences, as the geometri...

Vulnerable code:
```\n/**\n * @title GeoEmaAndCumSmaPump\n * @author Publius\n * @notice Stores a geometric EMA and cumulative geometric SMA for each reserve.\n * @dev A Pump designed for use in Beanstalk with 2 tokens.\n\nThis Pump has 3 main features:\n1. Multi-block MEV resistence reserves\n2. MEV-resistant Geometric EMA intended for instantaneous reserve queries\n3. MEV-resistant Cumulative Geometric intended for SMA reserve queries\n\nNote: If an `update` call is made with a reserve of 0, the Geometric mean oracles will be set to 0.\nEach Well is responsible for ensuring that an `update` call cannot be made with a reserve of 0.\n*/\n```\n```\nfor (uint i; i < length; ++i) {\n    b.lastReserves[i] = _capReserve(b.lastReserves[i], (reserves[i] > 0? reserves[i] : 1).fromUIntToLog2(), blocksPassed);\n    b.emaReserves[i] = b.lastReserves[i].mul(ABDKMathQuad.ONE.sub(aN)).add(b.emaReserves[i].mul(aN));\n    b.cumulativeReserves[i] = b.cumulativeReserves[i].add(b.lastReserves[i].mul(deltaTimestampBytes));\n}\n```