name
stringlengths
5
231
severity
stringclasses
3 values
description
stringlengths
107
68.2k
recommendation
stringlengths
12
8.75k
⌀
impact
stringlengths
3
11.2k
⌀
function
stringlengths
15
64.6k
`Goldigovernor._getProposalState()` shouldn't use `totalSupply`
medium
In `_getProposalState()`, it uses `Goldiswap(goldiswap).totalSupply()` during the comparison.\\n```\\n function _getProposalState(uint256 proposalId) internal view returns (ProposalState) {\\n Proposal storage proposal = proposals[proposalId];\\n if (proposal.cancelled) return ProposalState.Canceled;\\n else ...
We should introduce another mechanism for the quorum check rather than using `totalSupply`.
A proposal state might be changed unexpectedly.
```\\n function _getProposalState(uint256 proposalId) internal view returns (ProposalState) {\\n Proposal storage proposal = proposals[proposalId];\\n if (proposal.cancelled) return ProposalState.Canceled;\\n else if (block.number <= proposal.startBlock) return ProposalState.Pending;\\n else if (block.numb...
In `Goldivault.redeemYield()`, users can redeem more yield tokens using reentrancy
medium
Possible reentrancy in `Goldivault.redeemYield()` if `yieldToken` has a `beforeTokenTransfer` hook.\\nLet's assume `yt.totalSupply` = 100, `yieldToken.balance` = 100 and the user has 20 yt.\\nThe user calls `redeemYield()` with 10 yt.\\nThen `yt.totalSupply` will be changed to 90 and it will transfer `100 * 10 / 100 = ...
We should add a `nonReentrant` modifier to `redeemYield()`.
Malicious users can steal `yieldToken` using `redeemYield()`.
```\\n function redeemYield(uint256 amount) external {\\n if(amount == 0) revert InvalidRedemption();\\n if(block.timestamp < concludeTime + delay || !concluded) revert NotConcluded();\\n uint256 yieldShare = FixedPointMathLib.divWad(amount, ERC20(yt).totalSupply());\\n YieldToken(yt).burnYT(msg.sender, am...
Wrong validation in `Goldigovernor.cancel()`
medium
In `Goldigovernor.cancel()`, the proposer should have fewer votes than `proposalThreshold` to cancel his proposal.\\n```\\n function cancel(uint256 proposalId) external {\\n if(_getProposalState(proposalId) == ProposalState.Executed) revert InvalidProposalState();\\n Proposal storage proposal = proposals[proposa...
It should be modified like this.\\n```\\nif(msg.sender != proposal.proposer && GovLocks(govlocks).getPriorVotes(proposal.proposer, block.number - 1) > proposalThreshold) revert Error;\\n```\\n
A proposer can't cancel his proposal unless he decreases his voting power.
```\\n function cancel(uint256 proposalId) external {\\n if(_getProposalState(proposalId) == ProposalState.Executed) revert InvalidProposalState();\\n Proposal storage proposal = proposals[proposalId];\\n if(msg.sender != proposal.proposer) revert NotProposer();\\n if(GovLocks(govlocks).getPriorVotes(propo...
Users wouldn't cancel their proposals due to the increased `proposalThreshold`.
medium
When users call `cancel()`, it validates the caller's voting power with `proposalThreshold` which can be changed using `setProposalThreshold()`.\\n```\\n function setProposalThreshold(uint256 newProposalThreshold) external {\\n if(msg.sender != multisig) revert NotMultisig();\\n if(newProposalThreshold < MIN_PRO...
It would be good to cache `proposalThreshold` as a proposal state.
Users wouldn't cancel their proposals due to the increased `proposalThreshold`.
```\\n function setProposalThreshold(uint256 newProposalThreshold) external {\\n if(msg.sender != multisig) revert NotMultisig();\\n if(newProposalThreshold < MIN_PROPOSAL_THRESHOLD || newProposalThreshold > MAX_PROPOSAL_THRESHOLD) revert InvalidVotingParameter();\\n uint256 oldProposalThreshold = proposalThr...
`Goldilend.liquidate()` might revert due to underflow
medium
In `repay()`, there would be a rounding during the `interest` calculation.\\n```\\n function repay(uint256 repayAmount, uint256 _userLoanId) external {\\n Loan memory userLoan = loans[msg.sender][_userLoanId];\\n if(userLoan.borrowedAmount < repayAmount) revert ExcessiveRepay();\\n if(block.timestamp > ...
In `liquidate()`, `outstandingDebt` should be updated like the below.\\n```\\n /// @inheritdoc IGoldilend\\n function liquidate(address user, uint256 _userLoanId) external {\\n Loan memory userLoan = loans[msg.sender][_userLoanId];\\n if(block.timestamp < userLoan.endDate || userLoan.liquidated || userLoan.borr...
`liquidate()` might revert due to underflow.
```\\n function repay(uint256 repayAmount, uint256 _userLoanId) external {\\n Loan memory userLoan = loans[msg.sender][_userLoanId];\\n if(userLoan.borrowedAmount < repayAmount) revert ExcessiveRepay();\\n if(block.timestamp > userLoan.endDate) revert LoanExpired();\\n uint256 interestLoanRatio = F...
In `Goldigovernor`, wrong assumption of block time
medium
In `Goldigovernor.sol`, voting period/delay limits are set with 15s block time.\\n```\\n /// @notice Minimum voting period\\n uint32 public constant MIN_VOTING_PERIOD = 5760; // About 24 hours\\n\\n /// @notice Maximum voting period\\n uint32 public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks\\n\\n /// @n...
We should calculate these limits with 5s block time.
Voting period/delay limits will be set shorter than expected.
```\\n /// @notice Minimum voting period\\n uint32 public constant MIN_VOTING_PERIOD = 5760; // About 24 hours\\n\\n /// @notice Maximum voting period\\n uint32 public constant MAX_VOTING_PERIOD = 80640; // About 2 weeks\\n\\n /// @notice Minimum voting delay\\n uint32 public constant MIN_VOTING_DELAY = 1;\\n\\n ...
Queued transfers can become stuck on the source chain if Transceiver instructions are encoded in the incorrect order
high
In the case of multiple Transceivers, the current logic expects that a sender encodes Transceiver instructions in order of increasing Transceiver registration index, as validated in `TransceiverStructs::parseTransceiverInstructions`. Under normal circumstances, this logic works as expected, and the transaction fails wh...
When the transfer amount exceeds the current outbound capacity, verify the Transceiver instructions are ordered correctly before adding a message to the list of queued transfers.
The sender's funds are transferred to the NTT Manager when messages are queued. However, this queued message can never be executed if the Transceiver indices are incorrectly ordered and, as a result, the user funds remain stuck in the NTT Manager.\\nProof of Concept: Run the following test:\\n```\\ncontract TestWrongTr...
```\\n/* snip */\\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 incr...
Queued transfers can become stuck on the source chain if new Transceivers are added or existing Transceivers are modified before completion
high
When a sender transfers an amount that exceeds the current outbound capacity, such transfers are sent to a queue for delayed execution within `NttManager::_transferEntrypoint`. The rate limit duration is defined as an immutable variable determining the temporal lag between queueing and execution, with a typical rate li...
Consider passing no instructions into the delivery price estimation when the Transceiver index does not exist.
Missing Transceiver instructions prevents the total delivery price for the corresponding message from being calculated. This prevents any queued Transfers from being executed with the current list of transceivers. As a result, underlying sender funds will be stuck in the `NttManager` contract. Note that a similar issue...
```\\n/* snip */\\n// now check rate limits\\nbool isAmountRateLimited = _isOutboundAmountRateLimited(internalAmount);\\nif (!shouldQueue && isAmountRateLimited) {\\n revert NotEnoughCapacity(getCurrentOutboundCapacity(), amount);\\n}\\nif (shouldQueue && isAmountRateLimited) {\\n // emit an event to notify the u...
Silent overflow in `TrimmedAmount::shift` could result in rate limiter being bypassed
medium
Within `TrimmedAmount::trim`, there is an explicit check that ensures the scaled amount does not exceed the maximum uint64:\\n```\\n// NOTE: amt after trimming must fit into uint64 (that's the point of\\n// trimming, as Solana only supports uint64 for token amts)\\nif (amountScaled > type(uint64).max) {\\n revert Am...
Explicitly check the scaled amount in `TrimmedAmount::shift` does not exceed the maximum `uint64`.
A silent overflow in `TrimmedAmount::shift` could result in the rate limiter being bypassed, considering its usage in `NttManager::_transferEntryPoint`. Given the high impact and reasonable likelihood of this issue occurring, it is classified a MEDIUM severity finding.
```\\n// NOTE: amt after trimming must fit into uint64 (that's the point of\\n// trimming, as Solana only supports uint64 for token amts)\\nif (amountScaled > type(uint64).max) {\\n revert AmountTooLarge(amt);\\n}\\n```\\n
Disabled Transceivers cannot be re-enabled by calling `TransceiverRegistry::_setTransceiver` after 64 have been registered
medium
`TransceiverRegistry::_setTransceiver` handles the registering of Transceivers, but note that they cannot be re-registered as this has other downstream effects, so this function is also responsible for the re-enabling of previously registered but currently disabled Transceivers.\\n```\\nfunction _setTransceiver(address...
Move the placement of the maximum Transceivers validation to within the `else` block that is responsible for handling the registration of new Transceivers.
Under normal circumstances, this maximum number of registered Transceivers should never be reached, especially since the underlying Transceivers are upgradeable. However, while unlikely based on operational assumptions, this undefined behavior could have a high impact, and so this is classified as a MEDIUM severity fin...
```\\nfunction _setTransceiver(address transceiver) internal returns (uint8 index) {\\n /* snip */\\n if (transceiver == address(0)) {\\n revert InvalidTransceiverZeroAddress();\\n }\\n\\n if (_numTransceivers.registered >= MAX_TRANSCEIVERS) {\\n revert TooManyTransceivers();\\n }\\n\\n ...
NTT Manager cannot be unpaused once paused
medium
`NttManagerState::pause` exposes pause functionality to be triggered by permissioned actors but has no corresponding unpause functionality. As such, once the NTT Manager is paused, it will not be possible to unpause without a contract upgrade.\\n```\\nfunction pause() public onlyOwnerOrPauser {\\n _pause();\\n}\\n``...
```\\n// Add the line below\\n function unpause() public onlyOwnerOrPauser {\\n// Add the line below\\n _unpause();\\n// Add the line below\\n }\\n```\\n
The inability to unpause the NTT Manager could result in significant disruption, requiring either a contract upgrade or complete redeployment to resolve this issue.
```\\nfunction pause() public onlyOwnerOrPauser {\\n _pause();\\n}\\n```\\n
Transceiver invariants and ownership synchronicity can be broken by unsafe Transceiver upgrades
medium
Transceivers are upgradeable contracts integral to the cross-chain message handling of NTT tokens. While `WormholeTransceiver` is a specific implementation of the `Transceiver` contract, NTT Managers can integrate with Transceivers of any custom implementation.\\n`Transceiver::_checkImmutables` is an internal virtual f...
Consider making `Transceiver::_checkImmutables` and `Implementation::_setMigratesImmutables` private functions for Transceivers. If the `_checkImmutables()` function has to be overridden, consider exposing another function that is called inside `_checkImmutables` as follows:\\n```\\nfunction _checkImmutables() private ...
While this issue may require the owner of a Transceiver to misbehave, a scenario where a Transceiver is silently upgraded with a new NTT Manager or NTT Manager token can be problematic for cross-chain transfers and so is prescient to note.\\nProof of Concept: The below PoC calls the `_setMigratesImmutables()` function ...
```\\nfunction _initialize() internal virtual override {\\n // check if the owner is the deployer of this contract\\n if (msg.sender != deployer) {\\n revert UnexpectedDeployer(deployer, msg.sender);\\n }\\n\\n __ReentrancyGuard_init();\\n // owner of the transceiver is set to the owner of the ntt...
Asymmetry in Transceiver pausing capability
low
Pausing functionality is exposed via Transceiver::_pauseTransceiver; however, there is no corresponding function that exposes unpausing functionality:\\n```\\n/// @dev pause the transceiver.\\nfunction _pauseTransceiver() internal {\\n _pause();\\n}\\n```\\n
```\\n// Add the line below\\n /// @dev unpause the transceiver.\\n// Add the line below\\n function _unpauseTransceiver() internal {\\n// Add the line below\\n _unpause();\\n// Add the line below\\n }\\n```\\n
While not an immediate issue since the above function is not currently in use anywhere, this should be resolved to avoid cases where Transceivers could become permanently paused.
```\\n/// @dev pause the transceiver.\\nfunction _pauseTransceiver() internal {\\n _pause();\\n}\\n```\\n
Incorrect Transceiver payload prefix definition
low
The `WH_TRANSCEIVER_PAYLOAD_PREFIX` constant in `WormholeTransceiverState.sol` contains invalid ASCII bytes and, as such, does not match what is written in the inline developer documentation:\\n```\\n/// @dev Prefix for all TransceiverMessage payloads\\n/// This is 0x99'E''W''H'\\n/// @notice Magic string (constan...
Update the constant definition to use the correct prefix corresponding to the documented string:\\n```\\n// Add the line below\\n bytes4 constant WH_TRANSCEIVER_PAYLOAD_PREFIX = 0x99455748;\\n```\\n
While still a valid 4-byte hex prefix, used purely for identification purposes, an incorrect prefix could cause downstream confusion and result in otherwise valid Transceiver payloads being incorrectly prefixed.
```\\n/// @dev Prefix for all TransceiverMessage payloads\\n/// This is 0x99'E''W''H'\\n/// @notice Magic string (constant value set by messaging provider) that idenfies the payload as an transceiver-emitted payload.\\n/// Note that this is not a security critical field. It's meant to be used by messaging ...
Redemptions are blocked when L2 sequencers are down
medium
Given that rollups such as Optimism and Arbitrum offer methods for forced transaction inclusion, it is important that the aliased sender address is also checked within `Logic::redeemTokensWithPayload` when verifying the sender is the specified `mintRecipient` to allow for maximum uptime in the event of sequencer downti...
Validation of the sender address against the `mintRecipient` should also consider the aliased `mintRecipient` address to allow for maximum uptime when `Logic::redeemTokensWithPayload` is called via forced inclusion.
Failure to consider the aliased `mintRecipient` address prevents the execution of valid VAAs on a target CCTP domain where transactions are batched by a centralized L2 sequencer. Since this VAA could carry a time-sensitive payload, such as the urgent cross-chain liquidity infusion to a protocol, this issue has the pote...
```\\n// Confirm that the caller is the `mintRecipient` to ensure atomic execution.\\nrequire(\\n msg.sender.toUniversalAddress() == deposit.mintRecipient, "caller must be mintRecipient"\\n);\\n```\\n
Potentially dangerous out-of-bounds memory access in `BytesParsing::sliceUnchecked`
low
`BytesParsing::sliceUnchecked` currently bails early for the degenerate case when the slice `length` is zero; however, there is no validation on the `length` of the `encoded` bytes parameter `encoded` itself. If the `length` of `encoded` is less than the slice `length`, then it is possible to access memory out-of-bound...
Consider bailing early if the length of the bytes from which to construct a slice is zero, and always ensure the resultant offset is correctly validated against the length when using the unchecked version of the function.
The impact is limited in the context of the library function's usage in the scope of this review; however, it is advisable to check any other usage elsewhere and in the future to ensure that this behavior cannot be weaponized. `BytesParsing::sliceUnchecked` is currently only used in `WormholeCctpMessages::_decodeBytes`...
```\\nfunction sliceUnchecked(bytes memory encoded, uint256 offset, uint256 length)\\n internal\\n pure\\n returns (bytes memory ret, uint256 nextOffset)\\n{\\n //bail early for degenerate case\\n if (length == 0) {\\n return (new bytes(0), offset);\\n }\\n\\n assembly ("memory-safe") {\\n ...
A given CCTP domain can be registered for multiple foreign chains due to insufficient validation in `Governance::registerEmitterAndDomain`
low
`Governance::registerEmitterAndDomain` is a Governance action that is used to register the emitter address and corresponding CCTP domain for a given foreign chain. Validation is currently performed to ensure that the registered CCTP domain of the foreign chain is not equal to that of the local chain; however, there is ...
Consider adding the following validation when registering a CCTP domain for a foreign chain:\\n```\\n// Add the line below\\n require (getDomainToChain()[cctpDomain] == 0, "CCTP domain already registered for a different foreign chain");\\n```\\n
The impact of this issue in the current scope is limited since the corrupted state is only ever queried in a public view function; however, if it is important for third-party integrators, then this has the potential to cause downstream issues.\\nProof of Concept:\\nCCTP Domain A is registered for foreign chain identifi...
```\\nfunction registerEmitterAndDomain(bytes memory encodedVaa) public {\\n /* snip: parsing of Governance VAA payload */\\n\\n // For now, ensure that we cannot register the same foreign chain again.\\n require(registeredEmitters[foreignChain] == 0, "chain already registered");\\n\\n /* snip: additional p...
Lack of Governance action to update registered emitters
low
The Wormhole CCTP integration contract currently exposes a function `Governance::registerEmitterAndDomain` to register an emitter address and its corresponding CCTP domain on the given foreign chain; however, no such function currently exists to update this state. Any mistake made when registering the emitter and CCTP ...
The addition of a `Governance::updateEmitterAndDomain` function is recommended to allow Governance to more easily respond to any issues with the registered emitter state.
In the event an emitter is registered with an incorrect foreign chain identifier or CCTP domain, then a protocol upgrade will be required to mitigate this issue. As such, the risks associated with the deployment of protocol upgrades and the potential time-sensitive nature of this issue designate a low severity issue.\\...
```\\nfunction registerEmitterAndDomain(bytes memory encodedVaa) public {\\n /* snip: parsing of Governance VAA payload */\\n\\n // Set the registeredEmitters state variable.\\n registeredEmitters[foreignChain] = foreignAddress;\\n\\n // update the chainId to domain (and domain to chainId) mappings\\n ge...
Temporary denial-of-service when in-flight messages are not executed before a deprecated Wormhole Guardian set expires
low
Wormhole exposes a governance action in `Governance::submitNewGuardianSet` to update the Guardian set via Governance VAA.\\n```\\nfunction submitNewGuardianSet(bytes memory _vm) public {\\n // rest of code\\n\\n // Trigger a time-based expiry of current guardianSet\\n expireGuardianSet(getCurrentGuardianSetInd...
The practicality of executing the proposed Governance mitigations at scale should be carefully considered, given the extent to which USDC is entrenched within the wider DeFi ecosystem. There is a high likelihood of temporary widespread, high-impact DoS, although this is somewhat limited by the understanding that Guardi...
There is only a single address that is permitted to execute a given VAA on the target domain; however, there are several scenarios that have been identified where this `mintReceipient` may be unable to perform redemption for a period in excess of 24 hours following an update to the Guardian set while the VAA is in-flig...
```\\nfunction submitNewGuardianSet(bytes memory _vm) public {\\n // rest of code\\n\\n // Trigger a time-based expiry of current guardianSet\\n expireGuardianSet(getCurrentGuardianSetIndex());\\n\\n // Add the new guardianSet to guardianSets\\n storeGuardianSet(upgrade.newGuardianSet, upgrade.newGuardia...
`StrategyPassiveManagerUniswap` gives ERC20 token allowances to `unirouter` but doesn't remove allowances when `unirouter` is updated
medium
`StrategyPassiveManagerUniswap` gives ERC20 token allowances to unirouter:\\n```\\nfunction _giveAllowances() private {\\n IERC20Metadata(lpToken0).forceApprove(unirouter, type(uint256).max);\\n IERC20Metadata(lpToken1).forceApprove(unirouter, type(uint256).max);\\n}\\n```\\n\\n`unirouter` is inherited from `Stra...
1) Make `StratFeeManagerInitializable::setUnirouter` `virtual` such that it can be overridden by child contracts. 2) `StrategyPassiveManagerUniswap` should override `setUnirouter` to remove all allowances before calling the parent function to update `unirouter`.
The old `unirouter` contract will continue to have ERC20 token approvals for `StratFeeManagerInitializable` so it can continue to spend the protocol's tokens when this is not the protocol's intention as the protocol has changed `unirouter`.
```\\nfunction _giveAllowances() private {\\n IERC20Metadata(lpToken0).forceApprove(unirouter, type(uint256).max);\\n IERC20Metadata(lpToken1).forceApprove(unirouter, type(uint256).max);\\n}\\n```\\n
Owner of `StrategyPassiveManagerUniswap` can rug-pull users' deposited tokens by manipulating `onlyCalmPeriods` parameters
low
While `StrategyPassiveManagerUniswap` does have some permissioned roles, one of the attack paths we were asked to check was that the permissioned roles could not rug-pull the users' deposited tokens. There is a way that the owner of the `StrategyPassiveManagerUniswap` contract could accomplish this by modifying key par...
Beefy already intends to have all owner functions behind a timelocked multi-sig and if these transactions are attempted the suspicious parameters would be an obvious signal that a future attack is coming. Because of this the probability of this attack being effectively executed is low though it is still possible.\\nOne...
Owner of `StrategyPassiveManagerUniswap` can rug-pull users' deposited tokens.
```\\n// @audit `price` is derived from `pool.slot0`\\nshares = _amount1 + (_amount0 * price / PRECISION);\\n```\\n
`_onlyCalmPeriods` does not consider MIN/MAX ticks, which can DOS deposit, withdraw and harvest in edge cases
low
In Uniswap V3 liquidity providers can only provide liquidity between price ranges `[1.0001^{MIN_ TICK};1.0001^{MAX_TICK})`. Therefore these are the min and max prices.\\n```\\n function _onlyCalmPeriods() private view {\\n int24 tick = currentTick();\\n int56 twapTick = twap();\\n\\n if(\\n ...
Consider changing the current implementation to:\\n```\\n// Add the line below\\n const int56 MIN_TICK = // Remove the line below\\n887272;\\n// Add the line below\\n const int56 MAX_TICK = 887272;\\n function _onlyCalmPeriods() private view {\\n int24 tick = currentTick();\\n int56 twapTick = twap...
null
```\\n function _onlyCalmPeriods() private view {\\n int24 tick = currentTick();\\n int56 twapTick = twap();\\n\\n if(\\n twapTick - maxTickDeviationNegative > tick ||\\n twapTick + maxTickDeviationPositive < tick) revert NotCalm();\\n }\\n```\\n
Withdraw can return zero tokens while burning a positive amount of shares
low
Invariant fuzzing found an edge-case where a user could burn an amount of shares > 0 but receive zero output tokens. The cause appears to be a rounding down to zero precision loss for small `_shares` value in `BeefyVaultConcLiq::withdraw` L220-221:\\n```\\nuint256 _amount0 = (_bal0 * _shares) / _totalSupply;\\nuint256 ...
Change the slippage check to also revert if no output tokens are returned:\\n```\\nif (_amount0 < _minAmount0 || _amount1 < _minAmount1 ||\\n (_amount0 == 0 && _amount1 == 0)) revert TooMuchSlippage();\\n```\\n
Protocol can enter a state where a user burns their shares but receives zero output tokens in return.\\nProof of Concept: Invariant fuzz testing suite supplied at the conclusion of the audit.
```\\nuint256 _amount0 = (_bal0 * _shares) / _totalSupply;\\nuint256 _amount1 = (_bal1 * _shares) / _totalSupply;\\n```\\n
`SwellLib.BOT` can subtly rug-pull withdrawals by setting `_processedRate = 0` when calling `swEXIT::processWithdrawals`
medium
When users create a withdrawal request, their `swETH` is burned then the current exchange rate `rateWhenCreated` is fetched from swETH::swETHToETHRate:\\n```\\nuint256 rateWhenCreated = AccessControlManager.swETH().swETHToETHRate();\\n```\\n\\nHowever `SwellLib.BOT` can pass an arbitrary value for `_processedRate` when...
Two possible mitigations:\\nChange `swEXIT::processWithdrawals` to always fetch the current rate from `swETH::swETHToETHRate`\\nOnly allow `swEXIT::processWithdrawals` to be called by the `RepricingOracle` contract which calls it correctly.
null
```\\nuint256 rateWhenCreated = AccessControlManager.swETH().swETHToETHRate();\\n```\\n
Check for staleness of data when fetching Proof of Reserves via Chainlink `Swell ETH PoR` Oracle
low
`RepricingOracle::_assertRepricingSnapshotValidity` uses the `Swell ETH PoR` Chainlink Proof Of Reserves Oracle to fetch an off-chain data source for Swell's current reserves.\\nThe Oracle `Swell ETH PoR` is listed on Chainlink's website as having a heartbeat of `86400` seconds (check the "Show More Details" box in the...
Implement a staleness check and if the Oracle is stale, either revert or skip using it as the code currently does if the oracle is not set.\\nFor multi-chain deployments ensure that a correct staleness check is used for each feed as the same feed can have different heartbeats on different chains.\\nConsider adding an o...
If the `Swell ETH PoR` Chainlink Proof Of Reserves Oracle has stopped functioning correctly, `RepricingOracle::_assertRepricingSnapshotValidity` will continue processing with stale reserve data as if it were fresh.
```\\n// @audit no staleness check\\n(, int256 externallyReportedV3Balance, , , ) = AggregatorV3Interface(\\n ExternalV3ReservesPoROracle\\n).latestRoundData();\\n```\\n
Precision loss in `swETH::_deposit` from unnecessary hidden division before multiplication
low
`swETH::_deposit` L170 contains a hidden unnecessary division before multiplication as the call to `_ethToSwETHRate` performs a division which then gets multiplied by msg.value:\\n```\\nuint256 swETHAmount = wrap(msg.value).mul(_ethToSwETHRate()).unwrap();\\n// @audit expanding this out\\n// wrap(msg.value).mul(_ethToS...
Refactor to perform multiplication before division:\\n```\\nuint256 swETHAmount = wrap(msg.value).mul(wrap(1 ether)).div(_swETHToETHRate()).unwrap();\\n```\\n
Slightly less `swETH` will be minted to depositors. While the amount by which individual depositors are short-changed is individually small, the effect is cumulative and increases as depositors and deposit size increase.\\nProof of Concept: This stand-alone stateless fuzz test can be run inside Foundry to prove this as...
```\\nuint256 swETHAmount = wrap(msg.value).mul(_ethToSwETHRate()).unwrap();\\n// @audit expanding this out\\n// wrap(msg.value).mul(_ethToSwETHRate()).unwrap();\\n// wrap(msg.value).mul(wrap(1 ether).div(_swETHToETHRate())).unwrap();\\n```\\n
Attacker can abuse `RewardsDistributor::triggerRoot` to block reward claims and unpause a paused state
medium
Consider the code of RewardsDistributor::triggerRoot:\\n```\\n function triggerRoot() external {\\n bytes32 rootCandidateAValue = rootCandidateA.value;\\n if (rootCandidateAValue != rootCandidateB.value || rootCandidateAValue == bytes32(0)) revert RootCandidatesInvalid();\\n root = Root({value: ...
Two possible options:\\nMake `RewardsDistributor::triggerRoot` a permissioned function such that an attacker can't call it\\nChange `RewardsDistributor::triggerRoot` to reset `rootCandidateA.value = zeroRoot` such that it can't be successfully called repeatedly.
An attacker can abuse this function in 2 ways:\\nby calling it repeatedly an attacker can continually increase `root.lastUpdatedAt` to trigger the claim delay revert in `RewardsDistributor::claimAll` effectively blocking reward claims\\nby calling it after reward claims have been paused, an attacker can effectively unp...
```\\n function triggerRoot() external {\\n bytes32 rootCandidateAValue = rootCandidateA.value;\\n if (rootCandidateAValue != rootCandidateB.value || rootCandidateAValue == bytes32(0)) revert RootCandidatesInvalid();\\n root = Root({value: rootCandidateAValue, lastUpdatedAt: block.timestamp});\\...
`RewardsDistributor` doesn't correctly handle deposits of fee-on-transfer incentive tokens
medium
`the kenneth` stated in telegram that Fee-On-Transfer tokens are fine to use as incentive tokens with `RewardsDistributor`, however when receiving Fee-On-Transfer tokens and storing the reward amount the accounting does not account for the fee deducted from the transfer amount in-transit, for example:\\n```\\nfunction ...
In `RewardsDistributor::_depositLPIncentive` & depositVoteIncentive:\\nread the `before` transfer token balance of `RewardsDistributor` contract\\nperform the token transfer\\nread the `after` transfer token balance of `RewardsDistributor` contract\\ncalculate the difference between the `after` and `before` balances to...
The actual reward calculation is done off-chain and is outside the audit scope nor do we have visibility of that code. But events emitted by `RewardsDistributor` and the stored incentive token deposits in `RewardsDistributor::periodRewards` use incorrect amounts for Fee-On-Transfer incentive token deposits.
```\\nfunction _depositLPIncentive(\\n StoredReward memory reward,\\n uint256 amount,\\n uint256 periodReceived\\n) private {\\n IERC20(reward.token).safeTransferFrom(\\n msg.sender,\\n address(this),\\n amount\\n );\\n\\n // @audit stored `amount` here will be incorrect since it ...
Use low level `call()` to prevent gas griefing attacks when returned data not required
low
Using `call()` when the returned data is not required unnecessarily exposes to gas griefing attacks from huge returned data payload. For example:\\n```\\n(bool sent, ) = _to.call{value: _amount}("");\\nrequire(sent);\\n```\\n\\nIs the same as writing:\\n```\\n(bool sent, bytes memory data) = _to.call{value: _amount}(""...
Use a low-level call when the returned data is not required, eg:\\n```\\nbool sent;\\nassembly {\\n sent := call(gas(), _to, _amount, 0, 0, 0, 0)\\n}\\nif (!sent) revert FailedToSendEther();\\n```\\n
Contract unnecessarily exposed to gas griefing attacks.
```\\n(bool sent, ) = _to.call{value: _amount}("");\\nrequire(sent);\\n```\\n
No precision scaling or minimum received amount check when subtracting `relayerFeeAmount` can revert due to underflow or return less tokens to user than specified
medium
`PorticoFinish::payOut` L376 attempts to subtract the `relayerFeeAmount` from the final post-bridge and post-swap token balance:\\n```\\nfinalUserAmount = finalToken.balanceOf(address(this)) - relayerFeeAmount;\\n```\\n\\nThere is no precision scaling to ensure that PorticoFinish's token contract balance and `relayerFe...
Ensure that token balance and `relayerFeeAmount` have the same decimal precision before combining them. Alternatively check for underflow and don't charge a fee if this would be the case. Consider enforcing the user-specified minimum output token check again when deducting `relayerFeeAmount`, and if this would fail the...
Bridged tokens stuck or user receives less tokens than their specified minimum.
```\\nfinalUserAmount = finalToken.balanceOf(address(this)) - relayerFeeAmount;\\n```\\n
Use low level `call()` to prevent gas griefing attacks when returned data not required
low
Using `call()` when the returned data is not required unnecessarily exposes to gas griefing attacks from huge returned data payload. For example:\\n```\\n(bool sentToUser, ) = recipient.call{ value: finalUserAmount }("");\\nrequire(sentToUser, "Failed to send Ether");\\n```\\n\\nIs the same as writing:\\n```\\n(bool se...
Use a low-level call when the returned data is not required, eg:\\n```\\nbool sent;\\nassembly {\\n sent := call(gas(), recipient, finalUserAmount, 0, 0, 0, 0)\\n}\\nif (!sent) revert Unauthorized();\\n```\\n\\nConsider using ExcessivelySafeCall.
Contract unnecessarily exposed to gas griefing attacks.
```\\n(bool sentToUser, ) = recipient.call{ value: finalUserAmount }("");\\nrequire(sentToUser, "Failed to send Ether");\\n```\\n
The previous milestone stem should be scaled for use with the new gauge point system which uses untruncated values moving forward
high
Within the Beanstalk Silo, the milestone stem for a given token is the cumulative amount of grown stalk per BDV for this token at the last `stalkEarnedPerSeason` update. Previously, the milestone stem was stored in its truncated representation; however, the seed gauge system now stores the value in its untruncated form...
Scale up the existing milestone stem for each token:\\n```\\nfor (uint i = 0; i < siloTokens.length; i// Add the line below\\n// Add the line below\\n) {\\n// Add the line below\\n s.ss[siloTokens[i]].milestoneStem = int96(s.ss[siloTokens[i]].milestoneStem.mul(1e6));\\n```\\n\\n\\clearpage
The mixing of decimals between the old milestone stem (truncated) and the new milestone stem (untruncated, after the first `gm` call following the BIP-39 upgrade) breaks the existing grown stalk accounting, resulting in a loss of grown stalk for depositors.\\nProof of Concept: The previous implementation returns the cu...
```\\n_stemTipForToken = s.ss[token].milestoneStem +\\n int96(s.ss[token].stalkEarnedPerSeason).mul(\\n int96(s.season.current).sub(int96(s.ss[token].milestoneSeason))\\n );\\n```\\n
Both reserves should be checked in `LibWell::getWellPriceFromTwaReserves`
low
```\\nfunction getWellPriceFromTwaReserves(address well) internal view returns (uint256 price) {\\n AppStorage storage s = LibAppStorage.diamondStorage();\\n // s.twaReserve[well] should be set prior to this function being called.\\n // 'price' is in terms of reserve0:reserve1.\\n if (s.twaReserves[well].re...
```\\n// LibWell::getWellPriceFromTwaReserves`\\n// Remove the line below\\n if (s.twaReserves[well].reserve0 == 0) {\\n// Add the line below\\n if (s.twaReserves[well].reserve0 == 0 || s.twaReserves[well].reserve1 == 0) {\\n price = 0;\\n} else {\\n\\n// LibWell::setTwaReservesForWell\\n// Remove the line below...
null
```\\nfunction getWellPriceFromTwaReserves(address well) internal view returns (uint256 price) {\\n AppStorage storage s = LibAppStorage.diamondStorage();\\n // s.twaReserve[well] should be set prior to this function being called.\\n // 'price' is in terms of reserve0:reserve1.\\n if (s.twaReserves[well].re...
Small unripe token withdrawals don't decrease BDV and Stalk
low
For any whitelisted token where `bdvCalc(amountDeposited) < amountDeposited`, a user can deposit that token and then withdraw in small amounts to avoid decreasing BDV and Stalk. This is achieved by exploiting a rounding down to zero precision loss in LibTokenSilo::removeDepositFromAccount:\\n```\\n// @audit small unrip...
`LibTokenSilo::removeDepositFromAccount` should revert if `removedBDV == 0`. A similar check already exists in `LibTokenSilo::depositWithBDV` but is missing in `removeDepositFromAccount()` when calculating `removedBDV` for partial withdrawals.\\nThe breaking of protocol invariants could lead to other serious issues tha...
An attacker can withdraw deposited assets without decreasing BDV and Stalk. While the cost to perform this attack is likely more than the value an attacker would stand to gain, the potential impact should definitely be explored more closely especially considering the introduction of the Unripe Chop Convert in BIP-39 as...
```\\n// @audit small unripe bean withdrawals don't decrease BDV and Stalk\\n// due to rounding down to zero precision loss. Every token where\\n// `bdvCalc(amountDeposited) < amountDeposited` is vulnerable\\nuint256 removedBDV = amount.mul(crateBDV).div(crateAmount);\\n```\\n
Broken check in `MysteryBox::fulfillRandomWords()` fails to prevent same request being fulfilled multiple times
high
Consider the check which attempts to prevent the same request from being fulfilled multiple times:\\n```\\nif (vrfRequests[_requestId].fulfilled) revert InvalidVrfState();\\n```\\n\\nThe problem is that `vrfRequests[_requestId].fulfilled` is never set to `true` anywhere and `vrfRequests[_requestId]` is deleted at the e...
Set `vrfRequests[_requestId].fulfilled = true`.\\nConsider an optimized version which involves having 2 mappings `activeVrfRequests` and fulfilledVrfRequests:\\nrevert `if(fulfilledVrfRequests[_requestId])`\\nelse set `fulfilledVrfRequests[_requestId] = true`\\nfetch the matching active request into memory from `active...
The same request can be fulfilled multiple times which would override the previous randomly generated seed; a malicious provider who was also a mystery box minter could generate new randomness until they got a rare mystery box.
```\\nif (vrfRequests[_requestId].fulfilled) revert InvalidVrfState();\\n```\\n
Use low level `call()` to prevent gas griefing attacks when returned data not required
low
Using `call()` when the returned data is not required unnecessarily exposes to gas griefing attacks from huge returned data payload. For example:\\n```\\n(bool sent, ) = address(operatorAddress).call{value: msg.value}("");\\nif (!sent) revert Unauthorized();\\n```\\n\\nIs the same as writing:\\n```\\n(bool sent, bytes ...
Use a low-level call when the returned data is not required, eg:\\n```\\nbool sent;\\nassembly {\\n sent := call(gas(), receiver, amount, 0, 0, 0, 0)\\n}\\nif (!sent) revert Unauthorized();\\n```\\n\\nConsider using ExcessivelySafeCall.
Contracts unnecessarily expose themselves to gas griefing attacks.
```\\n(bool sent, ) = address(operatorAddress).call{value: msg.value}("");\\nif (!sent) revert Unauthorized();\\n```\\n
`TokenSaleProposal::buy` implicitly assumes that buy token has 18 decimals resulting in a potential total loss scenario for Dao Pool
high
`TokenSaleProposalBuy::buy` is called by users looking to buy the DAO token using a pre-approved token. The exchange rate for this sale is pre-assigned for the specific tier. This function internally calls `TokenSaleProposalBuy::_purchaseWithCommission` to transfer funds from the buyer to the gov pool. Part of the tran...
There are at least 2 options for mitigating this issue:\\nOption 1 - revise the design decision that all token amounts must be sent in 18 decimals even if the underlying token decimals are not 18, to instead that all token amounts should be sent in their native decimals and Dexe will convert everything.\\nOption 2 - ke...
It is easy to see that for tokens with smaller decimals, eg. USDC with 6 decimals, will cause a total loss to the DAO. In such cases amount is presumed to be 18 decimals & on converting to token decimals(6), this number can round down to 0.\\nProof of Concept:\\nTier 1 allows users to buy DAO token at exchange rate, 1 ...
```\\n function _sendFunds(address token, address to, uint256 amount) internal {\\n if (token == ETHEREUM_ADDRESS) {\\n (bool success, ) = to.call{value: amount}("");\\n require(success, "TSP: failed to transfer ether");\\n } else {\\n IERC20(token).safeTransferFrom(msg...
Attacker can destroy user voting power by setting `ERC721Power::totalPower` and all existing NFTs `currentPower` to 0
high
Attacker can destroy user voting power by setting `ERC721Power::totalPower` & all existing nfts' `currentPower` to 0 via a permission-less attack contract by exploiting a discrepancy ("<" vs "<=") in `ERC721Power` L144 & L172:\\n```\\nfunction recalculateNftPower(uint256 tokenId) public override returns (uint256 newPow...
Resolve the discrepancy between `ERC721Power` L144 & L172.
`ERC721Power::totalPower` & all existing nft's `currentPower` are set 0, negating voting using `ERC721Power` since `totalPower` is read when creating the snapshot and `GovUserKeeper::getNftsPowerInTokensBySnapshot()` will return 0 same as if the nft contract didn't exist. Can also negatively affect the ability to creat...
```\\nfunction recalculateNftPower(uint256 tokenId) public override returns (uint256 newPower) {\\n // @audit execution allowed to continue when\\n // block.timestamp == powerCalcStartTimestamp\\n if (block.timestamp < powerCalcStartTimestamp) {\\n return 0;\\n }\\n // @audit getNftPower() returns...
A malicious DAO Pool can create a token sale tier without actually transferring any DAO tokens
high
`TokenSaleProposalCreate::createTier` is called by a DAO Pool owner to create a new token sale tier. A fundamental prerequisite for creating a tier is that the DAO Pool owner must transfer the `totalTokenProvided` amount of DAO tokens to the `TokenSaleProposal`.\\nCurrent implementation implements a low-level call to t...
Calculate the contract balance before and after the low-level call and verify if the account balance increases by `totalTokenProvided`. Please be mindful that this check is only valid for non-fee-on-transfer tokens. For fee-on-transfer tokens, the balance increase needs to be further adjusted for the transfer fees. Exa...
A fake tier can be created without the proportionate amount of DAO Pool token balance in the `TokenSaleProposal` contract. Naive users can participate in such a token sale assuming their DAO token claims will be honoured at a future date. Since the pool has insufficient token balance, any attempts to claim the DAO pool...
```\\nfunction createTier(\\n mapping(uint256 => ITokenSaleProposal.Tier) storage tiers,\\n uint256 newTierId,\\n ITokenSaleProposal.TierInitParams memory _tierInitParams\\n ) external {\\n\\n // rest of code.\\n /// @dev return value is not checked intentionally\\n > tierIni...
Attacker can at anytime dramatically lower `ERC721Power::totalPower` close to 0
high
Attacker can at anytime dramatically lower `ERC721Power::totalPower` close to 0 using a permission-less attack contract by taking advantage of being able to call `ERC721Power::recalculateNftPower()` & `getNftPower()` for non-existent nfts:\\n```\\nfunction getNftPower(uint256 tokenId) public view override returns (uint...
`ERC721Power::recalculateNftPower()` should revert when called for non-existent nfts.
`ERC721Power::totalPower` lowered to near 0. This can be used to artificially increase voting power since `totalPower` is read when creating the snapshot and is used as the divisor in `GovUserKeeper::getNftsPowerInTokensBySnapshot()`.\\nThis attack is pretty devastating as `ERC721Power::totalPower` can never be increas...
```\\nfunction getNftPower(uint256 tokenId) public view override returns (uint256) {\\n if (block.timestamp <= powerCalcStartTimestamp) {\\n return 0;\\n }\\n\\n // @audit 0 for non-existent tokenId\\n uint256 collateral = nftInfos[tokenId].currentCollateral;\\n\\n // Calculate the minimum possibl...
`GovPool::delegateTreasury` does not verify transfer of tokens and NFTs to delegatee leading to potential voting manipulation
high
`GovPool::delegateTreasury` transfers ERC20 tokens & specific nfts from DAO treasury to `govUserKeeper`. Based on this transfer, the `tokenBalance` and `nftBalance` of the delegatee is increased. This allows a delegatee to use this delegated voting power to vote in critical proposals.\\nAs the following snippet of `Gov...
Since DEXE starts out with a trustless assumption that does not give any special trust privileges to a DAO treasury, it is always prudent to follow the "trust but verify" approach when it comes to non-standard tokens, both ERC20 and ERC721. To that extent, consider adding verification of token & nft balance increase be...
Since both the ERC20 and ERC721 token implementations are controlled by the DAO, and since we are dealing with upgradeable token contracts, there is a potential rug-pull vector created by the implicit transfer assumption above.
```\\n function delegateTreasury(\\n address delegatee,\\n uint256 amount,\\n uint256[] calldata nftIds\\n ) external override onlyThis {\\n require(amount > 0 || nftIds.length > 0, "Gov: empty delegation");\\n require(getExpertStatus(delegatee), "Gov: delegatee is not an expert")...
Voting to change `RewardsInfo::voteRewardsCoefficient` has an unintended side-effect of retrospectively changing voting rewards for active proposals
medium
`GovSettings::editSettings` is one of the functions that can be executed via an internal proposal. When this function is called, setting are validated via `GovSettings::_validateProposalSettings`. This function does not check the value of `RewardsInfo::voteRewardsCoefficient` while updating the settings. There is neith...
Consider freezing `voteRewardMultiplier` and the time of proposal creation. A prospective update of this setting via internal voting should not change rewards for old proposals.
Updating `rewardsCoefficient` can lead to unfair reward distribution on old proposals. Since voting rewards for a given proposal are communicated upfront, this could lead to a situation where promised rewards to users are not honoured.\\nProof of Concept: N/A
```\\n function _getInitialVotingRewards(\\n IGovPool.ProposalCore storage core,\\n IGovPool.VoteInfo storage voteInfo\\n ) internal view returns (uint256) {\\n (uint256 coreVotes, uint256 coreRawVotes) = voteInfo.isVoteFor\\n ? (core.votesFor, core.rawVotesFor)\\n : (co...
Proposal execution can be DOSed with return bombs when calling untrusted execution contracts
medium
`GovPool::execute` does not check for return bombs when executing a low-level call. A return bomb is a large bytes array that expands the memory so much that any attempt to execute the transaction will lead to an `out-of-gas` exception.\\nThis can create potentially risky outcomes for the DAO. One possible outcome is "...
Consider using `ExcessivelySafeCall` while calling untrusted contracts to avoid return bombs.
Voting actions can be manipulated by a creator causing two potential issues:\\nProposal actions can never be executed even after successful voting\\nOne-sided execution where some actions can be executed while others can be DOSed\\nProof of Concept: Consider the following malicious proposal action executor contract. No...
```\\n function execute(\\n mapping(uint256 => IGovPool.Proposal) storage proposals,\\n uint256 proposalId\\n ) external {\\n // rest of code. // code\\n\\n for (uint256 i; i < actionsLength; i++) {\\n> (bool status, bytes memory returnedData) = actions[i].executor.call{\\n ...
Use low-level `call()` to prevent gas griefing attacks when returned data not required
low
Using `call()` when the returned data is not required unnecessarily exposes to gas griefing attacks from huge returned data payload. For example:\\n```\\n(bool status, ) = payable(receiver).call{value: amount}("");\\nrequire(status, "Gov: failed to send eth");\\n```\\n\\nIs the same as writing:\\n```\\n(bool status, by...
Use a low-level call when the returned data is not required, eg:\\n```\\nbool status;\\nassembly {\\n status := call(gas(), receiver, amount, 0, 0, 0, 0)\\n}\\n```\\n\\nConsider using ExcessivelySafeCall.
Contracts unnecessarily expose themselves to gas griefing attacks.
```\\n(bool status, ) = payable(receiver).call{value: amount}("");\\nrequire(status, "Gov: failed to send eth");\\n```\\n
`abi.encodePacked()` should not be used with dynamic types when passing the result to a hash function such as `keccak256()`
low
`abi.encodePacked()` should not be used with dynamic types when passing the result to a hash function such as `keccak256()`.\\nUse `abi.encode()` instead which will pad items to 32 bytes, which will prevent hash collisions (e.g. `abi.encodePacked(0x123,0x456)` => `0x123456` => `abi.encodePacked(0x1,0x23456)`, but `abi....
See description.
null
```\\nFile: factory/PoolFactory.sol\\n\\n return keccak256(abi.encodePacked(deployer, poolName));\\n```\\n
A removal signature might be applied to the wrong `fid`.
medium
A remove signature is used to remove a key from `fidOwner` using `KeyRegistry.removeFor()`. And the signature is verified in `_verifyRemoveSig()`.\\n```\\n function _verifyRemoveSig(address fidOwner, bytes memory key, uint256 deadline, bytes memory sig) internal {\\n _verifySig(\\n _hashTypedDataV4...
The removal signature should contain `fid` also to be invalidated for another `fid`.
A key remove signature might be used for an unexpected `fid`.
```\\n function _verifyRemoveSig(address fidOwner, bytes memory key, uint256 deadline, bytes memory sig) internal {\\n _verifySig(\\n _hashTypedDataV4(\\n keccak256(abi.encode(REMOVE_TYPEHASH, fidOwner, keccak256(key), _useNonce(fidOwner), deadline))\\n ),\\n fi...
`VoteKickPolicy._endVote()` might revert forever due to underflow
high
In `onFlag()`, `targetStakeAtRiskWei[target]` might be less than the total rewards for the flagger/reviewers due to rounding.\\n```\\nFile: contracts\\OperatorTokenomics\\StreamrConfig.sol\\n /**\\n * Minimum amount to pay reviewers+flagger\\n * That is: minimumStakeWei >= (flaggerRewardWei + flagReviewerCou...
Always round the `minimumStakeWei()` up.
The `VoteKickPolicy` wouldn't work as expected and malicious operators won't be kicked forever.
```\\nFile: contracts\\OperatorTokenomics\\StreamrConfig.sol\\n /**\\n * Minimum amount to pay reviewers+flagger\\n * That is: minimumStakeWei >= (flaggerRewardWei + flagReviewerCount * flagReviewerRewardWei) / slashingFraction\\n */\\n function minimumStakeWei() public view returns (uint) {\\n ...
Possible overflow in `_payOutFirstInQueue`
high
In `_payOutFirstInQueue()`, possible revert during `operatorTokenToDataInverse()`.\\n```\\nuint amountOperatorTokens = moduleCall(address(exchangeRatePolicy), abi.encodeWithSelector(exchangeRatePolicy.operatorTokenToDataInverse.selector, amountDataWei));\\n```\\n\\nIf a delegator calls `undelegate()` with `type(uint256...
We should cap `amountDataWei` before calling `operatorTokenToDataInverse()`.
The queue logic will be broken forever because `_payOutFirstInQueue()` keeps reverting.
```\\nuint amountOperatorTokens = moduleCall(address(exchangeRatePolicy), abi.encodeWithSelector(exchangeRatePolicy.operatorTokenToDataInverse.selector, amountDataWei));\\n```\\n
Wrong validation in `DefaultUndelegationPolicy.onUndelegate()`
high
In `onUndelegate()`, it checks if the operator owner still holds at least `minimumSelfDelegationFraction` of total supply.\\n```\\n function onUndelegate(address delegator, uint amount) external {\\n // limitation only applies to the operator, others can always undelegate\\n if (delegator != owner) { retu...
`onUndelegate()` should compare amounts after converting to the same token.
The operator owner wouldn't be able to undelegate because `onUndelegate()` works unexpectedly.
```\\n function onUndelegate(address delegator, uint amount) external {\\n // limitation only applies to the operator, others can always undelegate\\n if (delegator != owner) { return; }\\n\\n uint actualAmount = amount < balanceOf(owner) ? amount : balanceOf(owner); //@audit amount:DATA, balanceOf:...
Malicious target can make `_endVote()` revert forever by forceUnstaking/staking again
high
In `_endVote()`, we update `forfeitedStakeWei` or `lockedStakeWei[target]` according to the target's staking status.\\n```\\nFile: contracts\\OperatorTokenomics\\SponsorshipPolicies\\VoteKickPolicy.sol\\n function _endVote(address target) internal {\\n address flagger = flaggerAddress[target];\\n bool ...
Perform stake unlocks in `_endVote()` without relying on the current staking amounts.
Malicious operators can bypass the flagging system by reverting `_endVote()` forever.
```\\nFile: contracts\\OperatorTokenomics\\SponsorshipPolicies\\VoteKickPolicy.sol\\n function _endVote(address target) internal {\\n address flagger = flaggerAddress[target];\\n bool flaggerIsGone = stakedWei[flagger] == 0;\\n bool targetIsGone = stakedWei[target] == 0;\\n uint reviewerC...
In `VoteKickPolicy.onFlag()`, `targetStakeAtRiskWei[target]` might be greater than `stakedWei[target]` and `_endVote()` would revert.
medium
`targetStakeAtRiskWei[target]` might be greater than `stakedWei[target]` in `onFlag()`.\\n```\\ntargetStakeAtRiskWei[target] = max(stakedWei[target], streamrConfig.minimumStakeWei()) * streamrConfig.slashingFraction() / 1 ether;\\n```\\n\\nFor example,\\nAt the first time, `streamrConfig.minimumStakeWei()` = 100 and an...
`onFlag()` should check if a target has staked enough funds for rewards and handle separately if not.
Operators with small staked funds wouldn't be kicked forever.
```\\ntargetStakeAtRiskWei[target] = max(stakedWei[target], streamrConfig.minimumStakeWei()) * streamrConfig.slashingFraction() / 1 ether;\\n```\\n
Possible front running of `flag()`
medium
The `target` might call `unstake()/forceUnstake()` before a flagger calls `flag()` to avoid a possible fund loss. Also, there would be no slash during the unstaking for `target` when it meets the `penaltyPeriodSeconds` requirement.\\n```\\nFile: contracts\\OperatorTokenomics\\SponsorshipPolicies\\VoteKickPolicy.sol\\n ...
There is no straightforward mitigation but we could implement a kind of `delayed unstaking` logic for some percent of staking funds.
A malicious target would bypass the kick policy by front running.
```\\nFile: contracts\\OperatorTokenomics\\SponsorshipPolicies\\VoteKickPolicy.sol\\n function onFlag(address target, address flagger) external {\\n require(flagger != target, "error_cannotFlagSelf");\\n require(voteStartTimestamp[target] == 0 && block.timestamp > protectionEndTimestamp[target], "error...
In `Operator._transfer()`, `onDelegate()` should be called after updating the token balances
medium
In `_transfer()`, `onDelegate()` is called to validate the owner's `minimumSelfDelegationFraction` requirement.\\n```\\nFile: contracts\\OperatorTokenomics\\Operator.sol\\n // transfer creates a new delegator: check if the delegation policy allows this "delegation"\\n if (balanceOf(to) == 0) {\\n ...
`onDelegate()` should be called after `super._transfer()`.
The operator owner might transfer his shares to other delegators in anticipation of slashing, to avoid slashing.
```\\nFile: contracts\\OperatorTokenomics\\Operator.sol\\n // transfer creates a new delegator: check if the delegation policy allows this "delegation"\\n if (balanceOf(to) == 0) {\\n if (address(delegationPolicy) != address(0)) {\\n moduleCall(address(delegationPolicy), abi.enco...
`onTokenTransfer` does not validate if the call is from the DATA token contract
medium
`SponsorshipFactory::onTokenTransfer` and `OperatorFactory::onTokenTransfer` are used to handle the token transfer and contract deployment in a single transaction. But there is no validation that the call is from the DATA token contract and anyone can call these functions.\\nThe impact is low for `Sponsorship` deployme...
Add a validation to ensure the caller is the actual DATA contract.
Attackers can prevent the deployment of `Operator` contracts.
```\\n if (msg.sender != address(token)) {\\n revert AccessDeniedDATATokenOnly();\\n }\\n```\\n
Insufficient validation of new Fertilizer IDs allow for a denial-of-service (DoS) attack on `SeasonFacet::gm` when above peg, once the last element in the FIFO is paid
medium
A Fertilizer NFT can be interpreted as a bond without an expiration date which is to be repaid in Beans and includes interest (Humidity). This bond is placed in a FIFO list and intended to recapitalize the $77 million in liquidity stolen during the April 2022 exploit. One Fertilizer can be purchased for 1 USD worth of ...
Despite being a complex issue to explain, the solution is as simple as replacing `>` with `>=` in `LibFertilizer::addFertilizer` as below:\\n```\\n function addFertilizer(\\n uint128 season,\\n uint256 fertilizerAmount,\\n uint256 minLP\\n ) internal returns (uint128 id) {\\n AppStorag...
It is possible to perform a denial-of-service (DoS) attack on `SeasonFacet::gm` if the Bean price is above the peg, either once fully recapitalized or when reaching the last element of the Fertilizer FIFO list.\\nProof of Concept: This coded PoC can be run by:\\nCreating file `Beantalk/protocol/test/POCs/mint0Fertilize...
```\\n// Previous code\\n\\n function addUnderlying(uint256 amount, uint256 minAmountOut) internal {\\n //// rest of code\\n C.bean().mint(\\n address(this),\\n newDepositedBeans.add(newDepositedLPBeans)\\n );\\n\\n // Add Liquidity\\n uint256 newLP = C.curveZ...
Use safe transfer for ERC20 tokens
medium
The protocol intends to support all ERC20 tokens but the implementation uses the original transfer functions. Some tokens (like USDT) do not implement the EIP20 standard correctly and their transfer/transferFrom function return void instead of a success boolean. Calling these functions with the correct EIP20 function s...
We recommend using OpenZeppelin's SafeERC20 versions with the safeTransfer and safeTransferFrom functions that handle the return value check as well as non-standard-compliant tokens.
Tokens that do not correctly implement the EIP20 like USDT, will be unusable in the protocol as they revert the transaction because of the missing return value.
```\\nTransferUtils.sol\\n function _transferERC20(address token, address to, uint256 amount) internal {\\n IERC20 erc20 = IERC20(token);\\n require(erc20 != IERC20(address(0)), "Token Address is not an ERC20");\\n uint256 initialBalance = erc20.balanceOf(to);\\n require(erc20.transfer(to...
Fee-on-transfer tokens are not supported
medium
The protocol intends to support all ERC20 tokens but does not support fee-on-transfer tokens. The protocol utilizes the functions `TransferUtils::_transferERC20()` and `TransferUtils::_transferFromERC20()` to transfer ERC20 tokens.\\n```\\nTransferUtils.sol\\n function _transferERC20(address token, address to, uint2...
The transfer utility functions can be updated to return the actually received amount. Or clearly document that only standard ERC20 tokens are supported.
Fee-on-transfer tokens can not be used for the protocol. Because of the rarity of these tokens, we evaluate this finding as a Medium risk.
```\\nTransferUtils.sol\\n function _transferERC20(address token, address to, uint256 amount) internal {\\n IERC20 erc20 = IERC20(token);\\n require(erc20 != IERC20(address(0)), "Token Address is not an ERC20");\\n uint256 initialBalance = erc20.balanceOf(to);\\n require(erc20.transfer(to...
Centralization risk
medium
The protocol has an owner with privileged rights to perform admin tasks that can affect users. Especially, the owner can change the fee settings and reward handler address.\\nValidation is missing for admin fee setter functions.\\n```\\nFeeData.sol\\n function setFeeValue(uint256 feeValue) external onlyOwner {\\n ...
Specify the owner's privileges and responsibilities in the documentation.\\nAdd constant state variables that can be used as the minimum and maximum values for the fee settings.\\nAdd proper validation for the admin functions.\\nLog the changes in the important state variables via events.
While the protocol owner is regarded as a trusted party, the owner can change the fee settings and reward handler address without any validation or logging. This can lead to unexpected results and users can be affected.
```\\nFeeData.sol\\n function setFeeValue(uint256 feeValue) external onlyOwner {\\n require(feeValue < _feeDenominator, "Fee percentage must be less than 1");\\n _feeValue = feeValue;\\n }\\n\\n function setFixedFee(uint256 fixedFee) external onlyOwner {//@audit-issue validate min/max\\n _...
Validation is missing for tokenA in `SwapExchange::calculateMultiSwap()`
low
The protocol supports claiming a chain of swaps and the function `SwapExchange::calculateMultiSwap()` is used to do some calculations including the amount of tokenA that can be received for a given amount of tokenB. Looking at the implementation, the protocol does not validate that the tokenA of the last swap in the ch...
Add a validation that the tokenA of the last swap in the chain is the same as the tokenA of `multiClaimInput`.
The function will return an incorrect swap calculation result if the last swap in the chain has a different tokenA than the tokenA of `multiClaimInput` and it can lead to unexpected results.
```\\nSwapExchange.sol\\n function calculateMultiSwap(SwapUtils.MultiClaimInput calldata multiClaimInput) external view returns (SwapUtils.SwapCalculation memory) {\\n uint256 swapIdCount = multiClaimInput.swapIds.length;\\n if (swapIdCount == 0 || swapIdCount > _maxHops) revert Errors.InvalidMultiClai...
Intermediate value sent by the caller can be drained via reentrancy when `Pipeline` execution is handed off to an untrusted external contract
high
Pipeline is a utility contract created by the Beanstalk Farms team that enables the execution of an arbitrary number of valid actions in a single transaction. The `DepotFacet` is a wrapper around Pipeline for use within the Beanstalk Diamond proxy. When utilizing Pipeline through the `DepotFacet`, Ether value is first ...
Add reentrancy guards to both the `DepotFacet` and `Pipeline`. Also, consider validating clipboard Ether values in `Pipeline::_advancedPipe` against the payable function value in `Pipeline::advancedPipe`.
A malicious external contract handed control of execution during the lifetime of a Pipeline call can reenter and steal intermediate user funds. As such, this finding is determined to be of HIGH severity.\\nProof of Concept: The following forge test demonstrates the ability of an NFT royalty recipient, for example, to r...
```\\nfunction advancedPipe(AdvancedPipeCall[] calldata pipes, uint256 value)\\n external\\n payable\\n returns (bytes[] memory results)\\n{\\n results = IPipeline(PIPELINE).advancedPipe{value: value}(pipes);\\n LibEth.refundEth();\\n}\\n```\\n
`FarmFacet` functions are susceptible to the draining of intermediate value sent by the caller via reentrancy when execution is handed off to an untrusted external contract
high
The `FarmFacet` enables multiple Beanstalk functions to be called in a single transaction using Farm calls. Any function stored in Beanstalk's EIP-2535 DiamondStorage can be called as a Farm call and, similar to the Pipeline calls originated in the `DepotFacet`, advanced Farm calls can be made within `FarmFacet` utiliz...
Add a reentrancy guard to `FarmFacet` Farm functions.\\n\\clearpage
A malicious external contract handed control of execution during the lifetime of a Farm call can reenter and steal intermediate user funds. As such, this finding is determined to be of HIGH severity.\\nProof of Concept: The following forge test demonstrates the ability of a Fertilizer recipient, for example, to re-ente...
```\\n// signals to Beanstalk functions that they should not refund Eth\\n// at the end of the function because the function is wrapped in a Farm function\\nmodifier withEth() {\\n if (msg.value > 0) s.isFarm = 2;\\n _;\\n if (msg.value > 0) {\\n s.isFarm = 1;\\n LibEth.refundEth();\\n }\\n}\\n...
Duplicate fees will be paid by `LibTransfer::transferFee` when transferring fee-on-transfer tokens with `EXTERNAL_INTERNAL` 'from' mode and `EXTERNAL` 'to' mode
medium
Beanstalk utilizes an internal virtual balance system that significantly reduces transaction fees when using tokens that are intended to remain within the protocol. `LibTransfer` achieves this by managing every transfer between accounts, considering both the origin 'from' and destination 'to' modes of the in-flight fun...
Add an internal function `LibTransfer::handleFromExternalInternalToExternalTransfer` to handle this case to avoid duplication of fees. For instance:\\n```\\nfunction handleFromExternalInternalToExternalTransfer(\\n IERC20 token,\\n address sender,\\n address recipient,\\n address amount\\n) internal {\\n ...
`LibTransfer::transferToken` will incur duplicate fees if this function is used for `(from mode: EXTERNAL_INTERNAL ; to mode: EXTERNAL)` with fee-on-transfer tokens if the internal balance is not sufficient to cover the full transfer amount.\\nEven though Beanstalk currently does not impose any fees on token transfers,...
```\\n// LibTransfer::transferToken\\nif (fromMode == From.EXTERNAL && toMode == To.EXTERNAL) {\\n uint256 beforeBalance = token.balanceOf(recipient);\\n token.safeTransferFrom(sender, recipient, amount);\\n return token.balanceOf(recipient).sub(beforeBalance);\\n}\\namount = receiveToken(token, amount, sender...
Flood mechanism is susceptible to DoS attacks by a frontrunner, breaking re-peg mechanism when BEAN is above 1 USD
medium
A call to the BEAN/3CRV Metapool is made withinWeather::sop, swapping Beans for 3CRV, to aid in returning Beanstalk to peg via a mechanism known as "Flood" (formerly Season of Plenty, or sop) when the Beanstalk Farm has been "Oversaturated" ($P > 1$; $Pod Rate < 5%$) for more than one Season and for each additional Sea...
Consider the use of an oracle to determine how many new Beans should be minted and sold for 3CRV. This implies the following modification:\\n```\\n function sop() private {\\n// Remove the line below\\n int256 newBeans = LibBeanMetaCurve.getDeltaB();\\n// Add the line below\\n int256 currentDeltaB = LibB...
Attempts by Beanstalk to restore peg via the Flood mechanism are susceptible to denial-of-service attacks by a sufficiently well-funded sandwich attacker through frontrunning of `SeasonFacet::gm`.
```\\n function getDeltaB() internal view returns (int256 deltaB) {\\n uint256[2] memory balances = C.curveMetapool().get_balances();\\n uint256 d = getDFroms(balances);\\n deltaB = getDeltaBWithD(balances[0], d);\\n }\\n```\\n
Spender can front-run calls to modify token allowances, resulting in DoS and/or spending more than was intended
low
When updating the allowance for a spender that is less than the value currently set, a well-known race condition allows the spender to spend more than the caller intended by front-running the transaction that performs this update. Due to the nature of the `ERC20::approve` implementation and other variants used within t...
Set the allowance to zero if the intended subtracted value exceeds the current allowance.\\n\\clearpage
Requiring that the intended subtracted allowance does not exceed the current allowance results in a degraded user experience and, more significantly, their loss of funds due to a different route to the same approval front-running attack vector.
```\\nrequire(\\n currentAllowance >= subtractedValue,\\n "Silo: decreased allowance below zero"\\n);\\n```\\n
Non-standard ERC20 tokens are not supported
medium
The protocol implemented a function `deposit()` to allow users to deposit.\\n```\\nDepositVault.sol\\n function deposit(uint256 amount, address tokenAddress) public payable {\\n require(amount > 0 || msg.value > 0, "Deposit amount must be greater than 0");\\n if(msg.value > 0) {\\n require(t...
We recommend adding another field in the `Deposit` structure, say `balance`\\nWe recommend allow users to withdraw partially and decrease the `balance` field appropriately for successful withdrawals. If these changes are going to be made, we note that there are other parts that need changes. For example, the withdraw f...
If non-standard ERC20 tokens are used, the tokens could be locked in the contract permanently.
```\\nDepositVault.sol\\n function deposit(uint256 amount, address tokenAddress) public payable {\\n require(amount > 0 || msg.value > 0, "Deposit amount must be greater than 0");\\n if(msg.value > 0) {\\n require(tokenAddress == address(0), "Token address must be 0x0 for ETH deposits");\\n ...
The deposit function is not following CEI pattern
low
The protocol implemented a function `deposit()` to allow users to deposit.\\n```\\nDepositVault.sol\\n function deposit(uint256 amount, address tokenAddress) public payable {\\n require(amount > 0 || msg.value > 0, "Deposit amount must be greater than 0");\\n if(msg.value > 0) {\\n require(t...
Handle token transfers after updating the `deposits` state.
null
```\\nDepositVault.sol\\n function deposit(uint256 amount, address tokenAddress) public payable {\\n require(amount > 0 || msg.value > 0, "Deposit amount must be greater than 0");\\n if(msg.value > 0) {\\n require(tokenAddress == address(0), "Token address must be 0x0 for ETH deposits");\\n ...
Nonstandard usage of nonce
low
The protocol implemented two withdraw functions `withdrawDeposit()` and `withdraw()`. While the function `withdrawDeposit()` is designed to be used by the depositor themselves, the function `withdraw()` is designed to be used by anyone who has a signature from the depositor. The function `withdraw()` has a parameter `n...
If the protocol intended to provide a kind of invalidation mechanism using the nonce, there should be a separate mapping that stores the nonce for each user. The current nonce can be used to generate a signature and a depositor should be able to increase the nonce to invalidate the previous signatures. Also the nonce w...
null
```\\nDepositVault.sol\\n function withdraw(uint256 amount, uint256 nonce, bytes memory signature, address payable recipient) public {\\n require(nonce < deposits.length, "Invalid deposit index");\\n Deposit storage depositToWithdraw = deposits[nonce];//@audit-info non aligned with common understanding...
Unnecessary parameter amount in withdraw function
low
The function `withdraw()` has a parameter `amount` but we don't understand the necessity of this parameter. At line L67, the `amount` is required to be the same to the whole deposit `amount`. This means the user does not have a flexibility to choose the withdraw `amount`, after all it means the parameter was not necess...
If the protocol intends to only allow full withdrawal, this parameter can be removed completely (that will help save gas as well). Unnecessary parameters increase the complexity of the function and more error prone.
null
```\\nDepositVault.sol\\n function withdraw(uint256 amount, uint256 nonce, bytes memory signature, address payable recipient) public {\\n require(nonce < deposits.length, "Invalid deposit index");\\n Deposit storage depositToWithdraw = deposits[nonce];\\n bytes32 withdrawalHash = getWithdrawalHa...
Functions not used internally could be marked external
low
Using proper visibility modifiers is a good practice to prevent unintended access to functions. Furthermore, marking functions as `external` instead of `public` can save gas.\\n```\\nFile: DepositVault.sol\\n\\n function deposit(uint256 amount, address tokenAddress) public payable\\n\\n function withdraw(uint256 ...
Consider change the visibility modifier to `external` for the functions that are not used internally.
null
```\\nFile: DepositVault.sol\\n\\n function deposit(uint256 amount, address tokenAddress) public payable\\n\\n function withdraw(uint256 amount, uint256 nonce, bytes memory signature, address payable recipient) public\\n\\n function withdrawDeposit(uint256 depositIndex) public\\n```\\n
User's funds are locked temporarily in the PriorityPool contract
medium
The protocol intended to utilize the deposit queue for withdrawal to minimize the stake/unstake interaction with the staking pool. When a user wants to withdraw, they are supposed to call the function `PriorityPool::withdraw()` with the desired amount as a parameter.\\n```\\nfunction withdraw(uint256 _amount) external ...
Consider add a feature to allow users to withdraw LSD tokens from the contract directly.
User's LSD tokens can be locked temporarily in the PriorityPool contract\\nProof of Concept:\\n```\\n it('Cyfrin: user funds can be locked temporarily', async () => {\\n // try deposit 1500 while the capacity is 1000\\n await strategy.setMaxDeposits(toEther(1000))\\n await sq.connect(signers[1]).deposit(toEthe...
```\\nfunction withdraw(uint256 _amount) external {//@audit-info LSD token\\n if (_amount == 0) revert InvalidAmount();\\n IERC20Upgradeable(address(stakingPool)).safeTransferFrom(msg.sender, address(this), _amount);//@audit-info get LSD token from the user\\n _withdraw(msg.sender, _amount);\\n}\\n```\\n
Each Well is responsible for ensuring that an `update` call cannot be made with a reserve of 0
high
The current implementation of `GeoEmaAndCumSmaPump` assumes each well will call `update()` with non-zero reserves, as commented at the beginning of the file:\\n```\\n/**\\n * @title GeoEmaAndCumSmaPump\\n * @author Publius\\n * @notice Stores a geometric EMA and cumulative geometric SMA for each reserve.\\n * @dev A Pu...
Revert the pump updates if they are called with zero reserve values.
Updating pumps with zero reserve values can lead to the distortion of critical states likely to be utilized for price oracles. Given that the issue is exploitable through valid transactions, we assess the severity as HIGH. It is crucial to note that attackers can exploit this vulnerability to manipulate the price oracl...
```\\n/**\\n * @title GeoEmaAndCumSmaPump\\n * @author Publius\\n * @notice Stores a geometric EMA and cumulative geometric SMA for each reserve.\\n * @dev A Pump designed for use in Beanstalk with 2 tokens.\\n *\\n * This Pump has 3 main features:\\n * 1. Multi-block MEV resistence reserves\\n * 2. MEV-resistant Geo...
`LibLastReserveBytes::storeLastReserves` has no check for reserves being too large
medium
After every liquidity event & swap, the IPump::update()is called. To update the pump, theLibLastReserveBytes::storeLastReservesfunction is used. This packs the reserve data intobytes32` slots in storage. A slot is then broken down into the following components:\\n1 byte for reserves array length\\n5 bytes for `timestam...
We recommend adding a check on the size of reserves in `LibLastReseveBytes`.\\nAdditionally, it is recommended to add comments to `LibLastReseveBytes` to inform users about the invariants of the system and how the max size of reserves should be equal to the max size of a `bytes16` and not a `uint256`.
While we assume users will be explicitly warned about malicious Wells and are unlikely to interact with invalid Wells, we assess the severity to be MEDIUM.\\nProof of Concept:\\n```\\nfunction testStoreAndReadTwo() public {\\n uint40 lastTimeStamp = 12345363;\\n bytes16[] memory reserves = new bytes16[](2);\\n ...
```\\nsrc\\libraries\\LibLastReserveBytes.sol\\n uint8 n = uint8(reserves.length);\\n if (n == 1) {\\n assembly {\\n sstore(slot, or(or(shl(208, lastTimestamp), shl(248, n)), shl(104, shr(152, mload(add(reserves, 32))))))\\n }\\n return;\\n }\\n assembly {\\n sstore(\\n ...