Farseen0/scar-pairs huggingface dataset:
MEDIUM severity: The vulnerability is related to the unsafe downcasting of arithmetic operations in the UserManager r. The vulnerability is related to the unsafe downcasting of arithmetic operations in the UserManager related contract and UToken.sol. Specifically, the code is prone to data loss and potential arithmetic errors due to the truncation of uint256 values to uint96 or uint128.\n\nIn the `stakeWithPermit` f...

Vulnerable code:
```\nfunction stakeWithPermit(\n    uint256 amount,\n    uint256 nonce,\n    uint256 expiry,\n    uint8 v,\n    bytes32 r,\n    bytes32 s\n) external whenNotPaused {\n    IDai erc20Token = IDai(stakingToken);\n    erc20Token.permit(msg.sender, address(this), nonce, expiry, true, v, r, s);\n\n    stake(uint96(amount));\n}\n```\n```\nfunction borrow(address to, uint256 amount) external override onlyMember(msg.sender) whenNotPaused nonReentrant {\n    // Code here\n}\n```\n```\nif (!assetManagerContract.withdraw(underlying, to, amount)) {\n    revert WithdrawFailed();\n}\n\nIUserManager(userManager).updateLocked(msg.sender, uint96(amount + fee), true);\n```\n```\nfunction _repayBorrowFresh(\n    address payer,\n    address borrower,\n    uint256 amount\n) internal {\n```\n```\naccountBorrows[borrower].principal = borrowedAmount - repayAmount;\naccountBorrows[borrower].interest = 0;\n```\n```\nIUserManager(userManager).updateLocked(borrower, uint96(repayAmount - interest), false);\n```\n```\nuint256 voucherIndex = vouchers[borrower].length;\nvoucherIndexes[borrower][staker] = Index(true, uint128(voucherIndex));\nvouchers[borrower].push(Vouch(staker, trustAmount, 0, 0));\n\nuint256 voucheeIndex = voucheesLength;\nvouchees[staker].push(Vouchee(borrower, uint96(voucherIndex)));\nvoucheeIndexes[borrower][staker] = Index(true, uint128(voucheeIndex));\n```\n```\nvouch.lastUpdated = uint64(block.number)\n```
MEDIUM severity: The vulnerability, RocketDAONodeTrustedUpgrade, arises from a critical flaw in the upgrade mechanism. The vulnerability, RocketDAONodeTrustedUpgrade, arises from a critical flaw in the upgrade mechanism of named contracts. Specifically, when upgrading a contract to a new implementation, the existing address is not checked for reuse, allowing an attacker to register the same address to multiple names...

Vulnerable code:
```\nsets contract.exists.0xfefe = true\nsets contract.name.0xfefe = "test"\nsets contract.address.test = "0xfefe"\nsets contract.abi.test = "abi"\n```\n```\nsets contract.exists.0xbadbad = true\nsets contract.name.0xbadbad = "badcontract"\nsets contract.address.badcontract = "0xbadbad"\nsets contract.abi.badcontract = "abi"\n```\n```\noverwrites contract.exists.0xbadbad = true\n    (even though it's already true)\nupdates contract.name.0xbadbad = "test"\n    (overwrites the reference to badcontract; badcontracts config is now inconsistent)\nupdates contract.address.test = 0xbadbad\n    (ok, expected)\nupdates contract.abi.test = "abi"\n    (ok, expected)\nremoves contract.name.0xfefe\n    (ok)\nremoves contract.exists.0xfefe\n    (ok)\n```\n```\nsets contract.exists.0xc0c0 = true\nsets contract.name.0xc0c0 = "test"  # (ok, expected)\nupdates contract.address.test = 0xc0c0  # (ok, expected)\nupdates contract.abi.test = abi  # (ok, expected)\nremoves contract.name.0xbadbad  # (the contract is still registered as badcontract, but is indirectly removed now)\nremoves contract.exists.0xbadbad  # (the contract is still registered as badcontract, but is indirectly removed now)\n```\n```\ncontract.exists = 0xbadbad\ncontract.name = 0xbadbad = "badcontract"\ncontract.address["badcontract"] = 0xbadbad\ncontract.abi["badcontract"] = abi\n```\n```\nrequire(_contractAddress!= address(0x0), "Invalid contract address");\n```\n```\nrequire(_contractAddress!= address(0x0), "Invalid contract address");\nrequire(_contractAddress!= oldContractAddress, "The contract address cannot be set to its current address");\n\nsetBool(keccak256(abi.encodePacked("contract.exists", _contractAddress)), true);\nsetString(keccak256(abi.encodePacked("contract.name", _contractAddress)), _name);\nsetAddress(keccak256(abi.encodePacked("contract.address", _name)), _contractAddress);\nsetString(keccak256(abi.encodePacked("contract.abi", _name)), _contractAbi);\n```
MEDIUM severity: The UniswapIncentive contract's `incentivize` function is vulnerable to an overflow attack due to th. The UniswapIncentive contract's `incentivize` function is vulnerable to an overflow attack due to the use of unchecked arithmetic operations in the `getBuyIncentive` function. This function calculates the buy incentive by casting the `amount` parameter to an `int256` and then performing arithmetic o...

