Farseen0/scar-pairs huggingface dataset:
MEDIUM severity: - Partial DoS: Although the function avoids running out of gas by processing refunds in batches, if a payee's transfer reverts (e.g., if the address is a contract that throws), the function will revert and block progress at that index, causing a stuck refund process.
- No handling of failed transfers: There is no mechanism to skip or handle addresses that consistently revert, so the contract can become stuck on a single problematic address.
- Potential for indefinite looping: If gas estimation is incorrect or the list is manipulated, the loop could still cause issues.. - Partial DoS: Although the function avoids running out of gas by processing refunds in batches, if a payee's transfer reverts (e.g., if the address is a contract that throws), the function will revert and block progress at that index, causing a stuck refund process.
- No handling of failed transfer...

Vulnerable code:
pragma solidity ^0.4.15;

contract CrowdFundSafe {
  address[] private refundAddresses;
  mapping(address => uint) public refundAmount;
  uint256 nextIdx;
  
  function refundSafe() public {
    uint256 i = nextIdx;
    while(i < refundAddresses.length && msg.gas > 200000) {
      refundAddresses[i].transfer(refundAmount[i]);
      i++;
    }
    nextIdx = i;
  }
}

Vulnerability type: - Partial DoS: Although the function avoids runnin
MEDIUM severity: - Uses pull pattern: Refunds are handled by letting users withdraw their own funds, which prevents DoS attacks caused by failing external calls.
- State changes before external call: The refund amount is set to zero before sending Ether, which mitigates reentrancy attacks.
- Potential minor issue: send() is used, which only forwards 2300 gas. This is generally safe, but if users are contracts that need more gas in their fallback function, refunds may silently fail. Consider using call with proper checks in newer Solidity versions.
- Overall, this contract is secure against the auction DoS vulnerability present in the previous example.. - Uses pull pattern: Refunds are handled by letting users withdraw their own funds, which prevents DoS attacks caused by failing external calls.
- State changes before external call: The refund amount is set to zero before sending Ether, which mitigates reentrancy attacks.
- Potential minor issue: s...

Vulnerable code:
pragma solidity ^0.4.15;

//Secure auction that cannot be DoS'd
contract SecureAuction {
  address currentFrontrunner;
  uint    currentBid;
  //Store refunds in mapping to avoid DoS
  mapping(address => uint) refunds;

  //Avoids "pushing" balance to users favoring "pull" architecture
  function bid() payable external {
    require(msg.value > currentBid);

    if (currentFrontrunner != 0) {
      refunds[currentFrontrunner] += currentBid;
    }

    currentFrontrunner = msg.sender;
    currentBid         = msg.value;
  }

  //Allows users to get their refund from auction
  function withdraw() external {
    //Do all state manipulation before external call to
    //avoid reentrancy attack
    uint refund = refunds[msg.sender];
    refunds[msg.sender] = 0;

    msg.sender.send(refund);
  }
}

Vulnerability type: - Uses pull pattern: Refunds are handled by lettin
MEDIUM severity: - Vulnerability: Reentrancy Attack
- Issue: External call to `recipient.transfer(amount)` is made before state is updated.
- Fix: Use Checks-Effects-Interactions pattern.

Fixed Code:

contract SecureWithChecks {
  mapping(address => uint) public balances;

  function withdraw(address payable recipient, uint amount) public {
    require(balances[msg.sender] >= amount, "Insufficient funds");
    balances[msg.sender] -= amount;
    recipient.transfer(amount);
  }
}. - Vulnerability: Reentrancy Attack
- Issue: External call to `recipient.transfer(amount)` is made before state is updated.
- Fix: Use Checks-Effects-Interactions pattern.

Fixed Code:

contract SecureWithChecks {
  mapping(address => uint) public balances;

  function withdraw(address payable recipi...

Vulnerable code:
contract Vulnerable {
  mapping(address => uint) public balances;

  function withdraw(address payable recipient, uint amount) public {
    balances[msg.sender] -= amount;
    recipient.transfer(amount);
  }
}

Vulnerability type: - Vulnerability: Reentrancy Attack
- Issue: Extern
MEDIUM severity: - Vulnerability: Integer Underflow/Overflow
- Issue: Subtraction/addition without bounds checks can lead to unintended behavior.
- Fix: Use SafeMath library.

Fixed Code:

contract SecureMath {
  using SafeMath for uint;

  mapping(address => uint) public balances;

  function transfer(address recipient, uint amount) public {
    balances[msg.sender] = balances[msg.sender].sub(amount);
    balances[recipient] = balances[recipient].add(amount);
  }
}. - Vulnerability: Integer Underflow/Overflow
- Issue: Subtraction/addition without bounds checks can lead to unintended behavior.
- Fix: Use SafeMath library.

Fixed Code:

contract SecureMath {
  using SafeMath for uint;

  mapping(address => uint) public balances;

  function transfer(address recip...

Vulnerable code:
contract VulnerableMath {
  mapping(address => uint) public balances;

  function transfer(address recipient, uint amount) public {
    balances[msg.sender] -= amount;
    balances[recipient] += amount;
  }
}

Vulnerability type: - Vulnerability: Integer Underflow/Overflow
- Issu
MEDIUM severity: - Vulnerability: Uninitialized Storage
- Issue: The `owner` variable is not declared or initialized.
- Fix: Initialize storage variables like `owner` in the constructor.

Fixed Code:

contract InitializedStorage {
  mapping(address => uint) public balances;
  address public owner;

  constructor() {
    owner = msg.sender;
    balances[msg.sender] = 0;
  }

  function setBalance(address _user, uint _amount) public {
    require(msg.sender == owner);
    balances[_user] = _amount;
  }
}. - Vulnerability: Uninitialized Storage
- Issue: The `owner` variable is not declared or initialized.
- Fix: Initialize storage variables like `owner` in the constructor.

Fixed Code:

contract InitializedStorage {
  mapping(address => uint) public balances;
  address public owner;

  constructor() {...

Vulnerable code:
contract UninitializedStorage {
  mapping(address => uint) public balances;

  function setBalance(address _user, uint _amount) public {
    require(msg.sender == owner);
    balances[_user] = _amount;
  }
}

Vulnerability type: - Vulnerability: Uninitialized Storage
- Issue: Th
MEDIUM severity: - Vulnerability: Denial of Service (DoS) via gas exhaustion
- Issue: Unbounded growth of the `data` array can lead to high gas cost and blocking behavior.
- Fix: Limit array size.

Fixed Code:

contract SecureDoS {
  uint[] public data;

  function addData(uint _value) public {
    require(data.length < 100, "Array too large");
    data.push(_value);
  }
}. - Vulnerability: Denial of Service (DoS) via gas exhaustion
- Issue: Unbounded growth of the `data` array can lead to high gas cost and blocking behavior.
- Fix: Limit array size.

Fixed Code:

contract SecureDoS {
  uint[] public data;

  function addData(uint _value) public {
    require(data.leng...

Vulnerable code:
contract DoS {
  uint[] public data;

  function addData(uint _value) public {
    data.push(_value);
  }
}

Vulnerability type: - Vulnerability: Denial of Service (DoS) via gas e
MEDIUM severity: - Vulnerability: Infinite loop causing out-of-gas error
- Fix: Use `gasleft()` to monitor available gas and exit gracefully.

Fixed Code:

contract SecureGasLimitation {
  function consumeGas() public {
    while (gasleft() > 10000) {
      // Do something
    }
    revert("Out of gas");
  }
}. - Vulnerability: Infinite loop causing out-of-gas error
- Fix: Use `gasleft()` to monitor available gas and exit gracefully.

Fixed Code:

contract SecureGasLimitation {
  function consumeGas() public {
    while (gasleft() > 10000) {
      // Do something
    }
    revert("Out of gas");
  }
}

Vulnerable code:
contract GasLimitation {
  function consumeGas() public {
    while (true) {
      // Do something that consumes gas
    }
  }
}

Vulnerability type: - Vulnerability: Infinite loop causing out-of-gas
MEDIUM severity: - Vulnerability: Unchecked External Call
- Issue: Does not verify the success of the external call.
- Fix: Check the return value of the call.

Fixed Code:

contract SecureExternalCall {
  function transferFunds(address _receiver, uint _amount) public {
    require(_receiver != address(0));
    (bool success, ) = _receiver.call{value: _amount}("");
    require(success, "Transfer failed");
  }
}. - Vulnerability: Unchecked External Call
- Issue: Does not verify the success of the external call.
- Fix: Check the return value of the call.

Fixed Code:

contract SecureExternalCall {
  function transferFunds(address _receiver, uint _amount) public {
    require(_receiver != address(0));
    (boo...

Vulnerable code:
contract VulnerableExternalCall {
  function transferFunds(address _receiver, uint _amount) public {
    require(_receiver != address(0));
    _receiver.call.value(_amount)("");
  }
}

Vulnerability type: - Vulnerability: Unchecked External Call
- Issue:
MEDIUM severity: Reentrancy vulnerability — external call made before state update.. Reentrancy vulnerability — external call made before state update.

Vulnerable code:
pragma solidity ^0.8.0;

contract ReentrancyExample {
    mapping(address => uint256) public balances;

    function deposit() public payable {
        balances[msg.sender] += msg.value;
    }

    function withdraw(uint256 _amount) public {
        require(balances[msg.sender] >= _amount, "Insufficient balance");
        (bool sent, ) = msg.sender.call{value: _amount}("");
        require(sent, "Failed to send Ether");
        balances[msg.sender] -= _amount;
    }
}

Vulnerability type: Reentrancy vulnerability — external call made befo
MEDIUM severity: Access control vulnerability — anyone can update the logic address.. Access control vulnerability — anyone can update the logic address.

Vulnerable code:
pragma solidity ^0.8.0;

contract InsecureUpgradeability {
    address public logicAddress;

    function updateLogicAddress(address _newAddress) public {
        logicAddress = _newAddress;
    }
}

Vulnerability type: Access control vulnerability — anyone can update t
MEDIUM severity: Phishing vulnerability — using tx.origin for authentication allows malicious contracts to hijack ownership.. Phishing vulnerability — using tx.origin for authentication allows malicious contracts to hijack ownership.

Vulnerable code:
pragma solidity ^0.8.0;

contract TxOriginExample {
    address public owner;

    constructor() {
        owner = msg.sender;
    }

    function transfer(address payable _to, uint256 _amount) public {
        require(tx.origin == owner, "Not owner");
        (bool sent, ) = _to.call{value: _amount}("");
        require(sent, "Transfer failed");
    }
}

Vulnerability type: Phishing vulnerability — using tx.origin for authe
MEDIUM severity: Underflow vulnerability — subtraction underflows when counter is zero.. Underflow vulnerability — subtraction underflows when counter is zero.

Vulnerable code:
pragma solidity ^0.8.0;

contract UnderflowExample {
    uint8 public counter = 0;

    function decrement() public {
        counter = counter - 1;
    }
}

Vulnerability type: Underflow vulnerability — subtraction underflows w
MEDIUM severity: Dangerous use of selfdestruct — may result in asset loss or contract deletion.. Dangerous use of selfdestruct — may result in asset loss or contract deletion.

Vulnerable code:
pragma solidity ^0.8.0;

contract SelfDestructExample {
    address public owner;

    constructor() {
        owner = msg.sender;
    }

    function destroy() public {
        require(msg.sender == owner, "Only owner can destroy");
        selfdestruct(payable(msg.sender));
    }
}

Vulnerability type: Dangerous use of selfdestruct — may result in asse
MEDIUM severity: The `increaseRedemptionFee` function in the `DepositRedemption` contract allows signers to approve a. The `increaseRedemptionFee` function in the `DepositRedemption` contract allows signers to approve a signable bitcoin transaction with a higher fee, in the event that the network is congested and miners are not approving the lower-fee transaction. This function can be called every 4 hours, and each...

Vulnerable code:
```\nrequire(block.timestamp >= _d.withdrawalRequestTime + TBTCConstants.getIncreaseFeeTimer(), "Fee increase not yet permitted");\n```\n```\nuint256 _previousOutputValue = DepositUtils.bytes8LEToUint(_previousOutputValueBytes);\n_newOutputValue = DepositUtils.bytes8LEToUint(_newOutputValueBytes);\nrequire(_previousOutputValue.sub(_newOutputValue) == _d.initialRedemptionFee, "Not an allowed fee step");\n```\n```\nrequire(\n    _d.utxoSize().sub(_fundingOutputValue) <= _d.initialRedemptionFee * 5,\n    "Fee unexpectedly very high"\n);\n```
MEDIUM severity: This vulnerability is characterized by a discrepancy between the uncommented code and the documentat. This vulnerability is characterized by a discrepancy between the uncommented code and the documentation's comment. Specifically, the code snippet appears to set multiple interfaces for the ERC1820Implementer, including AMP_INTERFACE_NAME and ERC20_INTERFACE_NAME, but the documentation's comment only...

Vulnerable code:
```\nERC1820Implementer._setInterface(AMP_INTERFACE_NAME);\nERC1820Implementer._setInterface(ERC20_INTERFACE_NAME);\n// ERC1820Implementer._setInterface(ERC777_INTERFACE_NAME);\n```\n```\n/**\n * @notice Indicates a supply refund was executed\n * @param supplier Address whose refund authorization was executed\n * @param partition Partition from which the tokens were transferred\n * @param amount Amount of tokens transferred\n */\nevent SupplyRefund(\n    address indexed supplier,\n    bytes32 indexed partition,\n    uint256 amount,\n    uint256 indexed nonce\n);\n```
MEDIUM severity: The `MSDController._withdrawReserves` function allows the owner to mint the difference between an MS. The `MSDController._withdrawReserves` function allows the owner to mint the difference between an MSD asset's accumulated debt and earnings. This function is responsible for updating the token's debt and minting the corresponding amount to the owner. However, it does not ensure that the interest is...

Vulnerable code:
```\nfunction _withdrawReserves(address _token, uint256 _amount)\n    external\n    onlyOwner\n    onlyMSD(_token)\n{\n    (uint256 _equity, ) = calcEquity(_token);\n\n    require(_equity >= _amount, "Token do not have enough reserve");\n\n    // Increase the token debt\n    msdTokenData[_token].debt = msdTokenData[_token].debt.add(_amount);\n\n    // Directly mint the token to owner\n    MSD(_token).mint(owner, _amount)\n```
MEDIUM severity: The vulnerability in `MultiInvoker._latest` and `Vault` calculations of `closable` values can lead t. The vulnerability in `MultiInvoker._latest` and `Vault` calculations of `closable` values can lead to incorrect liquidations in certain edge cases. The `closable` value is calculated as the maximum possible position size that can be closed, considering pending position updates. However, in the curre...

Vulnerable code:
```\nfor (uint256 id = context.local.latestId + 1; id < context.local.currentId; id++) {\n    _processPendingPosition(context, _loadPendingPositionLocal(context, account, id));\n}\n```\n```\nfunction _update(\n    context,\n    account,\n    newOrder,\n    collateral,\n    protected) {\n    _loadUpdateContext(context, account);\n    context.currentPosition.local.update(collateral);\n    _processPendingPosition(context, context.currentPosition.local);\n    _invariant(context, account, newOrder, collateral, protected);\n```\n```\nfor (uint256 id = local.latestId + 1; id <= local.currentId; id++) {\n    Position memory pendingPosition = market.pendingPositions(account, id);\n    pendingPosition.adjust(latestPosition);\n\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```\npending positions\nfor (uint256 id = marketContext.local.latestId + 1; id <= marketContext.local.currentId; id++) {\n    previousClosable = _loadPosition(\n        marketContext,\n        marketContext.currentAccountPosition = registration.market.pendingPositions(address(this), id),\n        previousClosable\n    );\n}\n```
MEDIUM severity: The `_previewWithdraw` function in `AuctionInternal.sol` is vulnerable to an underflow condition due. The `_previewWithdraw` function in `AuctionInternal.sol` is vulnerable to an underflow condition due to the total number of contracts sold (`totalContractsSold`) exceeding the total number of contracts available in the auction (`auction.totalContracts`). This underflow occurs when multiple orders ar...

Vulnerable code:
```\nit("previewWithdraw reverts if buyer has too many contracts", async () => {\n    assert.isEmpty(await auction.getEpochsByBuyer(addresses.buyer1));\n\n    await asset.connect(signers.buyer1).approve(addresses.auction, ethers.constants.MaxUint256);\n\n    const totalContracts = await auction.getTotalContracts(epoch);\n    await auction.addLimitOrder(\n        epoch,\n        fixedFromFloat(params.price.max),\n        totalContracts.mul(2)\n    );\n\n    await auction.addLimitOrder(\n        epoch,\n        fixedFromFloat(params.price.max),\n        totalContracts.div(2)\n    );\n\n    const epochByBuyer = await auction.getEpochsByBuyer(addresses.buyer1);\n\n    assert.equal(epochByBuyer.length, 1);\n    assert.bnEqual(epochByBuyer[0], epoch);\n\n    await expect(auction.callStatic["previewWithdraw(uint64)"](epoch)).to.be.reverted;\n});\n```
MEDIUM severity: The vulnerability arises when multiple Transceivers are involved in a transaction, and the sender en. The vulnerability arises when multiple Transceivers are involved in a transaction, and the sender encodes Transceiver instructions in an incorrect order. Specifically, the current logic relies on the assumption that the sender will encode instructions in the order of increasing Transceiver registrat...

Vulnerable code:
```\nfor (uint256 i = 0; i < instructionsLength; i++) {\n    TransceiverInstruction memory instruction;\n    (instruction, offset) = parseTransceiverInstructionUnchecked(encoded, offset);\n\n    uint8 instructionIndex = instruction.index;\n\n    // The instructions passed in have to be strictly increasing in terms of transceiver index\n    if (i!= 0 && instructionIndex <= lastIndex) {\n        revert UnorderedInstructions();\n    }\n    lastIndex = instructionIndex;\n\n    instructions[instructionIndex] = instruction;\n}\n```
MEDIUM severity: This vulnerability is a result of a misleading comment in the StakingContract's code. The comment cl. This vulnerability is a result of a misleading comment in the StakingContract's code. The comment claims that the `onlyActiveOperator` modifier ensures that the caller is the admin, which may lead developers to believe that the modifier is checking for the admin's identity. However, upon closer insp...

Vulnerable code:
```\nmodifier onlyActiveOperator(uint256 _operatorIndex) {\n    _onlyActiveOperator(_operatorIndex);\n}\n```
MEDIUM severity: The Merkle leaf values for `_clubDivsMerkleRoot` in FootiumAcademy are calculated by concatenating `. The Merkle leaf values for `_clubDivsMerkleRoot` in FootiumAcademy are calculated by concatenating `clubId` and `divisionTier` using `abi.encodePacked`, resulting in a 64-byte value. This is problematic because it allows for collisions between the calculated leaf values and the internal nodes of the...

Vulnerable code:
```\n* WARNING: You should avoid using leaf values that are 64 bytes long prior to hashing, or use a hash function other than keccak256 for hashing leaves.\n* This is because the concatenation of a sorted pair of internal nodes in the merkle tree could be reinterpreted as a leaf value.\n```\n```\nif (\n   !MerkleProofUpgradeable.verify(\n        divisionProof,\n        _clubDivsMerkleRoot,\n        keccak256(abi.encodePacked(clubId, divisionTier))\n    )\n)\n```
MEDIUM severity: The LToken implementation does not fully adhere to the specifications outlined in EIP-4626, a widely. The LToken implementation does not fully adhere to the specifications outlined in EIP-4626, a widely-adopted standard for tokenized lending protocols. Specifically, the `maxMint` function, as implemented, returns the maximum amount of shares that can be minted without causing a revert, which is set...

Vulnerable code:
```\nfunction maxMint(address) public view virtual returns (uint256) {\n    return type(uint256).max;\n}\n```
MEDIUM severity: The GMXAdapter contract, which inherits from BaseExchangeAdapter, is an implementation contract for . The GMXAdapter contract, which inherits from BaseExchangeAdapter, is an implementation contract for a transparent proxy. The contract's initializer, `initialize()`, is vulnerable to exploitation by an attacker. This is because the initializer is publicly accessible and can be called by anyone, allow...

Vulnerable code:
```\nfunction initialize() external initializer {\n    __Ownable_init();\n}\n```
MEDIUM severity: The `flashRebalance` function in the provided code is responsible for executing a flash loan to obta. The `flashRebalance` function in the provided code is responsible for executing a flash loan to obtain a specified amount of tokens, `tokenIn`, which is intended to be the difference between the token balance before and after the flash loan. However, when calling the `_handleRebalanceIn` function, t...

Vulnerable code:
```\nfunction flashRebalance(\n    DestinationInfo storage destInfoOut,\n    DestinationInfo storage destInfoIn,\n    IERC3156FlashBorrower receiver,\n    IStrategy.RebalanceParams memory params,\n    FlashRebalanceParams memory flashParams,\n    bytes calldata data\n) external returns (uint256 idle, uint256 debt) {\n    if (params.amountIn > 0) {\n        IDestinationVault dvIn = IDestinationVault(params.destinationIn);\n\n        uint256 tokenInBalanceBefore = IERC20(params.tokenIn).balanceOf(address(this));\n\n        bytes32 flashResult = receiver.onFlashLoan(msg.sender, params.tokenIn, params.amountIn, 0, data);\n\n        uint256 tokenInBalanceAfter = IERC20(params.tokenIn).balanceOf(address(this));\n\n        if (\n            flashResult!= keccak256("ERC3156FlashBorrower.onFlashLoan")\n                || tokenInBalanceAfter < tokenInBalanceBefore + params.amountIn\n        ) {\n            revert Errors.FlashLoanFailed(params.tokenIn, params.amountIn);\n        }\n\n        if (params.tokenIn!= address(flashParams.baseAsset)) {\n            (uint256 debtDecreaseIn, uint256 debtIncreaseIn) = \n                _handleRebalanceIn(destInfoIn, dvIn, params.tokenIn, tokenInBalanceAfter);\n            idleDebtChange.debtDecrease += debtDecreaseIn;\n            idleDebtChange.debtIncrease += debtIncreaseIn;\n        } else {\n            idleDebtChange.idleIncrease += tokenInBalanceAfter - tokenInBalanceBefore;\n        }\n    }\n}\n```