Farseen0/scar-pairs huggingface dataset:
MEDIUM severity: The `rescueFunds` function in the contract allows the owner to withdraw any funds that have been acc. The `rescueFunds` function in the contract allows the owner to withdraw any funds that have been accidentally transferred to the pool. This function can be called by the owner to manually transfer funds out of the pool, but it lacks any restrictions on which funds can be withdrawn or which token can...

Vulnerable code:
```\nfunction rescueFunds(IERC20 token, uint256 amount) external nonReentrant onlyOwner {\n    uint256 balance0 = token0.uniBalanceOf(address(this));\n    uint256 balance1 = token1.uniBalanceOf(address(this));\n\n    token.uniTransfer(msg.sender, amount);\n\n    require(token0.uniBalanceOf(address(this)) >= balance0, "Mooniswap: access denied");\n    require(token1.uniBalanceOf(address(this)) >= balance1, "Mooniswap: access denied");\n    require(balanceOf(address(this)) >= _BASE_SUPPLY, "Mooniswap: access denied");\n}\n```
MEDIUM severity: The vulnerability lies in the calculation of the maximum redeem amount (`maxRedeem`) in the Vault's . The vulnerability lies in the calculation of the maximum redeem amount (`maxRedeem`) in the Vault's redemption process. The `maxRedeem` is limited by the smallest position size in each underlying market, which can lead to an unexpectedly small maximum redeem amount, even when the Total Value Locked...

Vulnerable code:
```\nUFixed6 collateral = marketContext.currentPosition.maker\n   .sub(marketContext.currentPosition.net()\n       .min(marketContext.currentPosition.maker))  // available maker\n   .min(marketContext.closable.mul(StrategyLib.LEVERAGE_BUFFER))\n   .muldiv(marketContext.latestPrice.abs(), registration.leverage)  // available collateral\n   .muldiv(totalWeight, registration.weight);\n\nredemptionAssets = redemptionAssets.min(collateral);\n```
MEDIUM severity: The `claimRewards()` function is susceptible to a potential issue when calculating the rewards per c. The `claimRewards()` function is susceptible to a potential issue when calculating the rewards per cycle. The formula used to calculate `rewards` is `rewards` = `((rewardsPerTokenEnd - userRewardsClaimed) * stakeBalance[msg.sender]) / 10 ** stakedTokenDecimals`. This calculation can result in a situ...

Vulnerable code:
```\nfunction _claimEpochRewards(uint48 epoch_) internal returns (uint256) {\n    uint256 rewards = ((rewardsPerTokenEnd - userRewardsClaimed) * stakeBalance[msg.sender]) / 10 ** stakedTokenDecimals;\n    // Mint the option token on the teller\n    // This transfers the reward amount of payout tokens to the option teller in exchange for the amount of option tokens\n    payoutToken.approve(address(optionTeller), rewards);\n    optionTeller.create(optionToken, rewards);\n}\n```
MEDIUM severity: The inability to deposit into the Tranche/Adaptor under certain conditions can have severe implicati. The inability to deposit into the Tranche/Adaptor under certain conditions can have severe implications for the protocol's core functionality. The minting of PT and YT is a critical feature, and without it, the protocol would cease to operate. \n\nThe issue arises when the `stakeAmount` is set to ze...

