Farseen0/scar-pairs huggingface dataset:
MEDIUM severity: The `twapPriceInEther` calculation in the `baseOracleCircuitBreaker` function is vulnerable to a los. The `twapPriceInEther` calculation in the `baseOracleCircuitBreaker` function is vulnerable to a loss of precision due to an incorrect order of operations. Specifically, the `twapPrice` value is divided by `Constants.DECIMAL_USDC` before being multiplied by `1 ether`. This division operation reduces...

Vulnerable code:
```\nfunction baseOracleCircuitBreaker(\n    uint256 protocolPrice,\n    uint80 roundId,\n    int256 chainlinkPrice,\n    uint256 timeStamp,\n    uint256 chainlinkPriceInEth\n) private view returns (uint256 _protocolPrice) {\n    if (invalidFetchData || priceDeviation) {\n        uint256 twapPrice = IDiamond(payable(address(this))).estimateWETHInUSDC(\n            Constants.UNISWAP_WETH_BASE_AMT,\n            30 minutes\n        );\n        uint256 twapPriceInEther = (twapPrice / Constants.DECIMAL_USDC) * 1 ether;\n```\n```\ntwapPrice = 1902501929\ntwapPriceInEther = 1902000000000000000000\n\nif twapPrice * 10**18 == twapPriceInEther:\n```
MEDIUM severity: The vulnerability lies in the calculation of the spot price deviation, which uses a low precision wh. The vulnerability lies in the calculation of the spot price deviation, which uses a low precision when checking the deviation limit. Specifically, the calculation involves multiplying the absolute difference between the oracle and spot values by a constant `PERCENTAGE_DECIMALS` (set to 100) and then...

Vulnerable code:
```\nFile: Constants.sol\n\nint256 internal constant PERCENTAGE_DECIMALS = 100;\n```\n```\nFile: nTokenCalculations.sol\n\nint256 maxValueDeviationPercent = uint256(uint8(nToken.parameters[Constants.MAX_MINT_DEVIATION_LIMIT]));\n\nint256 deviationInPercentage = nTokenOracleValue.sub(nTokenSpotValue).abs().mul(Constants.PERCENTAGE_DECIMALS).div(nTokenOracleValue);\n\nrequire(deviationInPercentage <= maxValueDeviationPercent, "Over Deviation Limit");\n```\n```\nnTokenOracleValue.sub(nTokenSpotValue).abs().mul(Constants.PERCENTAGE_DECIMALS).div(nTokenOracleValue)\n\n((nTokenOracleValue - nTokenSpotValue) * Constants.PERCENTAGE_DECIMALS) / nTokenOracleValue\n\n((1_000_000_000 - 980_000_001) * Constants.PERCENTAGE_DECIMALS) / 1_000_000_000\n\n(19_999_999 * Constants.PERCENTAGE_DECIMALS) / 1_000_000_000\n\n1_999_999_900 / 1_000_000_000 = 1.9999999 = 1\n```
MEDIUM severity: The `UniV2LPOracle` implementation, which calculates the price of a liquidity provider (LP) token ba. The `UniV2LPOracle` implementation, which calculates the price of a liquidity provider (LP) token based on the fair asset prices and reserves, is vulnerable to incorrect calculations when the underlying tokens' `decimals` are not 18. This is because the implementation assumes that the pool balances...

Vulnerable code:
```\nfunction getPrice(address pair) external view returns (uint) {\n    (uint r0, uint r1,) = IUniswapV2Pair(pair).getReserves();\n\n    return FixedPointMathLib.sqrt(\n        r0.mulWadDown(r1)\n           .mulWadDown(oracle.getPrice(IUniswapV2Pair(pair).token0()))\n           .mulWadDown(oracle.getPrice(IUniswapV2Pair(pair).token1()))\n    )\n   .mulDivDown(2e27, IUniswapV2Pair(pair).totalSupply());\n}\n```\n```\nuint256 internal constant WAD = 1e18;  // The scalar of ETH and most ERC20s.\n\nfunction mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {\n    return mulDivDown(x, y, WAD);  // Equivalent to (x * y) / WAD rounded down.\n}\n```\n```\nfunction mulDivDown(\n    uint256 x,\n    uint256 y,\n    uint256 denominator\n) internal pure returns (uint256 z) {\n    assembly {\n        z := mul(x, y)\n\n        if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) {\n            revert(0, 0)\n        }\n\n        z := div(z, denominator)\n    }\n}\n```
MEDIUM severity: The vulnerability lies in the `onlySource` authentication mechanism implemented in the `XProvider` c. The vulnerability lies in the `onlySource` authentication mechanism implemented in the `XProvider` contract, which is responsible for managing interactions between vaults deployed on various networks and the `XChainController`. The `onlySource` modifier is designed to ensure that only authorized act...

