xanoutas/solidity-security-findings huggingface dataset:
Insufficient Reward Balance Check Leading to Potential Protocol Insolvency
Audit: 2024-02-uniswap-foundation-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L570-L599


# Vulnerability details

## Impact
Detailed description of the impact of this finding.
description: The `notifyRewardAmount` function in the provided smart contract contains a vulnerability where the balance check for the reward token does not account for unclaimed rewards already owed to users. This oversight could lead to a state of protocol insolvency where the contract falsely believes it has the balance to cover new rewards, potentially preventing users from claiming what they are owed. The root cause of this vulnerability is the function's failure to subtract unclaimed rewards from the contract's balance before comparing it to the required balance for new rewards. The maximum impact is that users may be unable to withdraw their earned rewards, damaging trust in the protocol and disrupting its normal operation.
## Proof of Concept
Provide direct links to all referenced code in GitHub. Add screenshots, logs, or any other relevant proof that illustrates the concept.
https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L570-L599
## Tools Used

## Recommended Mitigation Steps
## Finding Recommendation:

To address the vulnerability identified in the `notifyRewardAmount` function, it is recommended to update the balance check to account for the unclaimed rewards that are already part of the contract's balance. This can be achieved by modifying the balance check logic to deduct the amount of unclaimed rewards from the total balance before verifying if the contract has sufficient funds to cover the new rewards to be distributed.

Additionally, it is advisable to implement a mechanism that tracks and deducts unclaimed rewards from the total balance when calculating available funds for new rewards. This will ensure that users are always able to withdraw their earned rewards without the risk of protocol insolvency due to inaccurate balance calculations.

By incorporating these improvements, the contract can mitigate the risk of users being unable to claim their rewards and maintain the solvency of the protocol. It is also recommended to conduct thorough testing and auditing to validate the changes and ensure the overall security and functionality of the reward distribution mechanism.


## Assessed type

Math
Insufficient Reward Balance Validation in notifyRewardAmount Function
Audit: 2024-02-uniswap-foundation-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L570-L599


# Vulnerability details

## Impact
Detailed description of the impact of this finding.
description: The `notifyRewardAmount` function in the contract has a vulnerability due to insufficient checks on the reward balance. Specifically, it fails to account for unclaimed rewards in the contract's balance when updating the reward rate and distribution period. This can lead to a situation where the contract's balance is not enough to cover all user rewards, potentially freezing user funds and rendering the contract unable to operate as it cannot fulfill reward withdrawals. The vulnerability arises from the assumption that the balance of the REWARD_TOKEN in the contract is adequate for new reward distributions, without isolating and deducting the unclaimed rewards already owed to stakers. The impact of this vulnerability is maximized if an approved notifier updates the reward amount to a value higher than the actual liquid balance in the contract, causing the contract to incorrectly calculate the new reward rate and promise more rewards than it can deliver.
## Proof of Concept
Provide direct links to all referenced code in GitHub. Add screenshots, logs, or any other relevant proof that illustrates the concept.
https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L570-L599
## Tools Used

## Recommended Mitigation Steps
Based on the identified vulnerability related to insufficient reward balance checks in the `notifyRewardAmount` function, the following recommendation can be made:

Recommendation:
1. Implement a comprehensive reward balance check mechanism that considers both the liquid balance available for new distributions and the unclaimed rewards owed to users.
2. Consider implementing a separate accounting mechanism to track unclaimed rewards and factor them into the balance check before notifying new rewards.
3. Ensure that approved notifiers are aware of the importance of accurately assessing the contract balance before calling `notifyRewardAmount`.
4. Regularly audit and monitor the contract's reward distribution process to identify and address any discrepancies in the reward balance.


## Assessed type

Math
Staking Contract Vulnerable to Inaccurate Token Accounting Due to Transfer-on-Fee or Deflationary Token Mechanics
Audit: 2024-02-uniswap-foundation-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L723-L735


# Vulnerability details

