xanoutas/solidity-security-findings huggingface dataset:
First staker staking can lead to unfair profiting 
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Core/contracts/LQTY/LQTYStaking.sol#L104
https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Core/contracts/LQTY/LQTYStaking.sol#L118


# Vulnerability details

## Impact
A caller is able to drain all of the fees from the pool if the caller stakes prior to `totalLQTYStaked`, in the `LQTYStaking` contract, being greater than 0. 

When the protocol is first deployed, `F_LUSD` is zero. It is increased when troves are opened. If a caller stakes while `totalLQTYStaked == 0`, `_updateUserSnapshots` saves `F_LUSD` as zero for the caller. When the caller unstakes, his stake is multiplied by the result of the current `F_LUSD` minus the `F_LUSD_Snapshot`, which in this case is zero, divided by `DECIMAL_PRECISION`. The callers stake has to be greater than `F_LUSD` for the caller to receive all the fees. If the caller calls stake prior to calling unstake, he will not be able to receive `F_LUSD` amount of fees because `_updateUserSnapshots` will update his `F_LUSD_Snapshot` to `F_LUSD`.

When a caller calls the unstake function `_getPendingLUSDGain` is called before `_updateUserSnapshots`. As such F_LUSD_Snapshot for said caller will be 0. 

If tokens can only be created by opening a trove a caller is able to open a trove *without* increasing `F_LUSD` if `totalLQTYStaked == 0` because `F_LUSD` doesn’t increase while `totalLQTYStaked == 0`. The caller can then stake those tokens. 


## Proof of Concept
The caller stakes setting his `F_LUSD_Snapshot` to zero since `F_LUSD` is zero when `LQTYStaking` is first deployed.

```solidity
function stake(uint _LQTYamount) external override {
        _requireNonZeroAmount(_LQTYamount);

        uint currentStake = stakes[msg.sender];

        address[] memory collGainAssets;
        uint[] memory collGainAmounts;
        uint LUSDGain;
        // Grab any accumulated collateral and LUSD gains from the current stake
        if (currentStake != 0) {
            (collGainAssets, collGainAmounts) = _getPendingCollateralGain(msg.sender);
            LUSDGain = _getPendingLUSDGain(msg.sender);
        }
    
       _updateUserSnapshots(msg.sender);
...snip...

function _updateUserSnapshots(address _user) internal {
        address[] memory collaterals = collateralConfig.getAllowedCollaterals();
        uint[] memory amounts = new uint[](collaterals.length);
        for (uint i = 0; i < collaterals.length; i++) {
            address collateral = collaterals[i];
            snapshots[_user].F_Collateral_Snapshot[collateral] = F_Collateral[collateral];
            amounts[i] = F_Collateral[collateral];
        }
        uint fLUSD = F_LUSD;
        snapshots[_user].F_LUSD_Snapshot = fLUSD;
        emit StakerSnapshotsUpdated(_user, collaterals, amounts, fLUSD);
    }
```

The caller waits while other callers open troves. If BorrowOperations isn't in recovery mode `_triggerBorrowingFee` runs which calls `increaseF_LUSD` which increases `F_LUSD`.
No check for active sequencer
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/BorrowerOperations.sol#L181
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/BorrowerOperations.sol#L289
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/BorrowerOperations.sol#L383


# Vulnerability details

## Impact
The protocol will operate at the previous (stale) rates.

## Proof of Concept
Chainlink recommends that all Optimistic L2 oracles consult the Sequencer Uptime Feed to ensure that the sequencer is live before trusting the data returned by the oracle, even if PriceFeed it is not part of the scope, this finding still make sense as the fetchPrice functionality it used widely in the part of the code that is managing the code like openTrove or closeTrove from BorrowingOperations contract.

https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/BorrowerOperations.sol#L181
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/BorrowerOperations.sol#L289
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/BorrowerOperations.sol#L383

If the Sequencer goes down, oracle data will not be kept up to date, and thus could become stale. However, users are able to continue to interact with the protocol directly through the L1 optimistic rollup contract. You can review Chainlink docs on L2 Sequencer Uptime Feeds for more details on this.
--> https://docs.chain.link/data-feeds/l2-sequencer-feeds/