Vulnerable code:
```\nfunction incentivize(\n    address sender,\n    address receiver,\n    address operator,\n    uint amountIn\n) external override onlyFei {\n    updateOracle();\n\n    if (isPair(sender)) {\n        incentivizeBuy(receiver, amountIn);\n    }\n\n    if (isPair(receiver)) {\n        require(\n            isSellAllowlisted(sender) || isSellAllowlisted(operator),\n            "UniswapIncentive: Blocked Fei sender or operator"\n        );\n        incentivizeSell(sender, amountIn);\n    }\n}\n```\n```\nfunction incentivizeBuy(address target, uint amountIn) internal {\n    if (isExemptAddress(target)) {\n        return;\n    }\n\n    (uint incentive, uint32 weight,\n    Decimal.D256 memory initialDeviation,\n    Decimal.D256 memory finalDeviation) = getBuyIncentive(amountIn);\n\n    updateTimeWeight(initialDeviation, finalDeviation, weight);\n    if (incentive!= 0) {\n        fei().mint(target, incentive);\n    }\n}\n```\n```\nfunction getBuyIncentive(uint amount) public view override returns (\n    uint incentive,\n    uint32 weight,\n    Decimal.D256 memory initialDeviation,\n    Decimal.D256 memory finalDeviation\n) {\n    (\n        initialDeviation,\n        finalDeviation\n    ) = getPriceDeviations(-1 * int256(amount));\n}\n```
MEDIUM severity: The `repayAccountPrimeDebtAtSettlement()` function is responsible for calculating the residual cash . The `repayAccountPrimeDebtAtSettlement()` function is responsible for calculating the residual cash to be refunded to a user when settling a Vault Account. However, an incorrect calculation of the `primeCashRefund` value is performed, resulting in the loss of the user's residual cash. Specifically,...

Vulnerable code:
```\nfunction repayAccountPrimeDebtAtSettlement(\n    PrimeRate memory pr,\n    VaultStateStorage storage primeVaultState,\n    uint16 currencyId,\n    address vault,\n    address account,\n    int256 accountPrimeCash,\n    int256 accountPrimeStorageValue\n) internal returns (int256 finalPrimeDebtStorageValue, bool didTransfer) {\n    if (netPrimeDebtRepaid < accountPrimeStorageValue) {\n        // If the net debt change is greater than the debt held by the account, then only\n        // decrease the total prime debt by what is held by the account. The residual amount\n        // will be refunded to the account via a direct transfer.\n        netPrimeDebtChange = accountPrimeStorageValue;\n        finalPrimeDebtStorageValue = 0;\n\n        int256 primeCashRefund = pr.convertFromUnderlying(\n            pr.convertDebtStorageToUnderlying(netPrimeDebtChange.sub(accountPrimeStorageValue))\n        );\n        TokenHandler.withdrawPrimeCash(\n            account, currencyId, primeCashRefund, pr, false\n        );\n        didTransfer = true;\n    } else {\n```
MEDIUM severity: The `lockCapital` mechanism in the ProtectionPool contract is vulnerable to manipulation by an attac. The `lockCapital` mechanism in the ProtectionPool contract is vulnerable to manipulation by an attacker who can exploit the predictability of the timestamp when the pool switches to the `Late` state. This allows the attacker to use a flash loan from a secondary market, such as Uniswap, to claim a sh...

