Farseen0/scar-pairs huggingface dataset:
MEDIUM severity: The Controller contract in this system is responsible for managing the flow of treasury funds. Howev. The Controller contract in this system is responsible for managing the flow of treasury funds. However, it has a critical flaw in its design. When sending treasury funds, the Controller uses its own immutable `treasury` address, which is set during its initialization, instead of using the treasury a...

Vulnerable code:
```\nconstructor(\n    address _treasury\n) public SemiFungibleVault(IERC20(_assetAddress), _name, _symbol, _tokenURI) {\n    treasury = _treasury;\n    whitelistedAddresses[_treasury] = true;\n}\n\nfunction setTreasury(address _treasury) public onlyFactory {\n    if (_treasury == address(0)) {\n        revert AddressZero();\n    }\n    treasury = _treasury;\n}\n```\n```\nconstructor(\n    address _treasury\n) {\n    treasury = _treasury;\n}\n\nfunction triggerEndEpoch(uint256 _marketId, uint256 _epochId) public {\n    // send premium fees to treasury and remaining TVL to collateral vault\n    premiumVault.sendTokens(_epochId, premiumFee, treasury);\n    // strike price reached so collateral is entitled to collateralTVLAfterFee\n    premiumVault.sendTokens(\n        _epochId,\n        premiumTVLAfterFee,\n        address(collateralVault)\n    );\n}\n```
MEDIUM severity: The withdrawal request override vulnerability occurs when a user initiates a withdrawal request duri. The withdrawal request override vulnerability occurs when a user initiates a withdrawal request during the initial phase, when the `rebalancingPeriod` is set to 0. This allows for the possibility of overriding an existing withdrawal request, which can lead to unintended consequences.\n\nIn the provi...

Vulnerable code:
```\nfunction withdrawalRequest(\n    uint256 _amount\n) external nonReentrant onlyWhenVaultIsOn returns (uint256 value) {\n    UserInfo storage user = userInfo[msg.sender];\n    require(user.withdrawalRequestPeriod == 0, "Already a request");\n\n    value = (_amount * exchangeRate) / (10 ** decimals());\n\n    _burn(msg.sender, _amount);\n\n    user.withdrawalAllowance = value;\n    user.withdrawalRequestPeriod = rebalancingPeriod;\n    totalWithdrawalRequests += value;\n}\n```
MEDIUM severity: The `PauseManager` and `RateLimiter` contracts contain vulnerabilities that can lead to false alarms. The `PauseManager` and `RateLimiter` contracts contain vulnerabilities that can lead to false alarms and unnecessary panic. The `PauseManager` allows the `PAUSE_MANAGER_ROLE` to pause or unpause a type without checking if the type has already been paused or unpaused, resulting in unnecessary event e...

Vulnerable code:
```\nfunction pauseByType(bytes32 _pauseType) external onlyRole(PAUSE_MANAGER_ROLE) {\n    pauseTypeStatuses[_pauseType] = true;\n    emit Paused(_msgSender(), _pauseType);\n}\n```\n```\nfunction unPauseByType(bytes32 _pauseType) external onlyRole(PAUSE_MANAGER_ROLE) {\n    pauseTypeStatuses[_pauseType] = false;\n    emit UnPaused(_msgSender(), _pauseType);\n}\n```\n```\nfunction resetRateLimitAmount(uint256 _amount) external onlyRole(RATE_LIMIT_SETTER_ROLE) {\n    bool amountUsedLoweredToLimit;\n\n    if (_amount < currentPeriodAmountInWei) {\n        currentPeriodAmountInWei = _amount;\n        amountUsedLoweredToLimit = true;\n    }\n\n    limitInWei = _amount;\n\n    emit LimitAmountChange(_msgSender(), _amount, amountUsedLoweredToLimit);\n}\n```\n```\nfunction resetAmountUsedInPeriod() external onlyRole(RATE_LIMIT_SETTER_ROLE) {\n    currentPeriodAmountInWei = 0;\n\n    emit AmountUsedInPeriodReset(_msgSender());\n}\n```
MEDIUM severity: The Forta system's reward mechanism for stakers is vulnerable to inconsistencies in reward tracking . The Forta system's reward mechanism for stakers is vulnerable to inconsistencies in reward tracking due to the lack of checks for rewarding an epoch that has already been rewarded. The `RewardsDistributor` contract's `reward()` function allows a privileged account with the `REWARDER_ROLE` to distrib...