Vulnerable code:
```\nmodifier onlySource(address _originSender, uint32 _origin) {\n    require(_originSender == trustedRemoteConnext[_origin] && msg.sender == connext, "Not trusted");\n}\n```\n```\n(bool success, bytes memory returnData) = \nExcessivelySafeCall.excessivelySafeCall(\n    _params.to,\n    gasleft() - Constants.EXECUTE_CALLDATA_RESERVE_GAS,\n    0, \n    Constants.DEFAULT_COPY_BYTES, \n    abi.encodeWithSelector(\n        IXReceiver.xReceive.selector,\n        _transferId,\n        _amount,\n        _asset,\n        _reconciled? _params.originSender : address(0), \n        _params.originDomain,\n        _params.callData\n    )\n);\n```
MEDIUM severity: The Whitelist Proposal Duplicate Won't Fix vulnerability occurs when a user can submit a new proposa. The Whitelist Proposal Duplicate Won't Fix vulnerability occurs when a user can submit a new proposal with the same token, despite the existing mechanism to prevent duplicate proposals. This is because the current implementation only checks for sponsored proposals with the same token, but does not a...

Vulnerable code:
```\nif (proposal.flags[4]) {\n    require(!tokenWhitelist[address(proposal.tributeToken)], "cannot already have whitelisted the token");\n    require(!proposedToWhitelist[address(proposal.tributeToken)], 'already proposed to whitelist');\n    proposedToWhitelist[address(proposal.tributeToken)] = true;\n```
MEDIUM severity: The protocol's implementation of a blacklist feature is intended to enforce OFAC, AML, and other acc. The protocol's implementation of a blacklist feature is intended to enforce OFAC, AML, and other account security requirements by restricting blacklisted addresses from sending or receiving tokens. However, a critical vulnerability exists in the protocol's code, which allows blacklisted addresses to...

Vulnerable code:
```\nfunction _beforeTokenTransfer(address from, address to, uint256) internal virtual override {\n    // Restrictions ignored for minting and burning\n    // If transferRestrictor is not set, no restrictions are applied\n\n    if (from == address(0) || to == address(0) || address(transferRestrictor) == address(0)) {\n        return;\n    }\n\n    // Check transfer restrictions\n    transferRestrictor.requireNotRestricted(from, to);\n}\n```\n```\nfunction requireNotRestricted(address from, address to) external view virtual {\n    if (blacklist[from] || blacklist[to]) {\n        revert AccountRestricted();\n    }\n}\n```
MEDIUM severity: The vulnerability lies in the way the vault calculates its collateral for leverage calculations. The. The vulnerability lies in the way the vault calculates its collateral for leverage calculations. The vault's collateral is calculated as the sum of collaterals from all markets, excluding pending keeper and position fees. However, pending fees are included in the account health calculations within t...

