Farseen0/scar-pairs huggingface dataset:
MEDIUM severity: The `FeeManager` smart contract contains two critical vulnerabilities in its `trackVaultFee` and `re. The `FeeManager` smart contract contains two critical vulnerabilities in its `trackVaultFee` and `receiveFee` functions, which allow malicious users to manipulate fee accounting and temporarily brick the DVP smart contract.\n\nThe `trackVaultFee` function, responsible for tracking vault fees, lacks...

Vulnerable code:
```\nfunction trackVaultFee(address vault, uint256 feeAmount) external {\n    IDVP dvp = IDVP(msg.sender);\n    if (vault!= dvp.vault()) {\n        revert WrongVault();\n    }\n\n    vaultFeeAmounts[vault] += feeAmount;\n\n    emit TransferVaultFee(vault, feeAmount);\n```\n```\nfunction receiveFee(uint256 feeAmount) external {\n    _getBaseTokenInfo(msg.sender).safeTransferFrom(msg.sender, address(this), feeAmount);\n    senders[msg.sender] += feeAmount;\n\n    emit ReceiveFee(msg.sender, feeAmount);\n}\n\nfunction _getBaseTokenInfo(address sender) internal view returns (IERC20Metadata token) {\n    token = IERC20Metadata(IVaultParams(sender).baseToken());\n}\n```
MEDIUM severity: The system's administrative capabilities can lead to unpredictable behavior for users due to the pot. The system's administrative capabilities can lead to unpredictable behavior for users due to the potential for front-running or accidental changes. This vulnerability arises from the ability of administrators to update or upgrade system components without warning, which can result in malicious or un...

Vulnerable code:
```\nfunction setReferralFeeReceiver(address newReferralFeeReceiver) external onlyOwner {\n    referralFeeReceiver = newReferralFeeReceiver;\n    emit ReferralFeeReceiverUpdate(newReferralFeeReceiver);\n}\n```\n```\nif (referral!= address(0)) {\n    referralShare = invIncrease.mul(referralShare).div(_FEE_DENOMINATOR);\n    if (referralShare > 0) {\n        if (referralFeeReceiver!= address(0)) {\n            _mint(referralFeeReceiver, referralShare);\n            IReferralFeeReceiver(referralFeeReceiver).updateReward(referral, referralShare);\n        }\n    }\n}\n```\n```\nfunction addModule(address module) external onlyOwner {\n    require(_modules.add(module), "Module already registered");\n    emit AddModule(module);\n}\n```\n```\nfunction _notifyFor(address account, uint256 balance) private {\n    uint256 modulesLength = _modules.length();\n    for (uint256 i = 0; i < modulesLength; i++) {\n        IGovernanceModule(_modules.at(i)).notifyStakeChanged(account, balance);\n    }\n}\n```\n```\nfunction removeModule(address module) external onlyOwner {\n    require(_modules.remove(module), "Module was not registered");\n    emit RemoveModule(module);\n}\n```
MEDIUM severity: The `getDecimals()` method, invoked by `XChainController.pushVaultAmounts()`, is hardcoded to retrie. The `getDecimals()` method, invoked by `XChainController.pushVaultAmounts()`, is hardcoded to retrieve the decimals value from the MainNet, regardless of the `chainID` provided. This is problematic because the `address(vault)` returned by `XChainController.getVaultAddress()` can be associated with a...

Vulnerable code:
```\nuint256 newExchangeRate = (totalUnderlying * (10 ** decimals)) / totalSupply;\n```
MEDIUM severity: The `BassetStatus` enum defines a set of states that describe the status of a Basset, a type of asse. The `BassetStatus` enum defines a set of states that describe the status of a Basset, a type of asset. The enum includes several values that do not appear to be utilized in the code, specifically `Default`, `Liquidating`, `Liquidated`, and `Failed`. These unused states may indicate the presence of d...

Vulnerable code:
```\n/**\n * @dev Status of the Basset - has it broken its peg?\n */\nenum BassetStatus {\n    Default,\n    Normal,\n    BrokenBelowPeg,\n    BrokenAbovePeg,\n    Blacklisted,\n    Liquidating,\n    Liquidated,\n    Failed\n}\n```\n```\n_bAsset.status == BassetStatus.Liquidating ||\n_bAsset.status == BassetStatus.Blacklisted\n```
MEDIUM severity: The `Funding._withdraw()` function in the JOJODealer contract allows for arbitrary calls to a specif. The `Funding._withdraw()` function in the JOJODealer contract allows for arbitrary calls to a specified address with user-specified parameters. This vulnerability enables an attacker to manipulate the withdrawal process, enabling them to steal funds by making arbitrary calls to a contract, such as t...

Vulnerable code:
```\nfunction executeWithdraw(address from, address to, bool isInternal, bytes memory param) external nonReentrant {\n    Funding.executeWithdraw(state, from, to, isInternal, param);\n}\n```\n```\nfunction _withdraw(\n    Types.State storage state,\n    address spender,\n    address from,\n    address to,\n    uint256 primaryAmount,\n    uint256 secondaryAmount,\n    bool isInternal,\n    bytes memory param\n)\n    private\n{\n    if (param.length!= 0) {\n        require(Address.isContract(to), "target is not a contract");\n        (bool success,) = to.call(param);\n        if (success == false) {\n            assembly {\n                let ptr := mload(0x40)\n                let size := returndatasize()\n                returndatacopy(ptr, 0, size)\n                revert(ptr, size)\n            }\n        }\n    }\n}\n```
MEDIUM severity: The vulnerability lies in the inconsistent handling of dust balances in secondary debt. While the pr. The vulnerability lies in the inconsistent handling of dust balances in secondary debt. While the primary debt's `totalDebtUnderlying` is truncated towards zero, the secondary debt's `totalDebtUnderlying` is not. This discrepancy can lead to unintended consequences, as dust balances in secondary deb...

Vulnerable code:
```\nFile: VaultAccount.sol\n\nfunction updateAccountDebt(\n    // Update account debt\n    uint256 _newDebt,\n    uint256 _newDebtTimestamp,\n    uint256 _newDebtUnderlying\n) public {\n    // Update account debt\n    vaultState.totalDebt = _newDebt;\n    vaultState.totalDebtTimestamp = _newDebtTimestamp;\n    vaultState.totalDebtUnderlying = _newDebtUnderlying;\n\n    // Truncate dust balances towards zero\n    if (0 < vaultState.totalDebtUnderlying && vaultState.totalDebtUnderlying < 10) {\n        vaultState.totalDebtUnderlying = 0;\n    }\n}\n\n}\n```\n```\nFile: VaultSecondaryBorrow.sol\n\nfunction _updateTotalSecondaryDebt(\n    VaultConfig memory vaultConfig,\n    address account,\n    uint16 currencyId,\n    uint256 maturity,\n    int256 netUnderlyingDebt,\n    PrimeRate memory pr\n) private {\n    VaultStateStorage storage balance = LibStorage.getVaultSecondaryBorrow()\n        [vaultConfig.vault][maturity][currencyId];\n    int256 totalDebtUnderlying = VaultStateLib.readDebtStorageToUnderlying(pr, maturity, balance.totalDebt);\n\n    totalDebtUnderlying = totalDebtUnderlying.add(netUnderlyingDebt);\n    VaultStateLib.setTotalDebtStorage(\n        balance, pr, vaultConfig, currencyId, maturity, totalDebtUnderlying, false\n    );\n```
MEDIUM severity: The `LenderCommitmentForwarder#updateCommitment` function in the LenderCommitmentForwarder contract . The `LenderCommitmentForwarder#updateCommitment` function in the LenderCommitmentForwarder contract is vulnerable to a front-running attack, allowing malicious borrowers to manipulate the commitment data and cause lenders to over-commit funds. This vulnerability arises from the fact that the `update...

Vulnerable code:
```\nrequire(\n    _commitment.principalTokenAddress ==\n        commitments[_commitmentId].principalTokenAddress,\n    "Principal token address cannot be updated."\n);\n\nrequire(\n    _commitment.marketId == commitments[_commitmentId].marketId,\n    "Market Id cannot be updated."\n);\n\ncommitments[_commitmentId] = _commitment;\n```
MEDIUM severity: The UUPSUpgradeable vulnerability is a critical severity bug discovered in OpenZeppelin's contracts,. The UUPSUpgradeable vulnerability is a critical severity bug discovered in OpenZeppelin's contracts, specifically in versions 4.1.0 to 4.3.1. The affected contracts include `@openzeppelin/contracts` and `@openzeppelin/contracts-upgradeable`, which are widely used in the kyber-swap contracts, as evid...

Vulnerable code:
```\n{\n  "@openzeppelin/contracts": "4.3.1",\n  "@openzeppelin/test-helpers": "0.5.6",\n  "@openzeppelin/contracts-upgradeable": "4.3.1"\n}\n```
MEDIUM severity: The `ERC20Gauges` contract's `maxGauges` state variable is intended to safeguard against gas DOS att. The `ERC20Gauges` contract's `maxGauges` state variable is intended to safeguard against gas DOS attacks by limiting the number of gauges a user can allocate. This variable can be adjusted by authorized users through the `setMaxGauges` function, which updates the `maxGauges` state variable and emits...

Vulnerable code:
```\nfunction setMaxGauges(uint256 newMax) external requiresAuth {\n    uint256 oldMax = maxGauges;\n    maxGauges = newMax;\n\n    emit MaxGaugesUpdate(oldMax, newMax);\n}\n```
MEDIUM severity: The `TokenDrop.initialize()` function is vulnerable to unauthorized access and manipulation due to i. The `TokenDrop.initialize()` function is vulnerable to unauthorized access and manipulation due to its unprotected nature. This function, which is intended to set the `measure` and `asset` variables, can be called multiple times without any restrictions. This lack of protection allows an attacker to...

Vulnerable code:
```\nfunction initialize(address _measure, address _asset) external {\n    measure = IERC20Upgradeable(_measure);\n    asset = IERC20Upgradeable(_asset);\n\n    factory = msg.sender;\n}\n```
MEDIUM severity: A vulnerability exists in the `sdlPoolSecondary` contract, where a user can potentially lose funds i. A vulnerability exists in the `sdlPoolSecondary` contract, where a user can potentially lose funds if they attempt to add more SDL tokens to a lock that has been queued for complete withdrawal. This occurs when a user queues a withdrawal of the entire lock balance and then, before the withdrawal is...

Vulnerable code:
```\nit('PoC user will lose extra deposited tokens', async () => {\n  let user = accounts[1];\n  let initialUserSDLBalance = await sdlToken.balanceOf(user);\n\n  await sdlToken.connect(signers[1]).transferAndCall(\n    sdlPool.address,\n    toEther(100),\n    ethers.utils.defaultAbiCoder.encode(['uint256', 'uint64'], [0, 0])\n  );\n\n  await sdlPool.handleOutgoingUpdate();\n  await sdlPool.handleIncomingUpdate(1);\n  await sdlPool.connect(signers[1]).executeQueuedOperations([]);\n\n  assert.equal(await sdlPool.ownerOf(1), user);\n\n  await sdlPool.connect(signers[1]).withdraw(1, toEther(100));\n\n  await sdlToken.connect(signers[1]).transferAndCall(\n    sdlPool.address,\n    toEther(1000),\n    ethers.utils.defaultAbiCoder.encode(['uint256', 'uint64'], [1, 0])\n  );\n\n  await sdlPool.handleOutgoingUpdate();\n  await sdlPool.handleIncomingUpdate(2);\n  await sdlPool.connect(signers[1]).executeQueuedOperations([1]);\n\n  let finalUserSDLBalance = await sdlToken.balanceOf(user);\n  let sdlLost = initialUserSDLBalance.sub(finalUserSDLBalance);\n\n  console.log("The user has lost", sdlLost.toString(), "sdl tokens");\n\n  await expect(sdlPool.ownerOf(1)).to.be.revertedWith('InvalidLockId()');\n})\n```\n```\nSDLPoolSecondary\nThe user has lost 1000000000000000000000 sdl tokens\n    ✔ PoC user is not able to execute his lock updates (159ms)\n\n1 passing (3s)\n```
MEDIUM severity: The `refund` function is responsible for allocating refunds to insurance holders based on their elig. The `refund` function is responsible for allocating refunds to insurance holders based on their eligibility. The `refundMap` mapping stores the refund amounts for each insurance holder, and the `refund` function retrieves the refund amount for a given holder by multiplying the `coverage.amount` by t...

Vulnerable code:
```\nfunction refund(\n    uint256 policyIndex_,\n    uint256 week_,\n    address who_\n) external nonReentrant {\n    Coverage storage coverage = coverageMap[policyIndex_][week_][who_];\n\n    require(!coverage.refunded, "Already refunded");\n\n    uint256 allCovered = coveredMap[policyIndex_][week_];\n    uint256 amountToRefund = refundMap[policyIndex_][week_].mul(coverage.amount).div(allCovered);\n    coverage.amount = coverage.amount.mul(coverage.premium.sub(amountToRefund)).div(coverage.premium);\n    coverage.refunded = true;\n\n    IERC20(baseToken).safeTransfer(who_, amountToRefund);\n\n    if (eventAggregator!= address(0)) {\n        IEventAggregator(eventAggregator).refund(\n            policyIndex_,\n            week_,\n            who_,\n            amountToRefund\n        );\n    }\n}\n```
MEDIUM severity: The `zAuction` smart contract contains incomplete and potentially malicious code in its `zWithdraw` . The `zAuction` smart contract contains incomplete and potentially malicious code in its `zWithdraw` and `zDeposit` functions. Specifically, the `zWithdraw` function appears to burn the Ethereum (ETH) balance of an account instead of actually transferring the funds, as it does not include a transfer...

Vulnerable code:
```\nfunction zDeposit(address to) external payable onlyZauction {\n    ethbalance[to] = SafeMath.add(ethbalance[to], msg.value);\n    emit zDeposited(to, msg.value);\n}\n\nfunction zWithdraw(address from, uint256 amount) external onlyZauction {\n    ethbalance[from] = SafeMath.sub(ethbalance[from], amount);\n    emit zWithdrew(from, amount);\n}\n```
MEDIUM severity: The vulnerability arises when the `claimOrder` function is called under specific conditions, resulti. The vulnerability arises when the `claimOrder` function is called under specific conditions, resulting in the owner being unable to collect fulfillment fees from certain users. This occurs when the difference in precision between the `token0` and `token1` in the pool is significant, typically when o...

Vulnerable code:
```\nFile: LimitOrderRegistry.sol\n\nfunction claimOrder(uint128 batchId, address user) external payable returns (ERC20, uint256) {\n    Claim storage userClaim = claim[batchId];\n    if (!userClaim.isReadyForClaim) {\n        revert LimitOrderRegistry__OrderNotReadyToClaim(batchId);\n    }\n    uint256 depositAmount = batchIdToUserDepositAmount[batchId][user];\n    if (depositAmount == 0) {\n        revert LimitOrderRegistry__UserNotFound(user, batchId);\n\n    // Zero out user balance.\n    delete batchIdToUserDepositAmount[batchId][user];\n\n    // Calculate owed amount.\n    uint256 totalTokenDeposited;\n    uint256 totalTokenOut;\n    ERC20 tokenOut;\n\n    // again, remembering that direction == true means that the input token is token0.\n    if (userClaim.direction) {\n        totalTokenDeposited = userClaim.token0Amount;\n        totalTokenOut = userClaim.token1Amount;\n        tokenOut = poolToData[userClaim.pool].token1;\n    } else {\n        totalTokenDeposited = userClaim.token1Amount;\n        totalTokenOut = userClaim.token0Amount;\n        tokenOut = poolToData[userClaim.pool].token0;\n    }\n\n    uint256 owed = (totalTokenOut * depositAmount) / totalTokenDeposited;\n\n    // Transfer tokens owed to user.\n    tokenOut.safeTransfer(user, owed);\n}\n```\n```\nowed = (totalTokenOut * depositAmount) / totalTokenDeposited\nowed = (9 * 10**6 * 10 * 10**18) / (100000000 * 10**18)\nowed = (9 * 10**6 * 10) / (100000000)\nowed = 90000000 / 100000000\nowed = 0\n```\n```\ntokenOut.safeTransfer(user, owed)\n```
MEDIUM severity: The `MarketUtils.getFundingAmountPerSizeDelta()` function, responsible for calculating the `FundingA. The `MarketUtils.getFundingAmountPerSizeDelta()` function, responsible for calculating the `FundingAmountPerSizeDelta` with a roundup input mode parameter, contains a critical logical error. Specifically, the divisor consistently employs a rounding up approach, regardless of the input `roundUp` roun...

Vulnerable code:
```\nfunction testGetFundingAmountPerSizeDelta() public {\n    uint result = MarketUtils.getFundingAmountPerSizeDelta(2e15, 1e15 + 1, true);\n    console2.log("result: %d", result);\n    uint256 correctResult = 2e15 * 1e15 * 1e30 + 1e15;\n    correctResult = correctResult / (1e15 + 1);\n    console2.log("correctResult: %d", correctResult);\n    assertTrue(result == 1e15 * 1e30);\n}\n```
MEDIUM severity: The `pay` function within the `InfinityPool` may lead to potential overpayment due to rounding impre. The `pay` function within the `InfinityPool` may lead to potential overpayment due to rounding imprecision. This occurs when an Agent attempts to repay only the fees portion of a debt. In such a scenario, the code executes the branch where `vc.value` is compared to `interestOwed`. \n\nThe issue aris...

Vulnerable code:
```\nif (vc.value <= interestOwed) {\n    uint256 epochsForward = vc.value.divWadDown(interestPerEpoch);\n    account.epochsPaid += epochsForward;\n    feeBasis = vc.value;\n} else {\n```\n```\nuint256 epochsForward = vc.value.divWadDown(interestPerEpoch);\n```
MEDIUM severity: The protocol's ability to handle multiple vaults is compromised due to an issue with the rebalancing. The protocol's ability to handle multiple vaults is compromised due to an issue with the rebalancing mechanism. Specifically, the protocol's reliance on the `lastTimeStamp` variable to determine whether a rebalance is needed can lead to incorrect behavior when multiple vaults are involved.\n\nWhen t...

Vulnerable code:
```\nfunction rebalanceNeeded() public view returns (bool) {\n    return (block.timestamp - lastTimeStamp) > rebalanceInterval || msg.sender == guardian;\n}\n```\n```\nlastTimeStamp = block.timestamp\n```\n```\nrequire(rebalanceNeeded(), "No rebalance needed");\n```
MEDIUM severity: The `repay` function in the smart contract is vulnerable to a scenario where the loan defaults due t. The `repay` function in the smart contract is vulnerable to a scenario where the loan defaults due to the lender being blacklisted by the debt token. This occurs when the `repay` function attempts to transfer the debt token directly to the lender using the `transferFrom` method. If the lender is bla...

Vulnerable code:
```\nfunction repay(uint256 loanID, uint256 repaid) external {\n    Loan storage loan = loans[loanID];\n\n    debt.transferFrom(msg.sender, loan.lender, repaid);\n    collateral.transfer(owner, decollateralized);\n```
MEDIUM severity: The vulnerability arises from the inability to value ICHI LP tokens due to the unavailability of ora. The vulnerability arises from the inability to value ICHI LP tokens due to the unavailability of oracle data for the underlying tokens. The ICHI LP token's value is calculated using the Fair LP Pricing technique, which relies on the prices of the individual tokens and their quantities. However, this...

Vulnerable code:
```\nfunction getPrice(address token) external view override returns (uint256) {\n    IICHIVault vault = IICHIVault(token);\n    uint256 totalSupply = vault.totalSupply();\n    if (totalSupply == 0) {\n        return 0;\n    }\n\n    address token0 = vault.token0();\n    address token1 = vault.token1();\n\n    (uint256 r0, uint256 r1) = vault.getTotalAmounts();\n    uint256 px0 = base.getPrice(address(token0));\n    uint256 px1 = base.getPrice(address(token1));\n    uint256 t0Decimal = IERC20Metadata(token0).decimals();\n    uint256 t1Decimal = IERC20Metadata(token1).decimals();\n\n    uint256 totalReserve = (r0 * px0) / (10**t0Decimal) + (r1 * px1) / (10**t1Decimal);\n\n    return (totalReserve * 1e18) / totalSupply;\n}\n```
MEDIUM severity: The vulnerability lies in the `addToTotalRewards` function, which is responsible for accruing reward. The vulnerability lies in the `addToTotalRewards` function, which is responsible for accruing rewards for a user's previous rebalancing period. However, the function only considers the current rebalancing period and ignores the previous period if the `rebalanceBasket` function is called in the next...

Vulnerable code:
```\nfunction addToTotalRewards(uint256 _basketId) internal onlyBasketOwner(_basketId) {\n    if (baskets[_basketId].nrOfAllocatedTokens == 0) {\n        return;\n    }\n\n    uint256 vaultNum = baskets[_basketId].vaultNumber;\n    uint256 currentRebalancingPeriod = vaults[vaultNum].rebalancingPeriod;\n    uint256 lastRebalancingPeriod = baskets[_basketId].lastRebalancingPeriod;\n\n    if (currentRebalancingPeriod <= lastRebalancingPeriod) {\n        return;\n    }\n\n    for (uint k = 0; k < chainIds.length; k++) {\n        uint32 chain = chainIds[k];\n        uint256 latestProtocol = latestProtocolId[chain];\n\n        for (uint i = 0; i < latestProtocol; i++) {\n            int256 allocation = basketAllocationInProtocol(_basketId, chain, i) / 1E18;\n            if (allocation == 0) {\n                continue;\n            }\n\n            int256 lastRebalanceReward = getRewardsPerLockedToken(\n                vaultNum,\n                chain,\n                lastRebalancingPeriod,\n                i\n            );\n            int256 currentReward = getRewardsPerLockedToken(\n                vaultNum,\n                chain,\n                currentRebalancingPeriod,\n                i\n            );\n            baskets[_basketId].totalUnRedeemedRewards +=\n                (currentReward - lastRebalanceReward) * allocation;\n        }\n    }\n}\n```
MEDIUM severity: The `liquidationAccountant` can be exploited by claiming the liquidation at any time due to a vulner. The `liquidationAccountant` can be exploited by claiming the liquidation at any time due to a vulnerability in the `handleNewLiquidation` function. This function is responsible for updating the `finalAuctionEnd` variable in the `liquidationAccountant` with the `finalAuctionTimestamp` value. However,...

Vulnerable code:
```\nLiquidationAccountant(accountant).handleNewLiquidation(\n  lien.amount,\n  COLLATERAL_TOKEN.auctionWindow() + 1 * days\n);\n```\n```\nrequire(\n  block.timestamp > finalAuctionEnd || finalAuctionEnd == uint256(0),\n  "final auction has not ended"\n);\n```
MEDIUM severity: The `getTotalBorrowingFees` function in the `DataStore` contract is prone to returning an inaccurate. The `getTotalBorrowingFees` function in the `DataStore` contract is prone to returning an inaccurate and stale amount of borrowing fees due to an incorrect function call. Specifically, the function calls `getCumulativeBorrowingFactor` instead of `getNextCumulativeBorrowingFactor` to calculate the cu...

Vulnerable code:
```\nfunction getTotalBorrowingFees(\n    DataStore dataStore,\n    address market,\n    address longToken,\n    address shortToken,\n    bool isLong\n) internal view returns (uint256) {\n    uint256 openInterest = getOpenInterest(\n        dataStore,\n        market,\n        longToken,\n        shortToken,\n        isLong\n    );\n    uint256 cumulativeBorrowingFactor = getCumulativeBorrowingFactor(\n        dataStore,\n        market,\n        isLong\n    );\n    uint256 totalBorrowing = getTotalBorrowing(\n        dataStore,\n        market,\n        isLong\n    );\n    return openInterest * cumulativeBorrowingFactor - totalBorrowing;\n}\n```\n```\nuint256 durationInSeconds = getSecondsSinceCumulativeBorrowingFactorUpdated(dataStore, market.marketToken, isLong);\n\nuint256 borrowingFactorPerSecond = getBorrowingFactorPerSecond(\n    dataStore,\n    market,\n    prices,\n    isLong\n);\n\nuint256 cumulativeBorrowingFactor = getCumulativeBorrowingFactor(dataStore, market.marketToken, isLong);\n\nuint256 delta = durationInSeconds * borrowingFactorPerSecond;\n\nuint256 nextCumulativeBorrowingFactor = cumulativeBorrowingFactor + delta;\n\nreturn (nextCumulativeBorrowingFactor, delta);\n```