xanoutas/solidity-security-findings huggingface dataset:
Delegatecal Loop : contracts/base/Multicall.sol#L12-L36
Audit: 2024-06-panoptic-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-06-panoptic/blob/main/contracts/base/Multicall.sol#L12-L36


# Vulnerability details

## Impact
An attacker could exploit the delegatecall-loop vulnerability by crafting malicious data that causes unexpected behavior when the delegatecall is executed inside a loop in a payable function. This could potentially result in unauthorized access to sensitive data, manipulation of contract state, or loss of funds. By repeatedly calling delegatecall within the loop, an attacker could potentially bypass security checks or manipulate the flow of execution in a way that benefits them. This vulnerability poses a high risk as it could lead to severe consequences if exploited by a malicious actor.

## Proof of Concept
Position :  https://github.com/code-423n4/2024-06-panoptic/blob/main/contracts/base/Multicall.sol#L12-L36

Code : 
```
function multicall(bytes[] calldata data) public payable returns (bytes[] memory results) {
    results = new bytes[](data.length);
    for (uint256 i = 0; i &lt; data.length; ) {
        (bool success, bytes memory result) = address(this).delegatecall(data[i]);

        if (!success) {
            // Bubble up the revert reason
            // The bytes type is ABI encoded as a length-prefixed byte array
            // So we simply need to add 32 to the pointer to get the start of the data
            // And then revert with the size loaded from the first 32 bytes
            // Other solutions will do work to differentiate the revert reasons and provide paranthetical information
            // However, we have chosen to simply replicate the the normal behavior of the call
            // NOTE: memory-safe because it reads from memory already allocated by solidity (the bytes memory result)
            assembly ("memory-safe") {
                revert(add(result, 32), mload(result))
            }
        }

        results[i] = result;

        unchecked {
            ++i;
        }
    }
}
```

## Tools Used
SET IN STONE : https://lab.setinstone.io

## Recommended Mitigation Steps

The vulnerability in the provided code snippet is the presence of a delegatecall inside a loop in a payable function. This can lead to potential reentrancy attacks, where an attacker can repeatedly call the multicall function and potentially drain the contract's Ether balance.

To rectify this vulnerability, you should ensure that the function being called by delegatecall is not payable and does not use msg.value. Here's a recommended approach:

1. Create a modifier , for instance onlyOwner, that restricts access to certain functions to only authorized users ( ie : the contract owner).
```

address public owner;

constructor() {
    owner = msg.sender; // Setting the contract deployer as the owner
}

modifier onlyOwner() {
    require(msg.sender == owner, "Caller is not the owner");
    _;
}
```



2. Make the multicall function non-payable and restrict its access to only the contract owner using the on
There is couple of issues with the privius code.
Audit: 2024-06-panoptic-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/tokens/ERC20Minimal.sol#L35
https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/tokens/ERC20Minimal.sol#L122


# Vulnerability details

## Impact
1. Corrected the syntax for mappings.

2. Fixed the unchecked block in the _mint function to increment totalSupply first and then update balanceOf[to].

3. Ensured the increment of totalSupply is within the unchecked block in _mint.

## Proof of Concept

1.Mapping Syntax:
//Solidity does not support the mapping syntax used in the code. The correct syntax for mappings should be mapping(address => uint256) instead of mapping(address account => uint256) and mapping(address => mapping(address => uint256)) instead of mapping(address owner => mapping(address spender => uint256)).

2. Unchecked Block in _mint Function:
//The unchecked block in _mint is misplaced. The increment of totalSupply should be within the unchecked block since that's the value that might overflow, although totalSupply should be incremented before updating the balanceOf[to].

3. Total Supply Overflow Check:
//There is no check to ensure totalSupply doesn't overflow. Although Solidity 0.8.0 and above has built-in overflow checks, the usage of unchecked blocks bypasses these checks. Ensure the increment is handled properly within the unchecked block if necessary. 