Vulnerable code:
```\nlocal memory local = registration.market.locals(address(this));\ncontext.latestIds.update(marketId, local.latestId);\ncontext.currentIds.update(marketId, local.currentId);\ncontext.collaterals[marketId] = local.collateral;\n```\n```\ncontext.pendingCollateral = context.pendingCollateral\n   .sub(newPendingPosition.fee)\n   .sub(Fixed6Lib.from(newPendingPosition.keeper));\n\nif (protected && (\n   !context.closable.isZero() || // even if closable is 0, position can still increase\n    context.latestPosition.local.maintained(\n        context.latestVersion,\n        context.riskParameter,\n        context.pendingCollateral.sub(collateral)\n    ) ||\n    collateral.lt(Fixed6Lib.from(-1, _liquidationFee(context, newOrder)))\n)) {\n    revert MarketInvalidProtectionError();\n}\n\nif (!context.currentPosition.local.margined(\n    context.latestVersion,\n    context.riskParameter,\n    context.pendingCollateral\n)) {\n    revert MarketInsufficientMarginError();\n}\n\nif (!PositionLib.maintained(\n    context.maxPendingMagnitude,\n    context.latestVersion,\n    context.riskParameter,\n    context.pendingCollateral\n)) {\n    revert MarketInsufficientMaintenanceError();\n}\n```
MEDIUM severity: The vulnerability arises from the use of inline assembly in a Solidity smart contract, which lacks o. The vulnerability arises from the use of inline assembly in a Solidity smart contract, which lacks overflow protection. This allows an attacker to manipulate the function selector by overflowing the `mul(swapAmountInDataIndex, 0x20)` calculation. The `swapAmountInDataValue` is stored at a memory loc...

Vulnerable code:
```\nif gt(swapAmountInDataValue, 0) {\n    mstore(add(add(ptr, 0x24), mul(swapAmountInDataIndex, 0x20)), swapAmountInDataValue)\n}\n\nsuccess := call(\n    maxGas,\n    target,\n    0, // value\n    ptr, // Inputs are stored at location ptr\n    data.length,\n    0,\n    0\n)\n```
MEDIUM severity: The vulnerability arises when a liquidator is tasked with liquidating a borrower's collateral in a J. The vulnerability arises when a liquidator is tasked with liquidating a borrower's collateral in a JUSDBank contract. In the event of over liquidation, where the liquidator's borrowings exceed the borrower's actual collateral, the liquidator can exploit this vulnerability to avoid paying the borrowe...

Vulnerable code:
```\n} else {\n    liquidateData.actualCollateral = JUSDBorrowed\n       .decimalDiv(priceOff)\n       .decimalDiv(JOJOConstant.ONE - reserve.insuranceFeeRate);\n\n    liquidateData.insuranceFee = JUSDBorrowed\n       .decimalMul(reserve.insuranceFeeRate)\n       .decimalDiv(JOJOConstant.ONE - reserve.insuranceFeeRate);\n\n    liquidateData.actualLiquidatedT0 = liquidatedInfo.t0BorrowBalance;\n    liquidateData.actualLiquidated = JUSDBorrowed;\n\n    liquidateData.liquidatedRemainUSDC = (amount -\n        liquidateData.actualCollateral).decimalMul(price);\n```\n```\nrequire(\n    IERC20(primaryAsset).balanceOf(liquidated) -\n        primaryLiquidatedAmount >=\n    liquidateData.liquidatedRemainUSDC,\n    JUSDErrors.LIQUIDATED_AMOUNT_NOT_ENOUGH\n);\n```
MEDIUM severity: The vulnerability lies in the practice of approving the maximum value of uint256, which is a common . The vulnerability lies in the practice of approving the maximum value of uint256, which is a common technique used to save gas in smart contracts. However, this approach can have severe consequences if the approved contract is compromised. By approving the maximum amount of ERC20 tokens, an attacker...

Vulnerable code:
```\nIERC20(vaultWantToken()).approve(vault, MAX_INT);\n```\n```\nIERC20(vaultInfo.tokenAddress).approve(vaultAddress, type(uint256).max)\n```\n```\nIERC20(LP_TOKEN).safeApprove(ETH_STETH_POOL, type(uint256).max);\n\nIERC20(LP_TOKEN).safeApprove(\n    address(CONVEX_BOOSTER),\n    type(uint256).max\n)\n```\n```\ncrv.safeApprove(address(crveth), type(uint256).max);\n\ncvx.safeApprove(address(cvxeth), type(uint256).max);\n\nldo.safeApprove(address(uniswapRouter), type(uint256).max);\n```\n```\nIERC20(wantTokenL2).safeApprove(\n    address(UniswapV3Controller.uniswapRouter),\n    type(uint256).max\n);\n\nLyraController.sUSD.safeApprove(\n    address(UniswapV3Controller.uniswapRouter),\n    type(uint256).max\n);\n```
MEDIUM severity: The `_convert()` function in the `DAOfiV1Pair` contract is responsible for handling token conversion. The `_convert()` function in the `DAOfiV1Pair` contract is responsible for handling token conversions with varying `decimals()` values. However, it contains a critical flaw that can lead to the loss of funds. The function implicitly returns 0 for any `amount` in three specific scenarios, including w...