## Tools Used
Manual review

## Recommended Mitigation Steps
Add a check for the sequencer and if the sequencer is down switch to the Trello oracle as you are doing with other flows inside the fetchPrice logic.
Use of strict condition can be manipulated
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Vault/contracts/ReaperVaultERC4626.sol#L66-L68


# Vulnerability details

## Impact
The use of strict condition can be manipulated by attackers, which can lead to unforeseen consequences. Use >= and <= instead. 


## Proof of Concept
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Vault/contracts/ReaperVaultERC4626.sol#L66-L68

## Tools Used
Manual review

## Recommended Mitigation Steps
Use loose condition instead like  >= and <= instead.
Address(0) check on array of addresses is not performed
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Vault/contracts/ReaperStrategyGranarySupplyOnly.sol#L65


# Vulnerability details

## Impact
Likelihood-Impact = Severity
Low-High = Medium

## Proof of Concept
https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Vault/contracts/ReaperStrategyGranarySupplyOnly.sol#L65

`function initialize(
        address _vault,
        address[] memory _strategists,
        address[] memory _multisigRoles,// @audit array both length check
        IAToken _gWant
    )`
calls to another `__ReaperBaseStrategy_init()` in contract `ReaperBaseStrategyv4.sol` which is inherited in ReaperStrategyGranarySupplyOnly.sol

If the array of addresses are not checked then it could lead to something devastating during initialization

## Tools Used
VSCode, Manual Code Review

## Recommended Mitigation Steps

Check if both the array of addresses are not address 0
Max approve will not work for tokens that do not support it 
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Vault/contracts/abstract/ReaperBaseStrategyv4.sol#L74


# Vulnerability details

## Impact
Max approve does not work for all tokens types

## Proof of Concept
Inside the ReaperBaseStrategyv4 contract initializers, the contract is doing a max approve for the vault over the underlying asset, however this will not work for all tokens types

https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Vault/contracts/abstract/ReaperBaseStrategyv4.sol#L74

## Tools Used
Manual review

## Recommended Mitigation Steps
Remove the max approve and approve only necessary amounts inside the flows that requires this or never use  tokens that does not support max approve.
Improper Management of Critical Market Condition
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Core/contracts/BorrowerOperations.sol#L597-L600
https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Core/contracts/BorrowerOperations.sol#L620-L622
https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Core/contracts/BorrowerOperations.sol#L624-L626


# Vulnerability details

## Impact

The `BorrowerOperations::_requireValidAdjustmentInCurrentMode` validation function will apply a weak level of validation, causing the system to magnify its critical market conditions when in recovery mode.

In detail, both `BorrowerOperations::_requireICRisAboveCCR` and `BorrowerOperations::_requireNewICRisAboveOldICR` apply **inclusive conditionals** rather than non-inclusive ones when comparing the ICR with the CCR as well as the new ICR with the old ICR. 

This can cause a position to retain the same ICR and exaggerate the volatile collateral in use by the system that triggered the recovery fault in the first place.

## Proof of Concept

As a proper demonstration of the vulnerability would require multiple lines of code to demonstrate, the following transaction flow has been created instead:
- Critical market conditions trigger the system's recovery mode due to a volatile asset
- Asset is anticipated to drop further in a downward trajectory
- A malicious party mints a debt at the exact ICR ratio permitted by the CCR as well as the same ICR ratio they had their original deposit in
- Bad debt is created at an unfavorable ratio further exaggerating the Ethos Reserve's market condition

## Tools Used

Manual review.

## Recommended Mitigation Steps

We advise stricter validations to be performed when the system is in recovery mode. Example mitigation steps include:
- Enforce a minimum delta between the old and new ICRs, potentially corresponding to the volatility of the asset
- Prevent debt creation beyond a certain ICR threshold
- Enforce a "maximum" debt cap on each trove
CommunityIssuance.sol – Stability pool can manipulate time stamps with the fund function to issue more oath than appropriate. 
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Core/contracts/LQTY/CommunityIssuance.sol#L84


# Vulnerability details