## Impact
Detailed description of the impact of this finding.
description: The function _withdraw in the staking contract contains a critical vulnerability due to the lack of validation after calling _stakeTokenSafeTransferFrom to transfer staked tokens. This function assumes that the full amount of tokens specified by _amount will be transferred to the deposit owner. However, if the staked token implements a transfer-on-fee or deflationary mechanism, the actual transferred amount could be less than the _amount due to fees deducted or tokens burned during the transfer. This assumption leads to inconsistent internal accounting, as the deposit balance, totalStaked, depositorTotalStaked, and earningPower are all decremented by _amount regardless of the actual amount transferred. This discrepancy could allow users to withdraw more tokens than they are entitled to, resulting in potential protocol insolvency as the contract may falsely represent more tokens than are actually held or available, leading to a shortfall when users attempt to withdraw their funds.
## Proof of Concept
Provide direct links to all referenced code in GitHub. Add screenshots, logs, or any other relevant proof that illustrates the concept.
https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L723-L735
## Tools Used

## Recommended Mitigation Steps
Finding Recommendation:
To address the vulnerability related to inconsistent balances when dealing with transfer-on-fee or deflationary tokens, it is recommended to implement a check after the `_stakeTokenSafeTransferFrom` operation to verify that the correct amount of tokens has been transferred. This check should compare the expected amount with the actual amount received by the `deposit.owner` and adjust the internal accounting (`deposit.balance`, `totalStaked`, `depositorTotalStaked`, `earningPower`) accordingly. By ensuring that the contract's accounting reflects the actual token balances, the risk of protocol insolvency due to discrepancies in token amounts can be mitigated. Additionally, consider implementing mechanisms to handle transfer fees or token burns to maintain accurate accounting and prevent unexpected outcomes.


## Assessed type

Invalid Validation
Incompatibility with Fee-Charging ERC20 Tokens Resulting in Fund Freezing in Vault Contract
Audit: 2024-02-uniswap-foundation-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L512-L532


# Vulnerability details

## Impact
Detailed description of the impact of this finding.
description: The Vault contract is vulnerable to incompatibility issues with ERC20 tokens that implement transfer fees. The `_transferAndCheckUnderlying()` function is designed to ensure the correct amount of tokens is received by the contract, but fails to account for tokens that deduct a fee upon transfer, causing the function to revert the transaction. This results in permanent or temporary freezing of funds or unclaimed yield when users attempt to deposit or sponsor using such fee-charging tokens, as the contract is unable to operate due to receiving less than the expected amount of tokens.
## Proof of Concept
Provide direct links to all referenced code in GitHub. Add screenshots, logs, or any other relevant proof that illustrates the concept.
https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L512-L532
## Tools Used

## Recommended Mitigation Steps
Finding Recommendation:
To address the vulnerability related to the incompatibility with fee-charging ERC20 tokens when depositing into the Vault contract, it is recommended to update the `_transferAndCheckUnderlying()` function to handle tokens that charge transfer fees. This can be achieved by adjusting the logic to account for the difference in the received amount due to transfer fees. Additionally, consider implementing a mechanism to allow for the successful deposit and sponsorship of fee-charging ERC20 tokens within the Vault contract. Testing with various fee-charging tokens is essential to ensure the compatibility and functionality of the contract. Regularly reviewing and updating the contract code to address potential vulnerabilities is also recommended to maintain the security and integrity of the smart contract system.


## Assessed type

DoS
Inaccurate Stake Accounting Due to Transfer-on-Fee or Deflationary Token Transfers
Audit: 2024-02-uniswap-foundation-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L638-L664


# Vulnerability details

## Impact
The borrowExactAmount function in the contract lacks proper authorization checks, allowing any user to borrow tokens against an NFT collateral. This omission enables unauthorized loans to be initiated against an NFT owner's collateral without restriction. The function first retrieves the NFT's ID and the token index, followed by syncing the lending user instance and obtaining the current ETH value of the collateralized NFT. Subsequently, it calculates the maximum borrowable amount of tokens based on the ETH value. However, it fails to verify whether the caller has the appropriate authorization to borrow against the specified NFT. As a result, any user can call this function and borrow tokens against any NFT without restriction or permission. This vulnerability poses significant risks, as it could lead to unwarranted debt for NFT owners and potential freezing of their NFT as collateral until the debt is resolved. The root cause of this vulnerability lies in the absence of proper access control mechanisms within the borrowExactAmount function, allowing unauthorized users to exploit the borrowing functionality without restriction.
## Proof of Concept
Provide direct links to all referenced code in GitHub. Add screenshots, logs, or any other relevant proof that illustrates the concept.
https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L638-L664
## Tools Used