Vulnerable code:
```\nfunction _convert(address token, uint256 amount, uint8 resolution, bool to) private view returns (uint256 converted) {\n    uint8 decimals = IERC20(token).decimals();\n    uint256 diff = 0;\n    uint256 factor = 0;\n    converted = 0;\n\n    if (decimals > resolution) {\n        diff = uint256(decimals.sub(resolution));\n        factor = 10 ** diff;\n        if (to && amount >= factor) {\n            converted = amount / factor;\n        } else if (!to) {\n            converted = amount * factor;\n        }\n    } else if (decimals < resolution) {\n        diff = uint256(resolution.sub(decimals));\n        factor = 10 ** diff;\n        if (to) {\n            converted = amount * factor;\n        } else if (!to && amount >= factor) {\n            converted = amount / factor;\n        }\n    }\n}\n```
MEDIUM severity: The `DepotFacet` and `Pipeline` contracts, designed to facilitate the execution of arbitrary actions. The `DepotFacet` and `Pipeline` contracts, designed to facilitate the execution of arbitrary actions in a single transaction, are vulnerable to reentrancy attacks when interacting with untrusted external contracts. This vulnerability arises from the lack of reentrancy guards in the `DepotFacet` and...

Vulnerable code:
```\nfunction advancedPipe(AdvancedPipeCall[] calldata pipes, uint256 value)\n    external\n    payable\n    returns (bytes[] memory results)\n{\n    results = IPipeline(PIPELINE).advancedPipe{value: value}(pipes);\n    LibEth.refundEth();\n}\n```\n```\nfunction refundEth()\n    internal\n{\n    AppStorage storage s = LibAppStorage.diamondStorage();\n    if (address(this).balance > 0 && s.isFarm!= 2) {\n        (bool success,) = msg.sender.call{value: address(this).balance}(\n            new bytes(0)\n        );\n        require(success, "Eth transfer Failed.");\n    }\n}\n```\n```\nfunction advancedPipe(AdvancedPipeCall[] calldata pipes)\n    external\n    payable\n    override\nreturns (bytes[] memory results) {\n    results = new bytes[](pipes.length);\n    for (uint256 i = 0; i < pipes.length; i++) {\n        results[i] = _advancedPipe(pipes[i], results);\n    }\n}\n```
MEDIUM severity: This vulnerability is related to the presence of code snippets intended for testing purposes in the . This vulnerability is related to the presence of code snippets intended for testing purposes in the production code. Specifically, the `onlyTest` modifier, `setTimeExtra` function, and `timeExtra` variable in `getCurrentWeek` and `getNow` functions are not necessary for the code's intended functiona...

Vulnerable code:
```\ndef onlyTest():\n    pass\n```\n```\nfunction setTimeExtra(uint256 timeExtra_) external onlyTest {\n```\n```\nfunction getCurrentWeek() public view returns(uint256) {\n    return (block.timestamp + TIME_OFFSET + timeExtra) / (7 * 86400);\n}\n```\n```\nfunction getNow() public view returns (uint256) {\n    return block.timestamp + timeExtra;\n}\n```
MEDIUM severity: The vulnerability allows an attacker to reset the primaryCredit and secondaryCredit variables for th. The vulnerability allows an attacker to reset the primaryCredit and secondaryCredit variables for the insurance account, which is responsible for covering losses. This is possible when the insurance account's primaryCredit becomes negative due to the liquidation of another account, and the `isSafe`...