Vulnerable code:
```\nfunction _snapshot() internal returns (uint256) {\n    /// step 1: Capture protection pool's current investors by creating a snapshot of the token balance by using ERC20Snapshot in SToken\n    return _snapshot();\n}\n```\n```\nFile: DefaultStateManager.sol\n\ndef claimableUnlockedCapital(\n    _poolSToken,\n    _seller,\n    _snapshotId,\n    lockedCapital\n) {\n    _claimableUnlockedCapital = (\n        _poolSToken.balanceOfAt(_seller, _snapshotId) *\n        lockedCapital.amount\n    ) /\n    _poolSToken.totalSupplyAt(_snapshotId);\n}\n```
MEDIUM severity: The vulnerability occurs when the `_invariant` function is bypassed for protected position updates, . The vulnerability occurs when the `_invariant` function is bypassed for protected position updates, allowing an attacker to exploit the system by sending a large number of pending position updates. This can lead to a denial-of-service (DoS) attack, as the system becomes overwhelmed by the excessive...

Vulnerable code:
```\nfunction _invariant(\n    Context memory context,\n    address account,\n    Order memory newOrder,\n    Fixed6 collateral,\n    bool protected\n) private view {\n    if (protected) return; // The following invariants do not apply to protected position updates (liquidations)\n\n    if (\n        context.global.currentId > context.global.latestId + context.marketParameter.maxPendingGlobal ||\n        context.local.currentId > context.local.latestId + context.marketParameter.maxPendingLocal\n    ) {\n        revert MarketExceedsPendingIdLimitError();\n    }\n}\n```\n```\n_invariant(context, account, newOrder, collateral, protected);\n\n_store(context.global.currentId, context.currentPosition.global);\n_pendingPositions[account][context.local.currentId].store(context.currentPosition.local);\n```\n```\nfunction _settle(Context memory context, address account) private {\n    while (\n        context.global.currentId!= context.global.latestId &&\n        (nextPosition = _pendingPosition[context.global.latestId + 1].read()).ready(context.latestVersion)\n    ) {\n        _processPositionGlobal(context, context.global.latestId + 1, nextPosition);\n    }\n```\n```\nfunction update(\n    address account,\n    UFixed6 newMaker,\n    UFixed6 newLong,\n    UFixed6 newShort,\n    Fixed6 collateral,\n    bool protect\n) external nonReentrant whenNotPaused {\n    Context memory context = _loadContext(account);\n    _settle(context, account);\n    _update(context, account, newMaker, newLong, newShort, collateral, protect);\n    _saveContext(context, account);\n}\n```
MEDIUM severity: The vulnerability arises when the account being liquidated or referred is the same as the account's . The vulnerability arises when the account being liquidated or referred is the same as the account's own address. During the market settlement process, the `local.claimable` storage is credited to the liquidator or referral's account. However, the in-memory cached copy of the account's local storage...