Vulnerable code:
```\nFile: BaseLSTAdapter.sol\n\nfunction prefundedDeposit() external nonReentrant returns (uint256, uint256) {\n    uint256 stakeAmount;\n    unchecked {\n        stakeAmount = availableEth + queueEthCache - targetBufferEth; // non-zero, no underflow\n    }\n    // If the stake amount exceeds 95% of the available ETH, cap the stake amount.\n    if (stakeAmount > (availableEth * 95) / 100) {\n        stakeAmount = (availableEth * 95) / 100; // max 95% of the available ETH\n    }\n\n    // Deposit into the yield source\n    // Actual amount of ETH spent may be less than the requested amount.\n    stakeAmount = _stake(stakeAmount); // stake amount can be 0\n```\n```\n/// @inheritdoc BaseLSTAdapter\n/// @dev Lido has a limit on the amount of ETH that can be staked.\n/// @dev Need to check the current staking limit before staking to prevent DoS.\n\nfunction _stake(uint256 stakeAmount) internal override returns (uint256) {\n    uint256 stakeLimit = STETH.getCurrentStakeLimit();\n    if (stakeAmount > stakeLimit) {\n        // Cap stake amount\n        stakeAmount = stakeLimit;\n    }\n\n    IWETH9(Constants.WETH).withdraw(stakeAmount);\n    uint256 _stETHAmt = STETH.submit{value: stakeAmount}(address(this));\n\n    if (_stETHAmt == 0) revert InvariantViolation();\n    return stakeAmount;\n}\n```\n```\nFile: SFrxETHAdapter.sol\n\nfunction _stake(uint256 stakeAmount) internal override returns (uint256) {\n    IWETH9(Constants.WETH).withdraw(stakeAmount);\n    FRXETH_MINTER.submit{value: stakeAmount}();\n    uint256 received = STAKED_FRXETH.deposit(stakeAmount, address(this));\n    if (received == 0) revert InvariantViolation();\n\n    return stakeAmount;\n```\n```\nfunction _submit(address recipient) internal nonReentrant {\n    require(!submitPaused, "Submit is paused");\n    require(msg.value!= 0, "Cannot submit 0");\n}\n```
MEDIUM severity: The MultiInvoker's `_latest()` function is responsible for calculating the `closableAmount` variable. The MultiInvoker's `_latest()` function is responsible for calculating the `closableAmount` variable, which is used in various judgments, including `_liquidationFee()`. However, the calculation logic in `_latest()` contains an error. Specifically, the `previousMagnitude` variable is incorrectly set...

Vulnerable code:
```\nfunction _processPendingPosition(Context memory context, Position memory newPendingPosition) private {\n    context.pendingCollateral = context.pendingCollateral\n       .sub(newPendingPosition.fee)\n       .sub(Fixed6Lib.from(newPendingPosition.keeper));\n\n    context.closable = context.closable\n       .sub(context.previousPendingMagnitude\n           .sub(newPendingPosition.magnitude().min(context.previousPendingMagnitude)));\n\n    context.previousPendingMagnitude = newPendingPosition.magnitude();\n\n    if (context.previousPendingMagnitude.gt(context.maxPendingMagnitude)) {\n        context.maxPendingMagnitude = newPendingPosition.magnitude();\n    }\n}\n```\n```\nfunction _latest(\n    IMarket market,\n    address account\n) internal view returns (Position memory latestPosition, Fixed6 latestPrice, UFixed6 closableAmount) {\n    // load latest price\n    OracleVersion memory latestOracleVersion = market.oracle().latest();\n    latestPrice = latestOracleVersion.price;\n    IPayoffProvider payoff = market.payoff();\n    if (address(payoff)!= address(0)) {\n        latestPrice = payoff.payoff(latestPrice);\n    }\n\n    // load latest settled position\n    uint256 latestTimestamp = latestOracleVersion.timestamp;\n    latestPosition = market.positions(account);\n    closableAmount = latestPosition.magnitude();\n    UFixed6 previousMagnitude = closableAmount;\n\n    // scan pending position for any ready-to-be-settled positions\n    Local memory local = market.locals(account);\n    for (uint256 id = local.latestId + 1; id <= local.currentId; id++) {\n        // load pending position\n        Position memory pendingPosition = market.pendingPositions(account, id);\n        pendingPosition.adjust(latestPosition);\n\n        // virtual settlement\n        if (pendingPosition.timestamp <= latestTimestamp) {\n            if (!market.oracle().at(pendingPosition.timestamp).valid) {\n                latestPosition.invalidate(pendingPosition);\n            }\n            latestPosition.update(pendingPosition);\n\n            previousMagnitude = latestPosition.magnitude();\n            closableAmount = previousMagnitude;\n        } else {\n            closableAmount = closableAmount.sub(previousMagnitude.sub(pendingPosition.magnitude().min(previousMagnitude)));\n            previousMagnitude = latestPosition.magnitude();\n        }\n    }\n}\n```
MEDIUM severity: The Quadratic Voting Strategy (QVS) implementation in the provided code snippet contains a critical . The Quadratic Voting Strategy (QVS) implementation in the provided code snippet contains a critical flaw that can lead to an exponential inflation of voice credits for each recipient. This issue arises from the accumulation of previously cast credits in the `_allocator.voiceCreditsCastToRecipient` m...