## Recommended Mitigation Steps
Finding Recommendation:
1. Review the implementation of the `_stakeTokenSafeTransferFrom` function to ensure it properly handles transfer-on-fee or deflationary token transfers, taking into account the possibility of receiving less than the specified `_amount`.
2. Implement checks or mechanisms to verify the actual amount received when transferring tokens that apply fees or have deflationary mechanics.
3. Consider implementing a mechanism to correct internal balances if the actual amount received differs from the specified `_amount`.
4. Conduct thorough testing, including edge cases with transfer-on-fee or deflationary tokens, to ensure the contract's accounting and user balances are accurately maintained.
5. Regularly audit the contract for any potential vulnerabilities related to inconsistent token transfers and update the code accordingly.


## Assessed type

Invalid Validation
Insufficient Fund Check Leads to Potential Protocol Insolvency and Reward Freezing
Audit: 2024-02-uniswap-foundation-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L570-L599


# Vulnerability details

## Impact
Detailed description of the impact of this finding.
description: The `notifyRewardAmount` function in the staking contract contains a vulnerability that could result in protocol insolvency or the freezing of user funds due to an inaccurate calculation of the `scaledRewardRate` relative to the actual `REWARD_TOKEN` balance. This flaw arises because the check for a sufficient balance does not account for unclaimed rewards, potentially allowing the contract to commit to distributing more rewards than the balance can support. If the contract's token balance is insufficient, users may not be able to claim their earned rewards, leading to a loss of trust and functionality in the system. The lack of a robust mechanism to refresh or update the contract's balance after distributing rewards exacerbates the issue, increasing the risk of an insolvent state where the promised rewards exceed the available tokens.
## Proof of Concept
Provide direct links to all referenced code in GitHub. Add screenshots, logs, or any other relevant proof that illustrates the concept.
https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L570-L599
## Tools Used
Meta Scan
## Recommended Mitigation Steps
**Finding Recommendation:**

To address the vulnerability identified in the `notifyRewardAmount` function and prevent potential protocol insolvency or freezing of funds/unclaimed yield, it is recommended to implement the following measures:

1. **Regularly Audit and Reconcile Reward Token Balances:** Implement a mechanism to regularly audit and reconcile the contract's balance of `REWARD_TOKEN` to ensure that it accurately reflects the total rewards owed to users, including unclaimed rewards. This will help prevent scenarios where the contract promises more rewards than it can deliver.

2. **Update Reward Rate Calculation:** Modify the reward rate calculation process to account for any unclaimed rewards or outstanding balances from previous reward periods. Consider implementing a mechanism to distribute unclaimed rewards or handle outstanding balances before setting a new reward rate to prevent protocol insolvency.

3. **Enhance Authorization and Access Control:** Strengthen authorization and access control mechanisms to ensure that only trusted and verified reward notifier contracts are approved to call the `notifyRewardAmount` function. This will help mitigate the risk of unauthorized entities manipulating reward rates or causing protocol insolvency.

4. **Implement Emergency Withdrawal Mechanism:** Consider implementing an emergency withdrawal mechanism that allows users to withdraw their funds in case of protocol insolvency or freezing of funds. This mechanism can provide an additional layer of protection for users in case of unforeseen circumstances.

By implementing these recommendations, the proto
Potential Misattribution of Accrued Rewards Due to Missing Claim Logic in Beneficiary Alteration Function
Audit: 2024-02-uniswap-foundation-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L704-L718


# Vulnerability details

## Impact
Detailed description of the impact of this finding.
"description: The `_alterBeneficiary` function in the smart contract fails to claim rewards for the original beneficiary before reassigning the deposit to a new beneficiary. This oversight can result in the original beneficiary not receiving the rewards they have accrued, as the `earningPower` mapping is updated to reflect the new beneficiary's balance without accounting for the unclaimed rewards. Consequently, the new beneficiary could unjustly benefit from rewards earned by the previous holder, leading to potential theft of unclaimed yield or a contract failing to deliver promised returns to the rightful owner."
## Proof of Concept
Provide direct links to all referenced code in GitHub. Add screenshots, logs, or any other relevant proof that illustrates the concept.
https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L704-L718
## Tools Used
Meta Scan
## Recommended Mitigation Steps
Finding: High

Recommendation: Add a check in the `_alterBeneficiary` function to ensure that rewards accrued to the original beneficiary are claimed before changing the beneficiary. This can be achieved by including a call to a reward claiming function (e.g., `claimTribute()`) before updating the beneficiary. Additionally, consider implementing a more robust reward distribution mechanism to prevent potential misattribution of rewards in the future. Regularly review and update the contract logic to adhere to best practices for fair reward distribution.