If lastDistributionTime is set to a date in the future, it would allow the issueOath() function to continue to mint tokens even after it should have stopped. This is because the if statement in issueOath() checks whether the current time is greater than lastDistributionTime, and if it is, it does not mint any more tokens.

Now, let's consider how lastDistributionTime could be set to a future date. The fund() function is the only function that sets lastDistributionTime, and it does so by adding the distributionPeriod to the current time.

For example, if distributionPeriod is set to 14 days (as it is in the contract), and the fund() function is called on February 1st at 12:00pm, the following will happen:

The rewardPerSecond variable will be set based on the amount of Oath tokens sent to the contract.
The lastDistributionTime variable will be set to February 15th at 12:00pm (14 days after the current time).
The lastIssuanceTimestamp variable will be set to February 1st at 12:00pm (the current time).
Now, let's say that StabilityPool wants to manipulate the contract to mint more tokens than appropriate. This can be done by calling the fund() function, which will set the lastDistributionTime variable to a date far in the future. This will allow the issueOath() function to continue minting tokens beyond the correct amount.

One way to fix this vulnerability is to avoid setting lastDistributionTime in the fund function, and instead use the lastIssuanceTimestamp to calculate the issuance of Oath tokens.This can be done by changing the calculation of the issuance variable in the issueOath function to use lastDistributionTime instead of lastIssuanceTimestamp, and removing the calculation of notIssued.

Here is an example of how the updated issueOath function might look:

function issueOath() external override returns (uint issuance) {
    _requireCallerIsStabilityPool();
    uint timePassed = block.timestamp.sub(lastIssuanceTimestamp);
    issuance = timePassed.mul(rewardPerSecond);
    totalOATHIssued = totalOATHIssued.add(issuance);
    lastIssuanceTimestamp = block.timestamp;
    emit TotalOATHIssuedUpdated(totalOATHIssued);
}

This way, the issuance of Oath tokens will only depend on the time elapsed since the last issuance, and will not be affected by the fund function.

manual review
Inexistent Slippage Evaluation
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Core/contracts/ActivePool.sol#L280
https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Core/contracts/ActivePool.sol#L282


# Vulnerability details

## Impact