Vulnerable code:
```\nfunction reward(\n    uint8 subjectType,\n    uint256 subjectId,\n    uint256 amount,\n    uint256 epochNumber\n) external onlyRole(REWARDER_ROLE) {\n    if (subjectType!= NODE_RUNNER_SUBJECT) {\n        revert InvalidSubjectType(subjectType);\n    }\n    if (!_subjectGateway.isRegistered(subjectType, subjectId)) {\n        revert RewardingNonRegisteredSubject(subjectType, subjectId);\n    }\n    uint256 shareId = FortaStakingUtils.subjectToActive(getDelegatorSubjectType(subjectType), subjectId);\n    _rewardsPerEpoch[shareId][epochNumber] = amount;\n    totalRewardsDistributed += amount;\n    emit Rewarded(subjectType, subjectId, amount, epochNumber);\n}\n```
MEDIUM severity: The `_calculateClaim()` function in the veSatin token system is vulnerable to an arithmetic underflo. The `_calculateClaim()` function in the veSatin token system is vulnerable to an arithmetic underflow issue, which can prevent users from claiming emissions for a particular week. This occurs when a user withdraws or merges their veSatin, causing the `lockEndTime` variable to be set to 0. Subsequent...

Vulnerable code:
```\nif ((lockEndTime - weekCursor) > (minLockDurationForReward)) {\n    toDistribute += (balanceOf * tokensPerWeek[weekCursor]) / veSupply[weekCursor];\n    weekCursor += WEEK;\n```
MEDIUM severity: The `_removeSigner` function is responsible for updating the `signerCount` and `threshold` variables. The `_removeSigner` function is responsible for updating the `signerCount` and `threshold` variables when a signer is removed from the list. However, under certain circumstances, this function can incorrectly update these variables, leading to potential issues in the system.\n\nThe function uses a c...

Vulnerable code:
```\nif (validSignerCount == currentSignerCount):\n    newSignerCount = currentSignerCount\nelse:\n    newSignerCount = currentSignerCount - 1\n```
MEDIUM severity: The `BalanceRedirectPresale` contract contains a vulnerability that allows the `OPEN_ROLE` to indefi. The `BalanceRedirectPresale` contract contains a vulnerability that allows the `OPEN_ROLE` to indefinitely extend the presale period, even after users have contributed funds to it. This is achieved by manipulating the `setPeriod` function, which is accessible to the `OPEN_ROLE`.\n\nThe `setPeriod` f...

Vulnerable code:
```\nfunction setPeriod(uint64 _period) external auth(OPEN_ROLE) {\n    _setPeriod(_period);\n}\n```\n```\nfunction _setPeriod(uint64 _period) internal {\n    require(_period > 0, ERROR_TIME_PERIOD_ZERO);\n    require(openDate == 0 || openDate + _period > getTimestamp64(), ERROR_INVALID_TIME_PERIOD);\n    period = _period;\n}\n```
MEDIUM severity: The vulnerability lies in the calculation of the exchange rate for shares in DnGmxSeniorVault, which. The vulnerability lies in the calculation of the exchange rate for shares in DnGmxSeniorVault, which is determined by dividing the total supply of shares by the total assets of the vault. Specifically, the `convertToShares` function uses the `mulDivDown` operation to calculate the exchange rate, whi...

Vulnerable code:
```\nfunction convertToShares(uint256 assets) public view virtual returns (uint256) {\n    uint256 supply = totalSupply();  # Saves an extra SLOAD if totalSupply is non-zero.\n\n    return supply == 0? assets : assets.mulDivDown(supply, totalAssets());\n}\n```
MEDIUM severity: The `DAOfiV1Pair` contract's `deposit()`, `withdraw()`, and `swap()` functions are restricted to onl. The `DAOfiV1Pair` contract's `deposit()`, `withdraw()`, and `swap()` functions are restricted to only be called by the router, ostensibly to prevent losses resulting from user error. However, this design decision has a significant security implication: any vulnerability or malicious behavior in the...