## Tools Used
1. Opinions from colleagues.
2. ChatGPT.
3. Knowledge

## Recommended Mitigation Steps

To ensure that your Solidity contract is secure and follows best practices, consider the following mitigation steps:

Correct Mapping Syntax:

Ensure that the mapping syntax adheres to Solidity's standards. Use mapping(address => uint256) for single-level mappings and mapping(address => mapping(address => uint256)) for nested mappings.
Proper Unchecked Block Usage:

Use the unchecked block only where necessary and ensure that critical operations like updating totalSupply and balanceOf are done correctly to prevent overflow or underflow issues.
Implement Overflow/Underflow Checks:

Although Solidity 0.8.x has built-in overflow/underflow checks, ensure that unchecked blocks are used judiciously and only where overflow/underflow is not a concern or is intentionally bypassed for specific reasons.
Balance and Total Supply Management:

Always ensure that the total supply and balances are updated in a consistent manner. Any minting or burning of tokens should be reflected accurately in the totalSupply and individual balanceOf mappings.
Follow Standard ERC-20 Practices:

Adhere to the ERC-20 token standard practices for functions like approve, transfer, and transferFrom. This ensures compatibility with other contracts and tools in the Ethereum ecosystem.
Event Emission:

Ensure that all state-changing operations emit the appropriate events. This provides transparency and traceability for actions performed on the blockc
the issue type ragarding expect return value for approve, transfer and we adding transfer from.
Audit: 2024-06-panoptic-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/tokens/interfaces/IERC20Partial.sol#L11
https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/tokens/interfaces/IERC20Partial.sol#L16
https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/tokens/interfaces/IERC20Partial.sol#L22
https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/tokens/interfaces/IERC20Partial.sol#L27


# Vulnerability details

## Impact
1. Standards Compliance:

2. Interface Incompatibility:

3. Security Considerations:

## Proof of Concept

1. The interface does not fully comply with the ERC20 standard, which expects certain functions to return a boolean value. This could lead to compatibility issues with tools, libraries, or contracts that strictly adhere to the ERC20 standard.

2. Contracts or services interacting with IERC20Partial expecting ERC20 functions with return values might face errors or unexpected behavior.

3. By not adhering to the ERC20 standard, there could be security implications, especially in contexts where the return value of approve, transfer, and transferFrom is critical for ensuring successful operations and preventing erroneous transfers or approvals.

1. https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/tokens/interfaces/IERC20Partial.sol#L11

2. https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/tokens/interfaces/IERC20Partial.sol#L22

3. https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/tokens/interfaces/IERC20Partial.sol#L27

4. Below the transfer we adding transferfrom.

function transferFrom(address from, address to, uint256 amount) external returns (bool);

## Discord, ChatGPT3.5, Discussions on Github.

## Recommended Mitigation Steps

1. Complying with ERC20: Including the return values ensures that the interface is fully compliant with the ERC20 standard.

2. Maintaining Compatibility: The interface remains compatible with tools, libraries, and contracts expecting the standard ERC20 interface.

3. Reducing Errors: Properly implementing the standard reduces the risk of errors or unexpected behavior in interactions with other contracts or services.


## Assessed type

ERC20
Pool deployment can be DoS'd through price manipulation
Audit: 2024-06-panoptic-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/PanopticFactory.sol#L230
https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/PanopticFactory.sol#L321


# Vulnerability details

