Part of CertiK’s series
CertiK reviewed Venus Protocol (Venus - Prime) on 13 Nov 2023: 43 findings, 0 critical; 35 marked fixed, 8 open.
Report hosted on skynet.certik.com.
Trustblock does not review code.
Statuses are the security firm’s own, from its report.
| Severity | Open | Acknowledged | Fixed |
|---|---|---|---|
| Critical | 0 | 0 | 0 |
| High | 2 | 0 | 2 |
| Medium | 0 | 0 | 2 |
| Low | 6 | 0 | 31 |
Function `accrueInterest()` in contract `Prime` assumes that mapping `tokenAmountAccrued` in `PrimeLiquidityProvider` always holds at least the value for an `underlying` token as is held in mapping `unreleasedPLPIncome`. However, function `releaseFunds()` in `PrimeLiquidityProvider` can be called by anyone at any time, which resets `tokenAmountAccrued` for the `underlying` token to 0. This function call will not have any effect on the current value of `unreleasedPLPIncome` for the `underlying`. Someone can independently call function `releaseFunds()` for the `underlying` token and consequently, the values for `tokenAmountAccrued` will now be less than the value of `unreleasedPLPIncome` for the `underlying`. As a result, function `accrueInterest()` will revert. Since the only way to reset `unreleasedPLPIncome` to 0 is through function `claimInterest()` being called, and since this function must first call `accrueInterest()`, this halts the functioning of the protocol.
The amount of `tokenAccrued` should be the amount accrued since the update as `tokenAmountAccrued[token_]` is incremented by this value, so that it should only take into account the balance that exceeds the current value of `tokenAmountAccrued[token_]`. Otherwise, the accrued amount can exceed the contract's balance and cause `releaseFunds()` to revert. This can prevent users from claiming their prime interest in the case that the prime contract does not hold enough balance after releasing funds from the `ProtocolShareReserve` and attempts to release funds from the `PrimeLiquidityProvider`.
Function `sweepToken()` is meant to transfer an input `amount_` of a specified `token_` to a destination address, from the contract. Instead, the function transfers the entire `token_.balanceOf(address(this))` to the destination address.
It is important for function `executeBoost()` to be called before function `updateScore()` any time an action occurs that affects a user's score. Actions that could affect a user's score include a user updating the stake in the `XVSVault`, updating their position in a supported market, or the team updating how the score gets updated. If a user can call function `updateScore()` before function `executeBoost()` in one of the scenarios above, then the newly updated score can be applied to the period of time since the last boost was performed. In a case where a user's score drastically increases, this allows them to unfairly gain a larger amount of rewards for the full duration since their last boost. One such case is outlined below. Users are transferred the underlying asset via `doTransferOut()` in the `VToken` contract before calling the verify hooks that make calls to `executeBoost()` and `updateScore()` in the `Prime` contract. It is assumed based on context that `VBNB` is a boosted Prime market, and as a consequence, the transfer of funds to users before updating `Prime` allows a user to make calls to `Prime` before the intended calls to `executeBoost()` and `updateScore()`. In particular, a malicious user can take advantage to call the functions of `Prime` in an incorrect order and cause an over-allocation of rewards that allows the user to steal rewards they are not privy to. For instance, a user can call `updateScore()` before function `executeBoost()` is called in order to apply their new score to their past accumulated difference in `rewardIndex`.
All other instances of assigning zero have been replaced with using `delete`.
In general, the counter in a for loop can be incremented or decremented in an unchecked block as it cannot overflow or underflow, saving gas as it will not perform a check for overflow or underflow. Additionally, it saves a small amount of gas to increment an index in a `for` loop from the left instead of from the right side as it performs fewer operations.
In the function `getPendingInterests()`, `allMarkets.length` is cached after defining the `pendingInterests` array. It can be cached prior to defining the `pendingInterests` array to save reading `allMarkets.length` for the length of the array.
### PrimeLiquidityProvider.sol - In function `releaseFunds()`, the event can be emitted before external call to `safeTransfer()`; - In function `sweepToken()`, the event can be emitted before external call to `safeTransfer()`;
The input `capital` in `calculateScore`, is an amount of underlying token which may differ in decimals across markets. The same $\alpha$ is used for every market, however, causing the equation to behave differently for each market.
The following unchecked blocks are used, however, we do not see an easy way to rationalize that there exists no scenario they will underflow or overflow. If you can please provide the rationale as to why these blocks cannot underflow or overflow, we can check there are no scenarios that were overlooked. ```solidity unchecked { totalTimeStaked = block.timestamp - userStakedAt; } ``` - considering `setStakedAt()` can update `stakedAt` to any value including one larger that the current `block.timestamp`, it is possible that this will underflow. ```solidity unchecked { supply = (exchangeRate * balanceOfAccount) / EXP_SCALE; } ``` - `exchangeRate * balanceOfAccount` may overflow. While it is understood that the `balanceOfAccount` value should be a portion of the `totalSupply` of vTokens used in the `exchangeRate`, if it is possible to manipulate the exchangeRate` to be inconsistently high, the product `exchangeRate * balance` may overflow. ```solidity unchecked { delta = ((distributionIncome * EXP_SCALE) / market.sumOfMembersScore); } ``` - `distributionIncome * EXP_SCALE` may overflow if `distributionIncome` is large enough. ```solidity unchecked { supply = (exchangeRate * balanceOfAccount) / EXP_SCALE; } ``` - `exchangeRate * balanceOfAccount` may overflow. ```solidity unchecked { _market.sumOfMembersScore = _market.sumOfMembersScore - interests[market][user].score + score; } ``` - may overflow if `score` is larger than `interests[market][user].score`. Without a check that the addition does not cause overflow, it cannot be ensured that the `_market.sumOfMembersScore` is an invariant. ```solidity unchecked { supplyUSD = (tokenPrice * supply) / EXP_SCALE; borrowUSD = (tokenPrice * borrow) / EXP_SCALE; } ``` - `tokenPrice * supply` and `tokenPrice * borrow` may overflow. ```solidity unchecked { supply = supplyUSD != 0 ? (supply * supplyCapUSD) / supplyUSD : 0; } ``` - `supply * supplyCapUSD` may overflow. ```solidity unchecked { borrow = borrowUSD != 0 ? (borrow * borrowCapUSD) / borrowUSD : 0; } ``` - `borrow * borrowCapUSD` may overflow. ```solidity unchecked { return (index * score) / EXP_SCALE; } ``` - `index * score` may overflow. ```solidity unchecked { return ((((market.totalBorrows() * market.borrowRatePerBlock()) / EXP_SCALE) * market.reserveFactorMantissa()) / EXP_SCALE); } ``` - may overflow when multiplying. ```solidity unchecked { userYearlyIncome = (userScore * _incomeDistributionYearly(vToken)) / totalScore; } ``` - `userScore * _incomeDistributionYearly(vToken)` may overflow. ```solidity unchecked { userSupplyIncomeYearly = (userYearlyIncome * totalCappedSupply) / totalCappedValue; userBorrowIncomeYearly = (userYearlyIncome * totalCappedBorrow) / totalCappedValue; supplyAPR = totalSupply == 0 ? 0 : ((userSupplyIncomeYearly * maximumBps) / totalSupply); borrowAPR = totalBorrow == 0 ? 0 : ((userBorrowIncomeYearly * maximumBps) / totalBorrow); } ``` - `userYearlyIncome * totalCappedSupply`, `userYearlyIncome * totalCappedBorrow`, `userSupplyIncomeYearly * maximumBps`, and `userBorrowIncomeYearly * maximumBps` may overflow.
The function `_interestAccrued` does not modify any states and can be marked as `view`.
Functions `setMaxTokensDistributionSpeed()` and `setMaxLoopsLimit()` are not included in the `IPrimeLiquidityProvider` interface; all other external-facing, non-initializing functions present in the `PrimeLiquidityProvider` contract are first declared in the interface.
- In `PrimeStorage`, constant `MAXIMUM_XVS_CAP` is set as 10000 * EXP_SCALE, however, the documentation provided states that the maximum XVS cap should be 100,000 XVS. - In `Prime`, the `_incomePerBlock()` uses formula ```solidity ((((market.totalBorrows() * market.borrowRatePerBlock()) / EXP_SCALE) * market.reserveFactorMantissa()) / EXP_SCALE); ``` However, the documentation states that the `_incomePerBlock` should be measured by ```solidity (borrowRatePerBlock * totalBorrows) - (supplyRatePerBlock*(cash + borrows - reserves)) ``` While the implementation and specification are mathematically equivalent, it is observed that the implementation is more direct and less gas intensive. The implementation also more accurately reflects what occurs within each `VToken` contract.
Custom errors are used, however, the `constructor()` still uses `require` statements instead of custom errors.
The `totalCappedValue` is always less than or equal to the `totalValue`. Thus it is sufficient to check that the `totalCapped` value is 0.
The input `user` in the function `_calculateUserAPR()` is never used within the function.
The file `Prime.sol` includes several interfaces along with the contract `Prime`.
In the contract `PrimeLiquidityProvider`: - The comments above `setPrimeToken()` do not reflect that it emits the `PrimeTokenUpdated` event and that access is restricted to governance by the `onlyOwner` modifier. - The comments above `releaseFunds()` do not reflect that it throws `FundsTransferIsPaused` if paused. - The comments above `getBlockNumber()` do not include the return value. In the contract `Prime`: - There are no comments reflecting the access restriction of functions, the events emitted, or the errors thrown. - There are no comments for the defined errors. - There are no NatSpec comments for the function `initialize()`. - The comments above `updateMultipliers()` do not include the parameter `market`. - The comments above `isEligible()` do not include the return value. - The comments above `getInterestAccrued()` do not include the return value. - There are no comments for the function `_interestAccrued()`. - There are no comments for the function `_getUnderlying()`. - The comments above `claimInterest()` do not include the parameter `user`. In the contract `SetterFacet` - The function `_setForcedLiquidation()` does not have a comment stating it allows a privileged role to call it. All other functions that have their access controlled by `ensureAllowed()` have such a comment.
Functions that update state variables or perform privileged actions should emit relevant events as notifications.
As of commit [f5e32216191f7959a51d30687df5610af543eca5](https://github.com/VenusProtocol/venus-protocol/commit/f5e32216191f7959a51d30687df5610af543eca5) the public functions `executeBoost()` and `updateScore()` in the `Prime` contract have been replaced with a public function `accrueInterestAndUpdateScore()` wherein the internal versions of these functions are called in their correct sequence. This change resolves finding PFD-01 concerning the misallocation of rewards via reentrancy in the `VBNB` contract, during the borrowing of an asset. In the `VBNB` contract (or if a market is created for an asset with a hook in the future), it is still possible to perform calls to the `Prime` contract when someone borrows or redeems, at the level of `doTransferOut()`, before function `accrueInterestAndUpdateScore()` is called for the user and the market within the `Prime` contract. The finding is set as informational since no perceived attacks can currently be accomplished via unintended entry into the `Prime` contract before the sequence of intended calls is completed.
Currently the restrictions on $\alpha$ include the ability for it to be set to 0 or 1. However, this causes potential discrepancies if `xvs` or `capital` is zero. If $\alpha=0$: $$ xvs^{\alpha} * capital^{1-\alpha} = capital $$ So that the score should be based solely on the `capital` of the user. However, if `xvs` is zero then the function `calculateScore()` in the `Scores` library will return 0 which may not be consistent with the amount of the user's capital. Note that if a user has an irrevocable prime token, then `xvs` may be 0. If $\alpha=1$: $$ xvs^{\alpha} * capital^{1-\alpha} = xvs $$ So that the score should be based solely on the `xvs` of the user. However, if `capital` is zero then `calculateScore()` in the `Scores` library will return 0 which may not be the consistent with the the user's amount of `xvs`.
Often, operations loop through all elements of `allMarkets`. If too many markets are added, then these operations may cause transactions to exceed the gas limit.
Any time functions `updateAlpha()`, `updateMultipliers()` or `addMarket()` are used to make an update to the protocol, there is a period of time between when the corresponding values are updated, and when all users' scores are updated to incorporate the change. A user can wait for such a change and take advantage of the discrepancy to potentially do one of the following items: - A new market is added and no one is included in the `sumOfMembersScore` yet. A user updates their own score as soon as the new market is added and for a period of time, they are currently 100% of the receivers for the market rewards. - The $\alpha$ value is changed to drastically increase most users' scores. One user updates their score while all other scores are the same value. As a result, the updated user is privy to more rewards than others for a period of time. A similar issue could occur with the borrow and supply multipliers.
Many of the added files use specific imports, however, some import the entire file.
The state variable `primeLiquidityProvider` is being shadowed by a local variable in function `accrueInterest()`.
In the contract `Prime`: - The comments above `updateMultipliers()` do not warn that the supply and borrow multiplier should be converted to `1e18`. - The functions `updateMultipliers()` and `addMarket()` have the same inputs, but do not follow the same conventions. - The comment above the function `setLimit()` misspells "minted" as "mined". - The comment above the function `_xvsBalanceOfUser()` for the parameter `user` is not consistent with the function. - The comment above the function `_xvsBalanceForScore()` misspelled "calculate" as "calcukate". - In the comment above `togglePause()`, "unpause" is misspelled as "unpuase". - Functions `calculateAPR()` and `estimateAPR()` should include comments specifying that the returned value is in BPS. - The comments above the function `issue()` has "is the tokens being issued", which should be "are the tokens being issued". - The check that a market is a supported prime market or that the user has a prime token is not consistent between the functions `executeBoost()` and `updateScore()`. - The comments above the function `_claimInterest()` state "the market for which claim", which should be "the market for which to claim". - The comment above the function `_accrueInterestAndUpdateScore()` includes the word "interest" misspelled as "interes." - The comments above the function `_interestAccrued()` state "for which calculate", which should be "for which to calculate". - The comment above the function `claimInterest()` states "the amount of tokens transferred to the user", however, it would be more accurate to say "the amount of tokens transferred to the msg.sender". In the contract `PrimeLiquidityProvider`: - The comment above the error `InsufficientBalance` references the `swapRouter`, when it should reference the `PrimeLiquidityProvider` contract. - The comment above the function `initialize()` references the `RewardsDistributor`, when it should reference the `PrimeLiquidityProvider` contract. - The comment above the function `pauseFundsTransfer()` states "Emits FundsTransferPaused on success", however, this event is not emitted. - The comment above the function `resumeFundsTransfer()` states "Emits FundsTransferResumed on success", however, this event is not emitted. - The comment above the function `releaseFunds()` states "token_ The list of tokens to claim tokens", however, the input is a single `address` and not a list. - The comment above the function `sweepToken()` states "Throw InsufficientBalance on Zero address(token)", however, it throws `InsufficientBalance` if the input amount of token exceeds the contracts balance. - The local variable `intializedBlock` contains misspelling "intialized" for the word "initialized". - The comment above the error `TokenNotInitialized` says "Error thrown when interest accrue is called for not initialized token." The comment may read better as "Error thrown when accrueTokens is called for an uninitialized token." In the contract `PolicyFacet`: - The hooks `mintVerify()`, `redeemVerify()`, `borrowVerify()`, `repayBorrowVerify()`, `liquidateBorrowVerify()`, `seizeVerify()`, and `transferVerify()` all include a comment which states that the purpose of the function is to validate each action. Instead, the hooks are now used to update rewards and scores in the `Prime` contract. Additionally, the `VToken` contract includes comments that refer to these functions as "defense hooks" which is not their purpose. In the contract `PrimeStorage`: - The public variables `_totalIrrevocable`, `_totalRevocable`, `_revocableLimit`, and `_irrevocableLimit` have a leading underscore when they are external facing variables.
The function `_incomeDistributionYearly()` has the following implementation: ```solidity function _incomeDistributionYearly(address vToken) internal view returns (uint256 amount) { uint256 totalIncomePerBlockFromMarket = _incomePerBlock(vToken); uint256 incomePerBlockForDistributionFromMarket = (totalIncomePerBlockFromMarket * _distributionPercentage()) / IProtocolShareReserve(protocolShareReserve).MAX_PERCENT(); amount += BLOCKS_PER_YEAR * incomePerBlockForDistributionFromMarket; uint256 totalIncomePerBlockFromPLP = IPrimeLiquidityProvider(primeLiquidityProvider) .getEffectiveDistributionSpeed(_getUnderlying(vToken)); amount += BLOCKS_PER_YEAR * totalIncomePerBlockFromPLP; } ``` However, the first time `amount` is updated it can be set equal to `BLOCKS_PER_YEAR * incomePerBlockForDistributionFromMarket` as the `amount` will be zero, saving an unnecessary addition operation.
The `for`-loop in the function `setStakedAt()` initializes `uint256 i = 0`. However, no other `for`-loops in the contract initialize their counter.
It is understood that the `PrimeLiquidityProvider` contract is an upgradeable child contract. Being the case, a storage placeholder `__gap` variable is unneeded, since all new variables can be appended to the end in the case of an upgrade.
Contract `PrimeLiquidityProvider` does not protect its initializer. An attacker can call the initializer and assume ownership of the logic contract, whereby they can perform privileged operations that trick unsuspecting users into believing that they are the owner of the upgradeable contract.
The cited errors are never used within the `Prime` contract codebase.
Due to refactoring the code so that all income now originates from the `PrimeLiquidityProvider`, the function `_incomePerBlock()` is no longer used or needed.
Some state variables are not used in the codebase. Variable `EXP_SCALE` in `PrimeLiquidityProvider` is never used in `PrimeLiquidityProvider`. ```solidity=15 uint256 internal constant EXP_SCALE = 1e18; ``` ```solidity=8 contract PrimeLiquidityProvider is AccessControlledV8, PausableUpgradeable { ```
The perceived pattern for upgrade handling is that a new child contract for comptroller storage versions is created each time an upgrade is to take place. We note that the comptroller has already been upgraded to the diamond proxy pattern on-chain at proxy address [0xfD36E2c2a6789Db23113685031d7F16329158384](https://bscscan.com/address/0xfD36E2c2a6789Db23113685031d7F16329158384#readProxyContract) with corresponding implementation [0xAd69AA3811fE0EE7dBd4e25C4bae40e6422c76C8](https://bscscan.com/address/0xAd69AA3811fE0EE7dBd4e25C4bae40e6422c76C8). Since `ComptrollerV13Storage` is already in use, we recommend moving the addition of the `prime` variable to a `ComptrollerV14Storage` contract, to distinguish the new upgrade.
In function `_updateRoundAfterTokenMinted()`, value `totalScoreUpdatesRequired` is checked to be nonzero by checking if the value is greater than zero. For consistency across the codebase, it can be checked that `totalScoreUpdatesRequired != 0` instead.
The report names a repository or files. Open the report to see its scope.
Repository and files the report names (12)
1,045 projects reviewed · 1,376 reports · latest May 2025
See CertiK’s auditsSomething wrong on this page? A missing report, a wrong date, a finding that was fixed since. Tell us and we check it against its source.
Tell us