Vulnerable code:
```\nfunction _qv_allocate(\n) internal onlyActiveAllocation {\n    uint256 creditsCastToRecipient = _allocator.voiceCreditsCastToRecipient[_recipientId];\n    // get the total credits and calculate the vote result\n    uint256 totalCredits = _voiceCreditsToAllocate + creditsCastToRecipient;\n    //E update allocator mapping voice for this recipient\n    _allocator.voiceCreditsCastToRecipient[_recipientId] += totalCredits; //E @question should be only _voiceCreditsToAllocate\n}\n```\n```\n_allocator.voiceCreditsCastToRecipient[_recipientId] = \n    _allocator.voiceCreditsCastToRecipient[_recipientId] + \n    _voiceCreditsToAllocate + \n    _allocator.voiceCreditsCastToRecipient[_recipientId];\n```
MEDIUM severity: The ERC20Lockable contract contains a vulnerability in its implementation of the `_is_locked` variab. The ERC20Lockable contract contains a vulnerability in its implementation of the `_is_locked` variable and the `onlyUnlocked` modifier. Specifically, the `Vega_Token.is_tradable()` function returns an incorrect result when the token's unlock time has passed, but the owner has not manually unlocked t...

Vulnerable code:
```\n/**\n * @dev locked status, only applicable before unlock_date\n */\nbool public _is_locked = true;\n\n/**\n * @dev Modifier that only allows function to run if either token is unlocked or time has expired.\n * Throws if called while token is locked.\n */\nmodifier onlyUnlocked() {\n    require(!_is_locked || now > unlock_date);\n    _\n}\n\n/**\n * @dev Internal function that unlocks token. Can only be ran before expiration (give that it's irrelevant after)\n */\nfunction _unlock() internal {\n    require(now <= unlock_date);\n    _is_locked = false;\n}\n```
MEDIUM severity: The `getCollateral` and `getAsset` functions of the AssetTotsDaiLeverageExecutor contract suffer fro. The `getCollateral` and `getAsset` functions of the AssetTotsDaiLeverageExecutor contract suffer from a data decoding issue. Specifically, the `getCollateral` function decodes the input data using the `SLeverageSwapData` struct before passing it to the `_swapAndTransferToSender` function. However, t...

Vulnerable code:
```\nSLeverageSwapData memory swapData = abi.decode(data, (SLeverageSwapData));\n\nuint256 daiAmount = \n    _swapAndTransferToSender(false, assetAddress, daiAddress, assetAmountIn, swapData.swapperData);\n```\n```\nfunction _swapAndTransferToSender(\n    bool sendBack,\n    address tokenIn,\n    address tokenOut,\n    uint256 amountIn,\n    bytes memory data\n) internal returns (uint256 amountOut) {\n    SLeverageSwapData memory swapData = abi.decode(data, (SLeverageSwapData));\n\n    // rest of code\n}\n```
MEDIUM severity: The protocol's design pattern, which involves a two-step process for user deposits and withdrawals, . The protocol's design pattern, which involves a two-step process for user deposits and withdrawals, is vulnerable to a cheap griefing attack that can lead to denial-of-service (DoS). This attack exploits the fact that the system's status variable is not properly synchronized, allowing an attacker to...

Vulnerable code:
```\nfunction deposit(\n  GMXTypes.Store storage self,\n  GMXTypes.DepositParams memory dp,\n  bool isNative\n) external {\n  GMXChecks.beforeDepositChecks(self, dp.depositValue);\n\n  self.status = GMXTypes.Status.Deposit;\n```\n```\nfunction beforeDepositChecks(\n    GMXTypes.Store storage self,\n    uint256 depositValue\n) external view {\n    if (self.status!= GMXTypes.Status.Open)\n        revert Errors.NotAllowedInCurrentVaultStatus();\n}\n```
MEDIUM severity: The `BytesParsing::sliceUnchecked` function is vulnerable to potentially dangerous out-of-bounds mem. The `BytesParsing::sliceUnchecked` function is vulnerable to potentially dangerous out-of-bounds memory access due to the lack of validation on the `length` of the `encoded` bytes parameter. This function is designed to slice a portion of the `encoded` bytes, starting from the specified `offset` and...