Vulnerable code:
```\nfunction handleBadDebt(Types.State storage state, address liquidatedTrader)\n    external\n{\n    if (\n        state.openPositions[liquidatedTrader].length == 0 &&\n       !Liquidation._isSafe(state, liquidatedTrader)\n    ) {\n        int256 primaryCredit = state.primaryCredit[liquidatedTrader];\n        uint256 secondaryCredit = state.secondaryCredit[liquidatedTrader];\n        state.primaryCredit[state.insurance] += primaryCredit;\n        state.secondaryCredit[state.insurance] += secondaryCredit;\n        state.primaryCredit[liquidatedTrader] = 0;\n        state.secondaryCredit[liquidatedTrader] = 0;\n        emit HandleBadDebt(\n            liquidatedTrader,\n            primaryCredit,\n            secondaryCredit\n        );\n    }\n}\n```
MEDIUM severity: The `KeeperFactory` contract contains a vulnerability that allows an attacker to drain all keeper fe. The `KeeperFactory` contract contains a vulnerability that allows an attacker to drain all keeper fees by repeatedly calling the `settle` function with empty arrays as input parameters. This is possible because the `settle` function does not check if the length of the input arrays is zero before pro...

Vulnerable code:
```\nfunction settle(bytes32[] memory ids, IMarket[] memory markets, uint256[] memory versions, uint256[] memory maxCounts)\n    external\n{\n    if (\n        ids.length!= markets.length ||\n        ids.length!= versions.length ||\n        ids.length!= maxCounts.length ||\n        // Prevent calldata stuffing\n        abi.encodeCall(KeeperFactory.settle, (ids, markets, versions, maxCounts)).length!= msg.data.length\n    )\n        revert KeeperFactoryInvalidSettleError();\n\n    for (uint256 i = 0; i < ids.length; i++) {\n        IKeeperOracle(address(oracles[ids[i]])).settle(markets[i], versions[i], maxCounts[i]);\n    }\n}\n```\n```\ninterface IKeeperFactory {\n    function settle(bytes32[] memory ids, IMarket[] memory markets, uint256[] memory versions, uint256[] memory maxCounts) external;\n}\n\ninterface IMarket {\n    function update() external;\n}\n\ncontract AttackContract {\n    address public attacker;\n    address public keeperFactory;\n    IERC20 public keeperToken;\n\n    constructor(address perennialDeployedKeeperFactory, IERC20 _keeperToken) {\n        attacker = msg.sender;\n        keeperFactory = perennialDeployedKeeperFactory;\n        keeperToken = _keeperToken;\n    }\n\n    function attack() external {\n        require(msg.sender == attacker, "not allowed");\n\n        bool canSteal = true;\n\n        // empty arrays as parameters\n        bytes32[] memory ids = [];\n        IMarket[] memory markets = [];\n        uint256[] memory versions = [];\n        uint256[] memory maxCounts = [];\n\n        // perform attack in a loop till all funds are drained or call reverts\n        while (canSteal) {\n            try IKeeperFactory(keeperFactory).settle(ids, markets, versions, maxCounts) {\n                // \n            } catch {\n                canSteal = false;\n            }\n        }\n        keeperToken.transfer(msg.sender, keeperToken.balanceOf(address(this)));\n    }\n}\n```
MEDIUM severity: The `finalizeBlocks` function is responsible for finalizing blocks by submitting proof, block data, . The `finalizeBlocks` function is responsible for finalizing blocks by submitting proof, block data, proof type, and parent state root hash. This process typically occurs every 12 seconds, and under normal circumstances, the system functions as intended. However, when blocks contain a large number of...

Vulnerable code:
```\nfunction finalizeBlocks(\n    BlockData[] calldata _blocksData,\n    bytes calldata _proof,\n    uint256 _proofType,\n    bytes32 _parentStateRootHash\n)\n```
MEDIUM severity: The Premature Liquidation When a Borrower Pays Early vulnerability in TellerV2 markets arises when a. The Premature Liquidation When a Borrower Pays Early vulnerability in TellerV2 markets arises when a borrower makes an early payment within a payment cycle, potentially leading to unintended liquidation in the subsequent payment cycle. This issue is distinct from issue #2, as it exploits user behavi...