Vulnerable code:
```\nfunction _credit(address account, UFixed6 amount) private {\n    if (amount.isZero()) return;\n\n    Local memory newLocal = _locals[account].read();\n    newLocal.credit(amount);\n    _locals[account].store(newLocal);\n\n    _credit(liquidators[account][newOrderId], accumulationResult.liquidationFee);\n    _credit(referrers[account][newOrderId], accumulationResult.subtractiveFee);\n```\n```\nfunction _storeContext(Context memory context, address account) private {\n    _global.store(context.global);\n    _locals[account].store(context.local);\n}\n```\n```\nfunction settle(address account) external nonReentrant whenNotPaused {\n    Context memory context = _loadContext(account);\n\n    _settle(context, account);\n\n    _storeContext(context, account);\n}\n```\n```\nit('self-liquidation fees lost', async () => {\n  const POSITION = parse6decimal('100.000');\n  const COLLATERAL = parse6decimal('120');\n\n  function setupOracle(price: string, timestamp: number, nextTimestamp: number) {\n    const oracleVersion = {\n      price: parse6decimal(price),\n      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  dsu.transferFrom.whenCalledWith(user.address, market.address, COLLATERAL.mul(1e12)).returns(true);\n  dsu.transferFrom.whenCalledWith(userB.address, market.address, COLLATERAL.mul(1e12)).returns(true);\n\n  let time = TIMESTAMP;\n\n  setupOracle('1', time, time + 100);\n  await market.connect(user).update(user.address, POSITION, 0, 0, COLLATERAL, false);\n\n  time += 100;\n  setupOracle('1', time, time + 100);\n  await market.connect(userB).update(userB.address, 0, POSITION, 0, COLLATERAL, false);\n\n  time += 100;\n  setupOracle('1', time, time + 100);\n\n  time += 100;\n  setupOracle('0.7', time, time + 100);\n\n  // self-liquidate\n  setupOracle('0.7', time, time + 100);\n  await market.connect(userB).update(userB.address, 0, 0, 0, 0, true);\n\n  // settle liquidation\n  time += 100;\n  setupOracle('0.7', time, time + 100);\n  await market.settle(userB.address);\n  var info = await market.locals(userB.address);\n  console.log("Claimable userB: " + info.claimable);\n})\n```\n```\nClaimable userB: 0\n```
MEDIUM severity: The `setLenderManager` function, used to update the lender manager address of a contract, can lead t. The `setLenderManager` function, used to update the lender manager address of a contract, can lead to unintended consequences when combined with the `claimLoanNFT` and `getLoanLender` functions. Specifically, when the lender manager is changed, repaid assets will be sent to the old lender manager, p...

Vulnerable code:
```\nfunction setLenderManager(address _lenderManager)\n    external\n    reinitializer(8)\n    onlyOwner\n{\n    _setLenderManager(_lenderManager);\n}\n\nfunction _setLenderManager(address _lenderManager)\n    internal\n    onlyInitializing\n{\n    require(\n        _lenderManager.isContract(),\n        "LenderManager must be a contract"\n    );\n    lenderManager = ILenderManager(_lenderManager);\n}\n```\n```\nfunction claimLoanNFT(uint256 _bidId)\n    external\n    acceptedLoan(_bidId, "claimLoanNFT")\n    whenNotPaused\n{\n    Bid storage bid = bids[_bidId];\n\n    address sender = _msgSenderForMarket(bid.marketplaceId);\n    require(sender == bid.lender, "only lender can claim NFT");\n    lenderManager.registerLoan(_bidId, sender);\n    bid.lender = address(lenderManager);\n}\n```\n```\nfunction getLoanLender(uint256 _bidId)\n    public\n    view\n    returns (address lender_)\n{\n    lender_ = bids[_bidId].lender;\n\n    if (lender_ == address(lenderManager)) {\n        return lenderManager.ownerOf(_bidId);\n    }\n}\n\naddress lender = getLoanLender(_bidId);\n\n// Send payment to the lender\nbid.loanDetails.lendingToken.safeTransferFrom(\n    _msgSenderForMarket(bid.marketplaceId),\n    lender,\n    paymentAmount\n);\n```
MEDIUM severity: The vulnerability allows a malicious spender to manipulate the token allowance by front-running call. The vulnerability allows a malicious spender to manipulate the token allowance by front-running calls to modify the allowance, leading to unintended spending and denial-of-service attacks. This occurs due to a race condition in the `ERC20::approve` implementation and its variants, which update the a...

Vulnerable code:
```\nrequire(\n    currentAllowance >= subtractedValue,\n    "Silo: decreased allowance below zero"\n);\n```
MEDIUM severity: When a user initiates a rollover, they are expected to receive the total amount of shares they are e. When a user initiates a rollover, they are expected to receive the total amount of shares they are entitled to, including any winnings from the previous epoch. However, the `mintRollovers` function does not accurately reflect this expectation. Instead, it mints only the original assets requested for...