## Assessed type

Invalid Validation
Front-Running Vulnerability in Reward Distribution Allowing Extraction of Miner-Extractable Value (MEV)
Audit: 2024-02-uniswap-foundation-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L753-L756


# Vulnerability details

## Impact
Detailed description of the impact of this finding.
description: The identified vulnerability stems from the potential for an attacker to engage in front-running within the `_checkpointGlobalReward` function of the staking contract. By monitoring the blockchain for transactions calling the `receiveRewards` function and placing a high gas fee transaction to deposit a substantial amount of tokens just before the `receiveRewards` transaction is confirmed, the attacker can manipulate the `rewardPerTokenAccumulatedCheckpoint` and `lastCheckpointTime` to reflect the inflated token amount. Consequently, when the `receiveRewards` transaction is processed, rewards are calculated and distributed based on this inflated stake, allowing the attacker to claim a disproportionate share of the rewards upon withdrawal. This manipulation effectively allows the attacker to extract miner-extractable value (MEV) and constitutes theft of unclaimed yield, severely impacting the fairness of reward distribution and resulting in financial losses for honest stakers.
## Proof of Concept
Provide direct links to all referenced code in GitHub. Add screenshots, logs, or any other relevant proof that illustrates the concept.
https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L753-L756
## Tools Used
Meta Scan
## Recommended Mitigation Steps
Finding Recommendation:
To address this vulnerability and prevent front-running attacks on the rewards distribution mechanism, it is recommended to implement safeguards such as:

1. Implementing a delay or lockup period before rewards can be claimed after a deposit is made to prevent attackers from quickly withdrawing their funds and rewards.
2. Implementing a cap on the amount of rewards that can be claimed based on the duration of staking, to prevent disproportionately large rewards for short staking periods.
3. Using secure timestamping techniques or oracle verification to ensure the accuracy of reward calculations and prevent manipulation of timing.
4. Auditing the contract code to identify and address any other potential vulnerabilities that could be exploited in a similar manner.

By implementing these safeguards, the contract can mitigate the risk of MEV extraction through front-running attacks and ensure a fair distribution of rewards to all stakers.


## Assessed type

MEV
Potential Exploitation of Outdated Reward Checkpoint in Staking Reward Calculation
Audit: 2024-02-uniswap-foundation-findings
Severity: HIGH

# Lines of code

https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L229-L234


# Vulnerability details

## Impact
Detailed description of the impact of this finding.
description: The `rewardPerTokenAccumulated` function in the provided Solidity code is vulnerable to the exploitation of outdated reward checkpoints in exceptional system states. This vulnerability arises because the function computes rewards based on the `rewardPerTokenAccumulatedCheckpoint` without updating it in response to changes in the system state that may prevent accurate reward distribution. If the system enters a state where the total staked amount (`totalStaked`) changes after a shutdown or similar exceptional condition, users could manipulate their rewards by transferring stakes and claiming rewards that are not rightfully theirs, based on the stale `rewardPerTokenAccumulatedCheckpoint`. This can result in unauthorized extraction of unclaimed yield, potentially leading to unjust enrichment at the expense of the protocol and its rightful users. The root cause is the absence of checks and balances to ensure that the checkpoint data reflects the current system state, and the maximum impact could be the theft or freezing of unclaimed yield, undermining the integrity of the reward distribution mechanism.
## Proof of Concept
Provide direct links to all referenced code in GitHub. Add screenshots, logs, or any other relevant proof that illustrates the concept.
https://github.com/code-423n4/2024-02-uniswap-foundation/blob/main/src/UniStaker.sol#L229-L234
## Tools Used
Meta Scan
## Recommended Mitigation Steps
Finding Recommendation:
To address the vulnerability identified in the code snippet, it is recommended to implement a mechanism that ensures the `rewardPerTokenAccumulatedCheckpoint` is updated consistently, even in special states where checkpoints are not normally updated. This could involve adding a check within the function to update the checkpoint if certain conditions are met, or implementing a separate function to handle checkpoint updates. Additionally, consider restricting user participation transfers when the system is in the special state to prevent exploitation of outdated data. Regularly auditing and monitoring the code for such vulnerabilities is also recommended to maintain the security and integrity of the protocol.


## Assessed type

Timing