Vulnerable code:
```\nreturn (uint32(block.timestamp) - \n        _liquidationDelay - \n        lastRepaidTimestamp(_bidId) > \n        bidDefaultDuration[_bidId]);\n```
MEDIUM severity: The withdrawal mechanism in the provided code is overly complex and vulnerable to potential issues. . The withdrawal mechanism in the provided code is overly complex and vulnerable to potential issues. To initiate a withdrawal, anyone with an account in the `PaymentRegistry` can call the `withdrawDeposit` function, which triggers a multi-step process. The process involves checking if the account is...

Vulnerable code:
```\nfunction withdrawDeposit(\n    address token\n) \nexternal \n{\n    address owner = _getContextAccount();\n    uint256 lockedUntil = deposits[owner].withdrawalLockedUntil[token];\n\n    if (lockedUntil!= 0 && lockedUntil <= now) {\n        deposits[owner].withdrawalLockedUntil[token] = 0;\n\n        address depositAccount = deposits[owner].account;\n        uint256 depositValue;\n\n        if (token == address(0)) {\n            depositValue = depositAccount.balance;\n        } else {\n            depositValue = ERC20Token(token).balanceOf(depositAccount);\n        }\n\n        _transferFromDeposit(\n            depositAccount,\n            owner,\n            token,\n            depositValue\n        );\n\n        emit DepositWithdrawn(\n            depositAccount,\n            owner,\n            token,\n            depositValue\n        );\n    } else {\n        _deployDepositAccount(owner);\n\n        lockedUntil = now.add(depositWithdrawalLockPeriod);\n\n        deposits[owner].withdrawalLockedUntil[token] = lockedUntil;\n\n        emit DepositWithdrawalRequested(\n            deposits[owner].account,\n            owner,\n            token,\n            lockedUntil\n        );\n    }\n}\n```\n```\nif (deposits[sender].withdrawalLockedUntil[token] > 0) {\n    deposits[sender].withdrawalLockedUntil[token] = 0;\n```
MEDIUM severity: The vulnerability is characterized by the absence of checks-effects-interactions pattern in various . The vulnerability is characterized by the absence of checks-effects-interactions pattern in various parts of the Rocket Pool system's smart contracts. This pattern is crucial in ensuring that the contract state is updated before making external calls, thereby preventing reentrancy attacks. \n\nIn th...

Vulnerable code:
```\nfunction close() override external {\n    require(status == MinipoolStatus.Dissolved, "The minipool can only be closed while dissolved");\n    distributeToOwner();\n    RocketMinipoolManagerInterface rocketMinipoolManager = RocketMinipoolManagerInterface(getContractAddress("rocketMinipoolManager"));\n    require(rocketMinipoolManager.getMinipoolExists(address(this)), "Minipool already closed");\n    rocketMinipoolManager.destroyMinipool();\n    nodeDepositBalance = 0;\n    nodeRefundBalance = 0;\n    userDepositBalance = 0;\n    userDepositBalanceLegacy = 0;\n    userDepositAssignedTime = 0;\n}\n```\n```\nwithdrawalBlock = block.number\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    // Record slashing\n    slashed = true;\n}\n```\n```\nuint256 newBondAmount = getUint(keccak256(abi.encodePacked("minipool.bond.reduction.value", msg.sender)));\n\nrequire(rocketNodeDeposit.isValidDepositAmount(newBondAmount), "Invalid bond amount");\n\nuint256 existingBondAmount = minipool.getNodeDepositBalance();\nuint256 delta = existingBondAmount.sub(newBondAmount);\n\naddress nodeAddress = minipool.getNodeAddress();\n\nrocketNodeDeposit.increaseEthMatched(nodeAddress, delta);\n\nrocketNodeDeposit.increaseDepositCreditBalance(nodeAddress, delta);\n\ndeleteUint(keccak256(abi.encodePacked("minipool.bond.reduction.time", msg.sender)));\ndeleteUint(keccak256(abi.encodePacked("minipool.bond.reduction.value", msg.sender)));\n```\n```\nrplContract.inflationMintTokens()\nincrementRewardIndex()\n```