The ecosystem of Ethos Reserve contains an [EIP-4626](https://eips.ethereum.org/EIPS/eip-4626) implementation of a vault meant to be integrated by its LUSD lending and borrowing system. **As per the standard's [Security Considerations](https://eips.ethereum.org/EIPS/eip-4626#security-considerations) itself**, slippage checks need to be introduced at the integration level as otherwise, the referenced interactions are fully prone to slippage-related vulnerabilities.

The `ActivePool` of the Ethos Reserve system is susceptible to all types of slippage related attacks (sandwich attacks, spot-price manipulations etc.) as an `IERC4626::deposit` / `IERC4626::withdraw` operation can be artificially created by a non-privileged EOA. 

Some example call-paths are as follows:

`TroveManager::liquidateTroves`
-> `ActivePool::sendCollateral`
--> `ActivePool::_rebalance`

`TroveManager::redeemCollateral`
-> `RedemptionHelper::redeemCollateral`
--> `ActivePool::sendCollateral`
---> `ActivePool::_rebalance`

As such, the arbitrage can be **exploited actively** by setting up the slippage-related conditions before executing either of the call-paths above.

## Proof of Concept

Slippage-related PoCs require extensive setup code set-up to demonstrate. For the purposes of this exhibit, we consider the EIP-4626 documentation linked as well as the explanation above sufficiently demonstrating the issue.

## Tools Used

Manual review, EIP documentation.

## Recommended Mitigation Steps

Adding slippage-related checks to automated integration points such as the one illustrated is difficult if not ineffective when based on user input as they can specify malicious slippage thresholds at the expense of the protocol.

A "true" solution to this issue would be a non-automatic rebalancing mechanism whereby deploying funds to the vault is done via a privileged role that is trusted with providing correct slippage bounds.

Alternatively, an on-chain price and share value measurement system can be crafted which would significantly increase the complexity of the project but retain the current automatic functionality in a decentralized and secure way.
Centralization Risk for trusted owners
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/ActivePool.sol#L125  https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/ActivePool.sol#L132  https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/ActivePool.sol#L138  https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/ActivePool.sol#L144  https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/ActivePool.sol#L214
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/BorrowerOperations.sol#L18
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/LQTY/CommunityIssuance.sol#L14  https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/LQTY/CommunityIssuance.sol#L67  https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/LQTY/CommunityIssuance.sol#L101  https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/LQTY/CommunityIssuance.sol#L120
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/LQTY/LQTYStaking.sol#L18  https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/LQTY/LQTYStaking.sol#L76
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Vault/contracts/ReaperVaultV2.sol#L21
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/StabilityPool.sol#L146
https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Core/contracts/TroveManager.sol#L18


# Vulnerability details

```
Contracts have owners with privileged rights to perform admin tasks and need to be trusted to not perform malicious updates or drain funds.
```
Lack of sanity check could block the vault
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Vault/contracts/ReaperVaultV2.sol#L123


# Vulnerability details

## Impact
All deposits will be blocked

## Proof of Concept

It is possible to set tvlCap as 0 as there are no sanity checks to prevent that, if that would happen to vault will be locked for deposits as there is a check at line #324 in _deposit function that will check the total future funds needs to be less or equal with tvlCap.


https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Vault/contracts/ReaperVaultV2.sol#L123

https://github.com/code-423n4/2023-02-ethos/blob/73687f32b934c9d697b97745356cdf8a1f264955/Ethos-Vault/contracts/ReaperVaultV2.sol#LL324C7-L324C7


## Tools Used
Manual review
## Recommended Mitigation Steps
Add a sanity check like the following, in the constructor to prevent this: 
``
require(tvlCap != 0, "Can not be set as 0");
``
StabilityPool.sol – Tracking scale factor changes
Audit: 2023-02-ethos-findings
Severity: MEDIUM

# Lines of code

https://github.com/code-423n4/2023-02-ethos/blob/main/Ethos-Core/contracts/StabilityPool.sol#L38


# Vulnerability details

The product-sum approach is used to efficiently and elegantly track deposits, collateral gains, and LQTY issuance. The use of a scale factor to ensure accurate tracking of the product P is a clever solution to the problem of Solidity floor division reaching 0. 

Notwithstanding, this methodology may be vulnerable to the following 2 significant risks:

1.Scale factor manipulation: There is a risk that malicious actors could attempt to manipulate the scale factor in order to exploit the system. For example, they could try to trigger a scale factor change in order to take advantage of precision loss and gain an unfair advantage over other depositors.
2.Inflationary risks: The use of a scale factor introduces inflationary risks, as the value of deposits and collateral gains are reduced over time due to the decreasing value of the scale factor. This could potentially impact the long-term value of deposits held by depositors.

Instead of using just the current scale factor approach, a combination of solutions can be an effective way to create a more robust system with fail-safes. By leveraging the strengths of different approaches and combining them in a thoughtful way, it's possible to create a system that is more accurate, more resilient, and more adaptable to changing conditions.

For example, the Stability Pool system could use a combination of continuous normalization and multi-level tracking to maintain accuracy over a large number of liquidations, while also avoiding precision loss and minimizing inflationary risks. By continuously normalizing P after each liquidation, the system can ensure that its value remains consistent over time. By tracking deposits and collateral gains at multiple levels of precision, the system can maintain accuracy even in the face of large numbers of liquidations.

Additionally, the system could use a fail-safe mechanism to detect and address any issues that arise with the scale factor or other aspects of the system. For example, the system could implement a threshold for the minimum value of P to prevent it from reaching zero and triggering precision loss. If P falls below this threshold, the system could automatically reset P and the scale factor, and start a new epoch to maintain accuracy and prevent inflationary risks.

Imposing limits on the rate or size of liquidations in certain situations may be another measure that may mitigate the scale factor manipulation.
Finally, to mitigate the inherent inflationary risk, the stability pool protocol could also implement several 
measures:

•Use a dynamic scale factor: Rather than using a fixed scale factor, the stability pool protocol could use a dynamic scale factor that adjusts over time to reflect changes in the value of the stability pool. For example, if the value of the stability pool increases significantly, the scale factor c