During Pool deployment, Uniswap's `slot0.sqrtPriceX96` is being used to calculate required liquidity. This value represents the most recent price and can be easily manipulated.
```solidity
function _mintFullRange(
        IUniswapV3Pool v3Pool,
        address token0,
        address token1,
        uint24 fee
    ) internal returns (uint256, uint256) {
@>      (uint160 currentSqrtPriceX96, , , , , , ) = v3Pool.slot0();

        // For full range: L = Δx * sqrt(P) = Δy / sqrt(P)
        // We start with fixed token amounts and apply this equation to calculate the liquidity
        // Note that for pools with a tickSpacing that is not a power of 2 or greater than 8 (887272 % ts != 0),
        // a position at the maximum and minimum allowable ticks will be wide, but not necessarily full-range.
        // In this case, the `fullRangeLiquidity` will always be an underestimate in respect to the token amounts required to mint.
        uint128 fullRangeLiquidity;
        unchecked {
            // Since we know one of the tokens is WETH, we simply add 0.1 ETH + worth in tokens
            if (token0 == WETH) {
                fullRangeLiquidity = uint128(
                    Math.mulDiv96RoundingUp(FULL_RANGE_LIQUIDITY_AMOUNT_WETH, currentSqrtPriceX96)
                );
            } else if (token1 == WETH) {
                fullRangeLiquidity = uint128(
                    Math.mulDivRoundingUp(
                        FULL_RANGE_LIQUIDITY_AMOUNT_WETH,
                        Constants.FP96,
                        currentSqrtPriceX96
                    )
                );
            } else {
                // Find the resulting liquidity for providing 1e6 of both tokens
                uint128 liquidity0 = uint128(
                    Math.mulDiv96RoundingUp(FULL_RANGE_LIQUIDITY_AMOUNT_TOKEN, currentSqrtPriceX96)
                );
                uint128 liquidity1 = uint128(
                    Math.mulDivRoundingUp(
                        FULL_RANGE_LIQUIDITY_AMOUNT_TOKEN,
                        Constants.FP96,
                        currentSqrtPriceX96
                    )
                );

                // Pick the greater of the liquidities - i.e the more "expensive" option
                // This ensures that the liquidity added is sufficiently large
                fullRangeLiquidity = liquidity0 > liquidity1 ? liquidity0 : liquidity1;
            }
        }

        // The maximum range we can mint is determined by the tickSpacing of the pool
        // The upper and lower ticks must be divisible by `tickSpacing`, so
        // tickSpacing = 1: tU/L = +/-887272
        // tickSpacing = 10: tU/L = +/-887270
        // tickSpacing = 6
the lack of access controls on certain functions
Audit: 2024-06-panoptic-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/CollateralTracker.sol#L1516


# Vulnerability details

A potential vulnerability in the CollateralTracker contract is the lack of access controls on certain functions. This could potentially allow an attacker to manipulate the contract in their favor. For example, the `_computeSpread` function calculates the required amount of collateral for a spread position, but it does not check the caller's permission to execute this function. An attacker could potentially call this function with manipulated input data to reduce the required collateral for a spread position, allowing them to open a position with less capital than required.

Here's an example of how an attacker might exploit this vulnerability:

1. The attacker creates a spread position with a wide spread, which requires a large amount of collateral.
2. The attacker calls the `_computeSpread` function with manipulated input data, such as a lower pool utilization value, to reduce the required collateral for the spread position.
3. The contract calculates the new, lower collateral requirement based on the manipulated input data.
4. The attacker then opens the spread position with the reduced collateral requirement, allowing them to control a larger position with less capital.

To prevent this type of attack, the contract should include access controls on sensitive functions like `_computeSpread` to ensure that only authorized users can call them. Additionally, input validation should be implemented to prevent manipulation of input data.

Another vulnerability is the lack of checks on the `tokenId` parameter in the `_computeSpread` function. An attacker could potentially pass an invalid `tokenId` value to the function, causing the contract to throw an error or behave unexpectedly. To prevent this, the contract should include checks to ensure that the `tokenId` parameter is valid before processing it.

In summary, the CollateralTracker contract lacks access controls and input validation on sensitive functions, potentially allowing an attacker to manipulate the contract in their favor. To secure the contract, access controls should be implemented on sensitive functions, and input validation should be added to prevent manipulation of input data. To exploit this vulnerability, the attacker can follow these steps:

1. Analyze the smart contract: The attacker first needs to understand the contract's functionality and identify vulnerable functions. In this case, the `_computeSpread` function lacks access controls and can be manipulated.

2. Exploit the vulnerability: The attacker can create a custom script or use existing tools to call the vulnerable function with manipulated input data. The script should call the `_computeSpread` function, passing lower pool utilization values to reduce the required collateral for a spread position.

3. Open a position with the reduced collateral: Aft
integer overflow.
Audit: 2024-06-panoptic-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/CollateralTracker.sol#L401


# Vulnerability details

vulnerability in the CollateralTracker contract related to the `deposit` function. The vulnerability is the lack of input validation on the `assets` parameter, which could potentially lead to an integer overflow. An attacker could exploit this vulnerability to deposit a value larger than the maximum allowed by the `uint256` type, leading to potential security issues or incorrect contract behavior.

Here's an example of how an attacker might exploit this vulnerability:

1. The attacker creates a deposit transaction with a value larger than the maximum allowed by the `uint256` type.
2. The attacker submits the transaction to the contract.
3. The contract processes the transaction without input validation, allowing the integer overflow.
4. The contract mints an excessive amount of shares to the attacker's account.

To prevent this type of attack, the contract should include input validation to ensure that the `assets` parameter is within the acceptable range for the `uint256` type before processing it. Additionally, overflow and underflow checks should be implemented to prevent integer overflows and underflows.

The vulnerability lies in the `deposit` function, specifically the line where the `shares` variable is calculated:
```solidity
uint256 shares = Math.mul(assets, decimals);
```
In this line, the `assets` parameter is multiplied by the `decimals` constant without any overflow or underflow checks. An attacker could potentially manipulate the `assets` parameter to cause an integer overflow, leading to unintended behavior in the contract.

To exploit this vulnerability, an attacker could create a custom script or use existing tools to call the `deposit` function with a manipulated `assets` value larger than the maximum allowed by the `uint256` type.

Here's an example of how an attacker might exploit this vulnerability in a custom script:

```javascript
const { ethers } = require("ethers");