Vulnerable code:
```\nrolloverQueue[index].assets = _assets;\n```\n```\nif (epochResolved[queue[index].epochId]) {\n    uint256 entitledShares = previewWithdraw(\n        queue[index].epochId,\n        queue[index].assets\n    );\n\n    if (entitledShares > queue[index].assets) {\n        _burn(\n            queue[index].receiver,\n            queue[index].epochId,\n            queue[index].assets\n        );\n    }\n}\n```\n```\nuint256 assetsToMint = queue[index].assets - relayerFee;\n_mintShares(queue[index].receiver, _epochId, assetsToMint);\n```\n```\ndef _burn(_owner, _id, _assets):\n    _burnEmissions(_owner, _id, _assets)\n    entitledShares = uint256(0)\n    entitledEmissions = previewEmissionsWithdraw(_id, _assets)\n    if epochNull[_id] == False:\n        entitledShares = previewWithdraw(_id, _assets)\n    else:\n        entitledShares = _assets\n    if entitledShares > 0:\n        SemiFungibleVault.asset.safeTransfer(_receiver, entitledShares)\n    if entitledEmissions > 0:\n        emissionsToken.safeTransfer(_receiver, entitledEmissions)\n```
MEDIUM severity: The vulnerability lies in the way the `currentMinted` value is updated when the Vault burns TAU toke. The vulnerability lies in the way the `currentMinted` value is updated when the Vault burns TAU tokens. Specifically, when the Vault acts on behalf of a user to burn TAU, the `_decreaseCurrentMinted` function is called, which incorrectly updates the `currentMinted` value.\n\nThe issue arises because...

Vulnerable code:
```\nfunction _decreaseCurrentMinted(address account, uint256 amount) internal virtual {\n    uint256 accountMinted = currentMinted[account];\n    if (accountMinted >= amount) {\n        currentMinted[msg.sender] = accountMinted - amount;\n    }\n}\n```
MEDIUM severity: The `addExternalErc721Award` function in the PeriodicPriceStrategy contract allows the prize-strateg. The `addExternalErc721Award` function in the PeriodicPriceStrategy contract allows the prize-strategy owner or listener to add an external ERC721 token as an additional prize that can be awarded. This function does not validate whether the provided `tokenIds` are unique or if they are actually owned...

Vulnerable code:
```\nfunction addExternalErc721Award(address _externalErc721, uint256[] calldata _tokenIds) external onlyOwnerOrListener {\n    require(prizePool.canAwardExternal(_externalErc721), "PeriodicPrizeStrategy/cannot-award-external");\n\n    if (!externalErc721s.contains(_externalErc721)) {\n        externalErc721s.addAddress(_externalErc721);\n    }\n\n    for (uint256 i = 0; i < _tokenIds.length; i++) {\n        uint256 tokenId = _tokenIds[i];\n        require(IERC721(_externalErc721).ownerOf(tokenId) == address(prizePool), "PeriodicPrizeStrategy/unavailable-token");\n        externalErc721TokenIds[_externalErc721].push(tokenId);\n    }\n\n    emit ExternalErc721AwardAdded(_externalErc721, _tokenIds);\n}\n```\n```\nfunction _awardExternalErc721s(address winner) internal {\n    address currentToken = externalErc721s.start();\n    while (currentToken!= address(0) && currentToken!= externalErc721s.end()) {\n        uint256 balance = IERC721(currentToken).balanceOf(address(prizePool));\n        if (balance > 0) {\n            prizePool.awardExternalERC721(winner, currentToken, externalErc721TokenIds[currentToken]);\n            delete externalErc721TokenIds[currentToken];\n        }\n        currentToken = externalErc721s.next(currentToken);\n    }\n    externalErc721s.clearAll();\n}\n```\n```\nfunction awardExternalERC721(\n  address to,\n  address externalToken,\n  uint256[] calldata tokenIds\n)\n  external\n  override\n  onlyPrizeStrategy\n{\n  require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token");\n\n  if (tokenIds.length == 0) {\n    return;\n  }\n\n  for (uint256 i = 0; i < tokenIds.length; i++) {\n    IERC721(externalToken).transferFrom(address(this), to, tokenIds[i]);\n  }\n\n  emit AwardedExternalERC721(to, externalToken, tokenIds);\n}\n```
MEDIUM severity: The vulnerability in Rocket Pool's unstaking mechanism allows for the possibility of failed unstakin. The vulnerability in Rocket Pool's unstaking mechanism allows for the possibility of failed unstaking transactions when the rEth contract and deposit pool are depleted. This occurs when users attempt to unstake their Ethereum (ETH) using Rocket Pool, as the protocol relies on these pools to source E...