Vulnerable code:
```\nfunction sliceUnchecked(bytes memory encoded, uint256 offset, uint256 length)\n    internal\n    pure\n    returns (bytes memory ret, uint256 nextOffset)\n{\n    if (length == 0) {\n        return (new bytes(0), offset);\n    }\n\n    assembly {\n        nextOffset := add(offset, length)\n        ret := mload(freeMemoryPtr)\n\n        let shift := and(length, 31)\n        if iszero(shift) {\n            shift := 32\n        }\n\n        let dest := add(ret, shift)\n        let end := add(dest, length)\n        for (\n            let src := add(add(encoded, shift), offset);\n            lt(dest, end);\n            src := add(src, 32),\n            dest := add(dest, 32)\n        ) {\n            mstore(dest, mload(src))\n        }\n\n        mstore(ret, length)\n        mstore(freeMemoryPtr, and(add(dest, 31), not(31)))\n    }\n}\n```\n```\nfunction slice(bytes memory encoded, uint256 offset, uint256 length)\n    internal\n    pure\n    returns (bytes memory ret, uint256 nextOffset)\n{\n    (ret, nextOffset) = sliceUnchecked(encoded, offset, length);\n    checkBound(nextOffset, encoded.length);\n}\n```
MEDIUM severity: The deposit method in this smart contract is vulnerable to an arithmetic calculation error. The meth. The deposit method in this smart contract is vulnerable to an arithmetic calculation error. The method calculates the net amount transferred from the user by subtracting the `reservedFunds` from the `balanceBefore` and `balanceAfter` variables. However, this calculation is unnecessary and can lead t...

Vulnerable code:
```\nuint256 balanceBefore = getVaultBalance() - reservedFunds;\nvaultCurrency.safeTransferFrom(msg.sender, address(this), _amount);\nuint256 balanceAfter = getVaultBalance() - reservedFunds;\nuint256 amount = balanceAfter - balanceBefore;\n```
MEDIUM severity: The `SwapperCallbackValidation` library, intended to ensure secure callback functionality in contrac. The `SwapperCallbackValidation` library, intended to ensure secure callback functionality in contracts, has a critical flaw. The `verifyCallback` function, responsible for verifying the legitimacy of callback calls, does not provide adequate protection. This vulnerability allows any user to bypass t...

Vulnerable code:
```\nfunction verifyCallback(\n    SwapperFactory factory_,\n    SwapperImpl swapper_\n) internal view returns (bool valid) {\n    return factory_.isSwapper(swapper_);\n}\n```\n```\nSwapperImpl swapper = SwapperImpl(msg.sender);\nif (!swapperFactory.verifyCallback(swapper)) {\n    revert Unauthorized();\n}\n```\n```\nfunction execCalls(Call[] calldata calls_)\n    external\n    payable\n    onlyOwner\n    returns (uint256 blockNumber, bytes[] memory returnData)\n{\n    blockNumber = block.number;\n    uint256 length = calls_.length;\n    returnData = new bytes[](length);\n\n    bool success;\n    for (uint256 i = 0; i < length) {\n        Call calldata calli = calls_[i];\n        (success, returnData[i]) = calli.to.call{value: calli.value}(calli.data);\n        require(success, string(returnData[i]));\n\n        unchecked {\n            i++;\n        }\n    }\n\n    emit ExecCalls(calls_);\n}\n```
MEDIUM severity: The NTT Manager's pause functionality, exposed through the `NttManagerState::pause` method, allows a. The NTT Manager's pause functionality, exposed through the `NttManagerState::pause` method, allows authorized actors to temporarily halt the manager's operations. However, this pause mechanism lacks a corresponding unpause capability, rendering it impossible to resume the manager's activities once i...

Vulnerable code:
```\nfunction pause() public {\n    if (msg.sender == owner || msg.sender == pauser) {\n        _pause();\n    }\n}\n```
MEDIUM severity: The contract `SushiYieldSource` initializes two state variables, `sushiBar` and `sushiAddr`, in its . The contract `SushiYieldSource` initializes two state variables, `sushiBar` and `sushiAddr`, in its constructor and assigns them the values `_sushiBar` and `_sushiAddr`, respectively. However, these variables are not declared as immutable, which means they can be modified after the contract's deploy...