// Connect to the target contract
const provider = new ethers.providers.JsonRpcProvider("RPC_URL");
const targetContractAddress = "CONTRACT_ADDRESS";
const targetContractABI = []; // ABI of the CollateralTracker contract
const targetContract = new ethers.Contract(targetContractAddress, targetContractABI, provider);

// Attacker's address and private key
const attackerAddress = "ATTACKER_ADDRESS";
const attackerPrivateKey = "ATTACKER_PRIVATE_KEY";
const attacker = new ethers.Wallet(attackerPrivateKey, provider);

// Set up transaction parameters
const assets = "0x10000000000000000000000000000000000000000000000000000000000000001"; // Example assets value, larger than the maximum allowed by uint256
const decimals = 10_000; // decimals constant

// Perform the attack
async function exploitVulnerability() {
  // Set up transaction
  const tx = await targetContract.connect(attacker).deposit(ass
Sum vonalblity of smart contact 
Audit: 2024-06-panoptic-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/PanopticPool.sol#L1


# Vulnerability details

I will now find a vulnerability in the provided smart contract and explain it, as well as provide a code example of how it works.

The vulnerability lies in the `_getAvailablePremium` function, which calculates the available premium for a given position. The issue is that the function does not properly check for underflow when calculating the numerator in the following line:

```solidity
int256 numerator = int256(settledTokens.rightSlot()) * int256(grossPremiumLast.rightSlot() - premia.rightSlot());
```

If `settledTokens.rightSlot()` is set to the maximum value for `uint256` (2**256 - 1) and `grossPremiumLast.rightSlot()` is less than `premia.rightSlot()`, the subtraction `grossPremiumLast.rightSlot() - premia.rightSlot()` will result in an underflow, causing the value to wrap around to a very large number. This can result in the `numerator` variable having a much larger absolute value than intended, potentially leading to security vulnerabilities or incorrect contract behavior.

To exploit this vulnerability, an attacker could manipulate the `settledTokens` and `grossPremiumLast` variables to trigger the underflow, allowing them to claim a larger premium than they are entitled to.

Here is a code example that demonstrates the vulnerability:

```solidity

    // Trigger underflow in _getAvailablePremium
```


Here is the updated function with the added underflow check:

```solidity
function _getAvailablePremium(
    uint256 totalLiquidity,
    LeftRightUnsigned settledTokens,
    LeftRightUnsigned grossPremiumLast,
    LeftRightUnsigned premia,
    uint256[2][4] memory premiumAccumulatorsByLeg
) internal pure returns (LeftRightUnsigned memory availablePremium) {
    int256 numerator = int256(settledTokens.rightSlot()) * (int256(grossPremiumLast.rightSlot()) - int256(premia.rightSlot()));
    require(numerator >= 0, "Underflow detected in _getAvailablePremium");

    int256 denominator = int256(totalLiquidity) * 2 ** 64;
    int256 difference = int256(premiumAccumulatorsByLeg[0][0].rightSlot()) - int256(premiumAccumulatorsByLeg[0][1].rightSlot());

    int256 rightSlotValue = numerator / denominator;

    unchecked {
        availablePremium = LeftRightUnsigned
            .wrap(0)
            .toRightSlot(uint128(Math.min(uint256(rightSlotValue), type(uint256).max)))
            .toLeftSlot(uint128(difference));
    }
}
```

By addressing this vulnerability, the contract will ensure that the `numerator` value is not unintentionally increased due to underflow, improving the overall security of the smart contract.
Another vulnerability in the smart contract is the lack of access control in the `_mintPosition` function, which allows any user to mint options without proper authorization. This can lead to security issues and unintended behavior in the contract.

The `_mintPosition` func
Use of delegatecall in a payable function inside a loop
Audit: 2024-06-panoptic-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/base/Multicall.sol#L12-L36


# Vulnerability details

## Description
The Multicall contract uses the delegatecall proxy pattern (which takes user-provided calldata) in a payable function within a loop. This means that each delegatecall within the for loop will retain the msg.value of the transaction:
## Impact
The protocol does not currently use the msg.value in any meaningful way. However, if a future version or refactor of the core protocol introduced a more meaningful use of it, it could be exploited to tamper with the system arithmetic.
## Proof of Concept
https://github.com/code-423n4/2024-06-panoptic/blob/153f0d82440b7e63075d55b0659706531431145f/contracts/base/Multicall.sol#L12-L36
      /// @notice Performs multiple calls on the inheritor in a single transaction, and returns the data from each call.
    /// @param data The calldata for each call
    /// @return results The data returned by each call
    /// @audit-issue : No use of msg.value .
    function multicall(bytes[] calldata data) public payable returns (bytes[] memory results) {
        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; ) {
      (bool success, bytes memory result) = address(this).delegatecall(data[i]);
                if (!success) {
                assembly ("memory-safe") {
                    revert(add(result, 32), mload(result))
                }
            }
            results[i] = result;
            unchecked {
                ++i;
            }
        }
    }
## Exploit Scenario
Alice, a member of the Panoptic team, adds a new functionality to the core protocol that adjusts users’ balances according to the msg.value. Eve, an attacker, uses the multicall functionality to increase her ETH balance without actually sending funds from her account, thereby stealing funds from the system.

## Tools Used
Manual Review .
## Recommended Mitigation Steps
Short term, document the risks associated with the use of msg.value and ensure that all developers are aware of this potential attack vector. Long term, detail the security implications of all functions in both the documentation and the code to ensure that potential attack vectors do not become exploitable when code is
refactored or added.
## References 
● ”Two Rights Might Make a Wrong,” Paradigm
● https://solodit.xyz/issues/use-of-delegatecall-in-a-payable-function-inside-a-loop-trailofbits-yield-v2-pdf


## Assessed type

call/delegatecall