Vulnerable code:
```\nfunction testWithdrawETHfromRocketPool() public {\n    string memory MAINNET_RPC_URL = vm.envString("MAINNET_RPC_URL");\n    uint256 mainnetFork = vm.createFork(MAINNET_RPC_URL, 15361748);\n\n    RocketTokenRETHInterface rEth = RocketTokenRETHInterface(0xae78736Cd615f374D3085123A210448E74Fc6393);\n    vm.selectFork(mainnetFork);\n\n    uint totalCollateral = rEth.getTotalCollateral();\n    assertEq(totalCollateral, 0); // pools are empty\n\n    address owner = 0x50A78DFb9F5CC22ac8ffA90FA2B6C595881CCb97; // has rEth at block 15361748\n    uint rEthBalance = rEth.balanceOf(owner);\n    assertGt(rEthBalance, 0);\n\n    vm.expectRevert("Insufficient ETH balance for exchange");\n    vm.prank(owner);\n    rEth.burn(rEthBalance);\n}\n```
MEDIUM severity: The vulnerability lies in the `_auctionPrice()` function of the `Auctions.sol` contract, which calcu. The vulnerability lies in the `_auctionPrice()` function of the `Auctions.sol` contract, which calculates the price of auctioned assets for the taker. This function does not consider the floor price of the pool, which can lead to a situation where the pool becomes insolvent. \n\nWhen a borrower cann...

Vulnerable code:
```\nfunction testInsolvency() public {\n    // ============== Setup Scenario ==============\n    uint256 interestRateOne = 0.05 * 10**18; \n    address poolThreeAddr = erc20PoolFactory.deployPool(address(dai), address(weth), interestRateOne);\n    ERC20Pool poolThree = ERC20Pool(address(poolThreeAddr));\n    vm.label(poolThreeAddr, "DAI / WETH Pool Three");\n\n    // Setup scenario and send liquidity providers some tokens\n    vm.startPrank(address(daiDoner));\n    dai.transfer(address(charlie), 3200 ether);\n    vm.stopPrank();\n\n    vm.startPrank(address(wethDoner));\n    weth.transfer(address(bob), 1000 ether);\n    vm.stopPrank();\n\n    // ==============================================\n\n\n    // Start Scenario\n    uint256 fenwick = 5635;\n\n    vm.startPrank(address(alice));\n    weth.deposit{value: 2 ether}();\n    weth.approve(address(poolThree), 2.226 ether);\n    poolThree.addQuoteToken(2 ether, fenwick); \n    vm.stopPrank();\n\n    vm.startPrank(address(bob));\n    weth.deposit{value: 9 ether}();\n    weth.approve(address(poolThree), 9 ether);\n    poolThree.addQuoteToken(9 ether, fenwick); \n    vm.stopPrank();\n\n    assertEq(weth.balanceOf(address(poolThree)), 11 ether);\n\n    // ======================== start testing ========================\n\n    vm.startPrank(address(bob));\n    bytes32 poolSubsetHashes = keccak256("ERC20_NON_SUBSET_HASH");\n    IPositionManagerOwnerActions.MintParams memory mp = IPositionManagerOwnerActions.MintParams({\n        recipient: address(bob),\n        pool: address(poolThree),\n        poolSubsetHash: poolSubsetHashes\n    });\n    positionManager.mint(mp);\n    positionManager.setApprovalForAll(address(rewardsManager), true);\n    rewardsManager.stake(1);\n    vm.stopPrank();\n\n    assertEq(dai.balanceOf(address(charlie)), 3200 ether);\n    vm.startPrank(address(charlie)); // Charlie runs away with the weth tokens\n    dai.approve(address(poolThree), 3200 ether);\n    poolThree.drawDebt(address(charlie), 2 ether, fenwick, 3200 ether);\n    vm.stopPrank();\n\n    vm.warp(block.timestamp + 62\n```