Vulnerable code:
```\ncontract SushiYieldSource is IYieldSource {\n    using SafeMath for uint256;\n\n    address public sushiBar;\n    address public sushiAddr;\n    mapping(address => uint256) public balances;\n\n    constructor(address _sushiBar, address _sushiAddr) public {\n        sushiBar = _sushiBar;\n        sushiAddr = _sushiAddr;\n    }\n}\n```
MEDIUM severity: The `_cacheFundraisingApps` and `_cacheFundraisingParams` methods in the EOPBCTemplate contract appe. The `_cacheFundraisingApps` and `_cacheFundraisingParams` methods in the EOPBCTemplate contract appear to be misleadingly named, as they do not actually cache parameters as state variables. Instead, these methods simply return memory structs, which are temporary data structures that are not stored i...

Vulnerable code:
```\nfunction _cacheFundraisingApps(\n    address _reserve,\n    address _presale,\n    address _marketMaker,\n    address _tap,\n    address _controller,\n    address _tokenManager\n)\n    internal\n    returns (FundraisingApps memory fundraisingApps)\n{\n    fundraisingApps.reserve = _reserve;\n    fundraisingApps.presale = _presale;\n    fundraisingApps.marketMaker = _marketMaker;\n    fundraisingApps.tap = _tap;\n    fundraisingApps.controller = _controller;\n    fundraisingApps.bondedTokenManager = _tokenManager;\n}\n\nfunction _cacheFundraisingParams(\n    address _owner,\n    string memory _id,\n    ERC20 _collateralToken,\n    MiniMeToken _bondedToken,\n    uint64 _period,\n    uint256 _exchangeRate,\n    uint64 _openDate,\n    uint256 _reserveRatio,\n    uint256 _batchBlocks,\n    uint256 _slippage\n)\n    internal\n    returns (FundraisingParams memory fundraisingParams)\n{\n    fundraisingParams = FundraisingParams({\n        owner: _owner,\n        id: _id,\n        collateralToken: _collateralToken,\n        bondedToken: _bondedToken,\n        period: _period,\n        exchangeRate: _exchangeRate,\n        openDate: _openDate,\n        reserveRatio: _reserveRatio,\n        batchBlocks: _batchBlocks,\n        slippage: _slippage\n    });\n}\n```
MEDIUM severity: The `functionDelegateCall` helper function is designed to ensure that the target being called is a c. The `functionDelegateCall` helper function is designed to ensure that the target being called is a contract before executing a delegatecall. However, a critical safety check is compromised due to the absence of the `revert` keyword. This oversight allows non-contracts to be passed as targets, which...

Vulnerable code:
```\nif (!isContract(target)) {\n    throw new Errors.AddressNotContract();\n}\n```\n```\n(bool success,) = target.delegatecall(data);\nrequire(success, "CALL_FAILED");\n```
MEDIUM severity: The vulnerability allows a malicious actor to prevent the migration process by intentionally calling. The vulnerability allows a malicious actor to prevent the migration process by intentionally calling a non-existent function in the `OVM_L2ToL1MessagePasser` contract. This malicious actor can manipulate the collected witness data by storing a message that does not correspond to a valid function in...

Vulnerable code:
```\nfunc (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) {\n    if addr == dump.MessagePasserAddress {\n        statedumper.WriteMessage(caller.Address(), input)\n    }\n```\n```\nmethod, err := abi.MethodById(msgB[:4])\nif err!= nil {\n    return nil, nil, fmt.Errorf("failed to get method: %w", err)\n}\n\nout, err := method.Inputs.Unpack(msgB[4:])\nif err!= nil {\n    return nil, nil, fmt.Errorf("failed to unpack: %w", err)\n}\n```
MEDIUM severity: The `roll` function in the `AutoRoller.sol` contract is vulnerable to a reentrancy attack due to the. The `roll` function in the `AutoRoller.sol` contract is vulnerable to a reentrancy attack due to the way it handles the `lastSettle` variable. When `lastSettle` is zero, the contract attempts to deposit a small amount of tokens and mint shares to the address zero. This is done to prevent the contrac...