Vulnerable code:
```\nfunction deposit(address to) external override {\n    require(msg.sender == router, 'DAOfiV1: FORBIDDEN_DEPOSIT');\n    return;\n}\n```\n```\nfunction withdraw(address to) external override {\n    require(msg.sender == router, 'DAOfiV1: FORBIDDEN_WITHDRAW');\n    return (uint256 amountBase, uint256 amountQuote);\n```\n```\nfunction swap(\n    address tokenIn,\n    address tokenOut,\n    uint256 amountIn,\n    uint256 amountOut,\n    address to\n) external override lock {\n    require(msg.sender == router, 'DAOfiV1: FORBIDDEN_SWAP');\n```
MEDIUM severity: The protocol's fee mechanism, as implemented in the `pendingFee` function, is susceptible to generat. The protocol's fee mechanism, as implemented in the `pendingFee` function, is susceptible to generating unnecessary fees when the vault is paused and reopened later. This issue arises when the protocol continues to mint fees based on the time elapsed since the last fee collection, without considerin...

Vulnerable code:
```\nfunction pendingFee(GMXTypes.Store storage self) public view returns (uint256) {\n    uint256 totalSupply_ = IERC20(address(self.vault)).totalSupply();\n    uint256 _secondsFromLastCollection = block.timestamp - self.lastFeeCollected;\n    return (totalSupply_ * self.feePerSecond * _secondsFromLastCollection) / SAFE_MULTIPLIER;\n}\n```
MEDIUM severity: The `Zer0 Name Service` (ZNS) registrar's initialization function, `initialize()`, skips the chained. The `Zer0 Name Service` (ZNS) registrar's initialization function, `initialize()`, skips the chained initializer `__ERC721Pausable_init()` in its implementation. This oversight allows the registrar to bypass the initialization of essential components, including `__ERC165_init_unchained()`, `__Pausab...

Vulnerable code:
```\nabstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable {\n    function __ERC721Pausable_init() internal initializer {\n        __Context_init_unchained();\n        __ERC165_init_unchained();\n        __Pausable_init_unchained();\n        __ERC721Pausable_init_unchained();\n    }\n}\n```\n```\nfunction initialize() public initializer {\n    __Ownable_init();\n    __ERC721_init("Zer0 Name Service", "ZNS");\n\n    // create the root domain\n    _createDomain(0, msg.sender, msg.sender, address(0));\n}\n```
MEDIUM severity: The `BlockhashRegistry` in the EVM environment stores the last 256 blocks' blockhashes in memory. Th. The `BlockhashRegistry` in the EVM environment stores the last 256 blocks' blockhashes in memory. This is achieved through the `snapshot()` and `saveBlockNumber(uint _blockNumber)` functions. The `recreateBlockheaders` method is responsible for recreating older blocks by overwriting existing blockha...

Vulnerable code:
```\nfunction saveBlockNumber(uint _blockNumber) public {\n    bytes32 bHash = blockhash(_blockNumber);\n\n    require(bHash!= 0x0, "block not available");\n\n    blockhashMapping[_blockNumber] = bHash;\n    emit LogBlockhashAdded(_blockNumber, bHash);\n}\n```\n```\nblockhashMapping[bnr] = calculatedHash;\n```
MEDIUM severity: The `remove` function in the `UniqueAddressQueue` contract is responsible for removing an item from . The `remove` function in the `UniqueAddressQueue` contract is responsible for removing an item from the queue. However, upon closer inspection, it appears that the function does not properly remove the item from the queue, leaving behind a residual reference to the removed item.\n\nThe issue arises...

Vulnerable code:
```\nfunction remove(UniqueAddressQueue storage baseQueue, address addrToRemove) internal returns (bool) {\n    if (!contains(baseQueue, addrToRemove)) {\n        return false;\n    }\n\n    if (baseQueue.HEAD == addrToRemove) {\n        return removeFirst(baseQueue);\n    }\n\n    if (baseQueue.TAIL == addrToRemove) {\n        return removeLast(baseQueue);\n    }\n\n    address prevAddr = baseQueue.queue[addrToRemove].prev;\n    address nextAddr = baseQueue.queue[addrToRemove].next;\n    baseQueue.queue[prevAddr].next = nextAddr;\n    baseQueue.queue[nextAddr].prev = prevAddr;\n    baseQueue.queueLength--;\n\n    return true;\n}\n```
MEDIUM severity: The vulnerability allows an attacker to frontrun liquidations by exploiting the warning mechanism in. The vulnerability allows an attacker to frontrun liquidations by exploiting the warning mechanism in the liquidation process. Specifically, the `Borrower.warn` function sets a timestamp for the liquidation to occur, which is calculated as `block.timestamp + LIQUIDATION_GRACE_PERIOD`. However, the `B...

Vulnerable code:
```\nslot0 = slot0_ | ((block.timestamp + LIQUIDATION_GRACE_PERIOD) << 208);\n```\n```\n_repay(repayable0, repayable1);\n\nslot0 = (slot0_ & SLOT0_MASK_POSITIONS) | SLOT0_DIRT\n```\n```\nfunction test_liquidationFrontrun() public {\n    uint256 margin0 = 1595e18;\n    uint256 margin1 = 0;\n    uint256 borrows0 = 0;\n    uint256 borrows1 = 1e18 * 100;\n\n    margin0 += 1;\n\n    deal(address(asset0), address(account), margin0);\n    deal(address(asset1), address(account), margin1);\n\n    bytes memory data = abi.encode(Action.BORROW, borrows0, borrows1);\n    account.modify(this, data, 1 << 32);\n\n    assertEq(lender0.borrowBalance(address(account)), borrows0);\n    assertEq(lender1.borrowBalance(address(account)), borrows1);\n    assertEq(asset0.balanceOf(address(account)), borrows0 + margin0);\n    assertEq(asset1.balanceOf(address(account)), borrows1 + margin1);\n\n    _setInterest(lender0, 10100);\n    _setInterest(lender1, 10100);\n\n    account.warn(1 << 32);\n\n    uint40 unleashLiquidationTime = uint40((account.slot0() + 208) % (1 << 40));\n    assertEq(unleashLiquidationTime, block.timestamp + LIQUIDATION_GRACE_PERIOD);\n\n    skip(LIQUIDATION_GRACE_PERIOD + 1);\n\n    account.liquidate(this, "", 1e10, 1 << 32);\n\n    unleashLiquidationTime = uint40((account.slot0() + 208) % (1 << 40));\n    assertEq(unleashLiquidationTime, 0);\n\n    vm.expectRevert();\n    account.liquidate(this, "", 1, 1 << 32);\n}\n```
MEDIUM severity: The `receiveApproval` function in the `TokenStaking` contract allows for the staking of tokens witho. The `receiveApproval` function in the `TokenStaking` contract allows for the staking of tokens without sufficient checks on the token amount. Specifically, the function does not verify whether the token transfer is approved by the owner, and instead relies on the fact that the token transfer to the...

Vulnerable code:
```\n/**\n * @notice Receives approval of token transfer and stakes the approved amount.\n * @dev Makes sure provided token contract is the same one linked to this contract.\n * @param _from The owner of the tokens who approved them to transfer.\n * @param _value Approved amount for the transfer and stake.\n * @param _token Token contract address.\n * @param _extraData Data for stake delegation. This byte array must have the\n * following values concatenated: Magpie address (20 bytes) where the rewards for participation\n * are sent, operator's (20 bytes) address, authorizer (20 bytes) address.\n */\n\nfunction receiveApproval(address _from, uint256 _value, address _token, bytes memory _extraData) public {\n    require(ERC20Burnable(_token) == token, "Token contract must be the same one linked to this contract.");\n    require(_value <= token.balanceOf(_from), "Sender must have enough tokens.");\n    require(_extraData.length == 60, "Stake delegation data must be provided.");\n\n    address payable magpie = address(uint160(_extraData.toAddress(0)));\n    address operator = _extraData.toAddress(20);\n    require(operators[operator].owner == address(0), "Operator address is already in use.");\n    address authorizer = _extraData.toAddress(40);\n\n    // Transfer tokens to this contract.\n    token.transferFrom(_from, address(this), _value);\n\n    operators[operator] = Operator(_value, block.number, 0, _from, magpie, authorizer);\n    ownerOperators[_from].push(operator);\n\n    emit Staked(operator, _value);\n}\n```
MEDIUM severity: The Maverick oracle's `getPriceInEth` function is vulnerable to manipulation due to its reliance on . The Maverick oracle's `getPriceInEth` function is vulnerable to manipulation due to its reliance on the reserves of the Maverick pool, which can fluctuate when the price of the Maverick pool changes. Specifically, the function multiplies the reserves of the Maverick pool with the external prices of...

Vulnerable code:
```\nuint256 reserveTokenA, uint256 reserveTokenB = boostedPosition.getReserves();\n\nuint256 boostedPositionTotalSupply = boostedPosition.totalSupply();\n\nIRootPriceOracle rootPriceOracle = systemRegistry.rootPriceOracle();\n\nuint256 priceInEthTokenA = rootPriceOracle.getPriceInEth(address(pool.tokenA()));\nuint256 priceInEthTokenB = rootPriceOracle.getPriceInEth(address(pool.tokenB()));\n\nuint256 totalBoostedPositionValueTokenA = reserveTokenA * priceInEthTokenA;\nuint256 totalBoostedPositionValueTokenB = reserveTokenB * priceInEthTokenB;\n\nreturn (totalBoostedPositionValueTokenA + totalBoostedPositionValueTokenB) / boostedPositionTotalSupply;\n```
MEDIUM severity: The FulfillInterpreter's `prepare` function checks whether the `callTo` address is either zero or a . The FulfillInterpreter's `prepare` function checks whether the `callTo` address is either zero or a contract, ensuring that the call is either a transfer to the zero address or a call to a contract. However, this check is not repeated when the `callTo` address is executed in the `execute` function....

Vulnerable code:
```\nrequire(\n    invariantData.callTo == address(0) || Address.isContract(invariantData.callTo),\n    "#P:031"\n)\n```\n```\nbool success, bytes memory returnData = callTo.call{value: isEther? amount : 0}(callData);\n\nif (!success) {\n    Asset.transferAsset(assetId, fallbackAddress, amount);\n    if (!isEther) {\n        Asset.decreaseERC20Allowance(assetId, callTo, amount);\n    }\n}\n```
MEDIUM severity: The `canReceive` function lacks additional validation to ensure that only the intended entity, in th. The `canReceive` function lacks additional validation to ensure that only the intended entity, in this case, the `Amp`, is authorized to execute the function. Unlike the `FlexaCollateralManager.tokensReceived` function, which has a validation check to restrict access to the `Amp` only, the `canRecei...

Vulnerable code:
```\nrequire(msg.sender == amp, "Invalid sender");\n```
MEDIUM severity: The `MarginAccountHelper` contract's `syncDeps` function is responsible for refreshing its reference. The `MarginAccountHelper` contract's `syncDeps` function is responsible for refreshing its references to the `marginAccount` and `insuranceFund` contracts, which are retrieved from the `registry` contract. However, a critical issue arises when the `syncDeps` function is called, as it updates the ref...

Vulnerable code:
```\nfunction syncDeps(address _registry) public onlyGovernance {\n    IRegistry registry = IRegistry(_registry);\n\n    vusd = IVUSD(registry.vusd());\n    marginAccount = IMarginAccount(registry.marginAccount());\n    insuranceFund = IInsuranceFund(registry.insuranceFund());\n}\n```
MEDIUM severity: The vulnerability allows users to circumvent the performance fee mechanism by withdrawing their asse. The vulnerability allows users to circumvent the performance fee mechanism by withdrawing their assets before the end of the epoch. This manipulation enables them to avoid paying the fee, which is typically deducted from the collateral tokens in the vault. The fee is calculated based on the total va...

Vulnerable code:
```\nuint256 adjustedTotalAssets = _totalAssets() + l.totalWithdrawals;\n\nif (adjustedTotalAssets > l.lastTotalAssets) {\n    netIncome = adjustedTotalAssets - l.lastTotalAssets;\n\n    feeInCollateral = l.performanceFee64x64.mul(l.netIncome);\n\n    ERC20.safeTransfer(l.feeRecipient, feeInCollateral);\n}\n```
MEDIUM severity: The vulnerability arises when an invalid oracle version is used to load the current position in the . The vulnerability arises when an invalid oracle version is used to load the current position in the market. This incorrect position is then used to calculate the minimum and maximum position limits enforced by the vault. The calculation of these limits is performed in the `_positionLimit` function,...

Vulnerable code:
```\ncontext.currentPosition = \n    registration.market.pendingPosition(global.currentId)\n```\n```\nfunction _positionLimit(\n    MarketContext memory context\n) private pure returns (UFixed6, UFixed6) {\n    return (\n        context.currentAccountPosition.maker.sub(\n            context.currentPosition.maker\n               .sub(context.currentPosition.net().min(context.currentPosition.maker))\n               .min(context.currentAccountPosition.maker)\n               .min(context.closable)\n        ),\n        context.currentAccountPosition.maker.add(\n            context.riskParameter.makerLimit\n               .sub(context.currentPosition.maker.min(context.riskParameter.makerLimit))\n        )\n    );\n}\n```\n```\n(targets[marketId].collateral, targets[marketId].position) = (\n    Fixed6Lib.from(_locals.marketCollateral).sub(\n        contexts[marketId].local.collateral\n    ),\n    _locals.marketAssets\n       .muldiv(\n            registrations[marketId].leverage,\n            contexts[marketId].latestPrice.abs()\n        )\n       .min(_locals.maxPosition)\n       .max(_locals.minPosition)\n)\n```
MEDIUM severity: The vulnerability allows an attacker to manipulate the voting process by exploiting the reorganizati. The vulnerability allows an attacker to manipulate the voting process by exploiting the reorganization of the blockchain. Specifically, it enables the attacker to abuse a victim's vote to pass their own proposal. This occurs when a user submits a proposal, and another user confirms it. If a blockcha...

Vulnerable code:
```\nfunction submitProposal(uint8 _actionType, bytes memory _payload) public onlyCouncil {\n    uint256 proposalId = proposalCount;\n    proposals[proposalId] = Proposal(\n        msg.sender,\n        _actionType,\n        _payload,\n        0,\n        false\n    );\n    proposalCount += 1;\n    emit ProposalSubmitted(proposalId, msg.sender);\n}\n```\n```\nfunction confirmTransaction(uint256 _proposalId) public onlyCouncil notConfirmed(_proposalId) {\n    confirmations[_proposalId][msg.sender] = true;\n    proposals[_proposalId].confirmation += 1;\n    emit Confirmation(_proposalId, msg.sender);\n}\n```
MEDIUM severity: The vulnerability arises when the interest rate model is updated, causing the `cTokenAggregator.getE. The vulnerability arises when the interest rate model is updated, causing the `cTokenAggregator.getExchangeRateView()` function to return the stored exchange rate, which does not account for accrued interest. This discrepancy in interest accrual can lead to a significant difference between the calcu...

Vulnerable code:
```\nFile: TreasuryAction.sol\n\nfunction _executeRebalance(uint16 currencyId) private {\n    IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\n    uint8[] memory rebalancingTargets = _getRebalancingTargets(currencyId, oracle.holdings());\n\n    (RebalancingData memory data) = REBALANCING_STRATEGY.calculateRebalance(oracle, rebalancingTargets);\n\n    (, uint256 totalUnderlyingValueBefore) = oracle.getTotalUnderlyingValueStateful();\n\n    // Process redemptions first\n    Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);\n    TokenHandler.executeMoneyMarketRedemptions(underlyingToken, data.redeemData);\n\n    // Process deposits\n    _executeDeposits(underlyingToken, data.depositData);\n\n    (, uint256 totalUnderlyingValueAfter) = oracle.getTotalUnderlyingValueStateful();\n\n    int256 underlyingDelta = totalUnderlyingValueBefore.toInt().sub(totalUnderlyingValueAfter.toInt());\n    require(underlyingDelta.abs() < Constants.REBALANCING_UNDERLYING_DELTA);\n}\n```\n```\nfunction getExchangeRateView() external view override returns (int256) {\n    uint256 exchangeRate = cToken.interestRateModel() == INTEREST_RATE_MODEL\n       ? _viewExchangeRate()\n        : cToken.exchangeRateStored();\n    _checkExchangeRate(exchangeRate);\n\n    return int256(exchangeRate);\n}\n```