Vulnerable code:
```\nfunction roll() external {\n    if (maturity!= MATURITY_NOT_SET) {\n        revert RollWindowNotOpen();\n    }\n\n    if (lastSettle == 0) {\n        // If this is the first roll, lock some shares in by minting them for the zero address.\n        // This prevents the contract from reaching an empty state during future active periods.\n        deposit(firstDeposit, address(0));\n    } else if (lastSettle + cooldown > block.timestamp) {\n        revert RollWindowNotOpen();\n    }\n\n    lastRoller = msg.sender;\n    adapter.openSponsorWindow();\n}\n```\n```\ndeposit(firstDeposit, address(0))\n```\n```\nfirstDeposit = (0.01e18 - 1) / scalingFactor + 1\n```\n```\nfunction deposit(uint256 assets, address receiver) public virtual returns (uint256 shares) {\n    require((shares = previewDeposit(assets))!= 0, "ZERO_SHARES");\n\n    asset.safeTransferFrom(msg.sender, address(this), assets);\n\n    _mint(receiver, shares);\n\n    emit Deposit(msg.sender, receiver, assets, shares);\n\n    afterDeposit(assets, shares);\n}\n```\n```\nrequire((shares = previewDeposit(assets))!= 0, "ZERO_SHARES");\n\nrequire(asset.safeTransferFrom(msg.sender, address(this), assets));\n```\n```\nfunction previewDeposit(uint256 assets) public view override returns (uint256) {\n    if (maturity == MATURITY_NOT_SET) {\n        return super.previewDeposit(assets);\n    } else {\n        Space _space = space;\n        (uint256 ptReserves, uint256 targetReserves) = _getSpaceReserves();\n\n        uint256 previewedLPBal = (assets - _getTargetForIssuance(ptReserves, targetReserves, assets, adapter.scaleStored()))\n           .mulDivDown(_space.adjustedTotalSupply(), targetReserves);\n\n        uint256 shares = previewedLPBal.mulDivDown(totalSupply, _space.balanceOf(address(this)));\n        return shares;\n    }\n}\n```
MEDIUM severity: The `chargeFundingRate` function in the `PartyBFacetImpl` contract is vulnerable to a potential issu. The `chargeFundingRate` function in the `PartyBFacetImpl` contract is vulnerable to a potential issue. The function is designed to increment the `partyANonces` counter for `partyA` when the `partyBAvailableBalance` and `partyAAvailableBalance` are greater than or equal to 0, indicating that both par...

Vulnerable code:
```\nfunction chargeFundingRate(\n    address partyA,\n    uint256[] memory quoteIds,\n    int256[] memory rates,\n    PairUpnlSig memory upnlSig\n) internal {\n    LibMuon.verifyPairUpnl(upnlSig, msg.sender, partyA);\n    require(quoteIds.length == rates.length, "PartyBFacet: Length not match");\n    int256 partyBAvailableBalance = LibAccount.partyBAvailableBalanceForLiquidation(\n        upnlSig.upnlPartyB,\n        msg.sender,\n        partyA\n    );\n    int256 partyAAvailableBalance = LibAccount.partyAAvailableBalanceForLiquidation(\n        upnlSig.upnlPartyA,\n        partyA\n    );\n    uint256 epochDuration;\n    uint256 windowTime;\n\n    for (uint256 i = 0; i < quoteIds.length; i++) {\n        // rest of code\n    }\n\n    require(partyAAvailableBalance >= 0, "PartyBFacet: PartyA will be insolvent");\n    require(partyBAvailableBalance >= 0, "PartyBFacet: PartyB will be insolvent");\n    AccountStorage.layout().partyBNonces[msg.sender][partyA] += 1;\n    AccountStorage.layout().partyANonces[partyA] += 1;\n}\n```\n```\nfunction forceClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal {\n    AccountStorage.Layout storage accountLayout = AccountStorage.layout();\n    MAStorage.Layout storage maLayout = MAStorage.layout();\n    Quote storage quote = QuoteStorage.layout().quotes[quoteId];\n\n    LibMuon.verifyPairUpnlAndPrice(upnlSig, quote.partyB, quote.partyA, quote.symbolId);\n}\n```