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
|
---|---|---|---|---|---|
StableSwapOperatorV1 - resistantFei value is not correct in the resistantBalanceAndFei function | high | The `resistantBalanceAndFei` function of a `PCVDeposit` contract is supposed to return the amount of funds that the contract controls; it is then used to evaluate the total value of PCV (collateral in the protocol). Additionally, this function returns the number of FEI tokens that are protocol-controlled. These FEI tokens are “temporarily minted”; they are not backed up by the collateral and shouldn't be used in calculations that determine the collateralization of the protocol.\\nIdeally, the amount of these FEI tokens should be the same during the deposit, withdrawal, and the `resistantBalanceAndFei` function call. In the `StableSwapOperatorV1` contract, all these values are totally different:\\nduring the deposit, the amount of required FEI tokens is calculated. It's done in a way so the values of FEI and 3pool tokens in the metapool should be equal after the deposit. So if there is the initial imbalance of FEI and 3pool tokens, the deposit value of these tokens will be different:\\n```\\n// get the amount of tokens in the pool\\n(uint256 \\_3crvAmount, uint256 \\_feiAmount) = (\\n IStableSwap2(pool).balances(\\_3crvIndex),\\n IStableSwap2(pool).balances(\\_feiIndex)\\n);\\n// // rest of code and the expected amount of 3crv in it after deposit\\nuint256 \\_3crvAmountAfter = \\_3crvAmount + \\_3crvBalanceAfter;\\n \\n// get the usd value of 3crv in the pool\\nuint256 \\_3crvUsdValue = \\_3crvAmountAfter \\* IStableSwap3(\\_3pool).get\\_virtual\\_price() / 1e18;\\n \\n// compute the number of FEI to deposit\\nuint256 \\_feiToDeposit = 0;\\nif (\\_3crvUsdValue > \\_feiAmount) {\\n \\_feiToDeposit = \\_3crvUsdValue - \\_feiAmount;\\n}\\n```\\n\\nduring the withdrawal, the FEI and 3pool tokens are withdrawn in the same proportion as they are present in the metapool:\\n```\\nuint256[2] memory \\_minAmounts; // [0, 0]\\nIERC20(pool).approve(pool, \\_lpToWithdraw);\\nuint256 \\_3crvBalanceBefore = IERC20(\\_3crv).balanceOf(address(this));\\nIStableSwap2(pool).remove\\_liquidity(\\_lpToWithdraw, \\_minAmounts);\\n```\\n\\nin the `resistantBalanceAndFei` function, the value of protocol-controlled FEI tokens and the value of 3pool tokens deposited are considered equal:\\n```\\nresistantBalance = \\_lpPriceUSD / 2;\\nresistantFei = resistantBalance;\\n```\\n\\nSome of these values may be equal under some circumstances, but that is not enforced. After one of the steps (deposit or withdrawal), the total PCV value and collateralization may be changed significantly. | Make sure that deposit, withdrawal, and the `resistantBalanceAndFei` are consistent and won't instantly change the PCV value significantly. | null | ```\\n// get the amount of tokens in the pool\\n(uint256 \\_3crvAmount, uint256 \\_feiAmount) = (\\n IStableSwap2(pool).balances(\\_3crvIndex),\\n IStableSwap2(pool).balances(\\_feiIndex)\\n);\\n// // rest of code and the expected amount of 3crv in it after deposit\\nuint256 \\_3crvAmountAfter = \\_3crvAmount + \\_3crvBalanceAfter;\\n \\n// get the usd value of 3crv in the pool\\nuint256 \\_3crvUsdValue = \\_3crvAmountAfter \\* IStableSwap3(\\_3pool).get\\_virtual\\_price() / 1e18;\\n \\n// compute the number of FEI to deposit\\nuint256 \\_feiToDeposit = 0;\\nif (\\_3crvUsdValue > \\_feiAmount) {\\n \\_feiToDeposit = \\_3crvUsdValue - \\_feiAmount;\\n}\\n```\\n |
CollateralizationOracle - Fei in excluded deposits contributes to userCirculatingFei | high | `CollateralizationOracle.pcvStats` iterates over all deposits, queries the resistant balance and FEI for each deposit, and accumulates the total value of the resistant balances and the total resistant FEI. Any Guardian or Governor can exclude (and re-include) a deposit that has become problematic in some way, for example, because it is reporting wrong numbers. Finally, the `pcvStats` function computes the `userCirculatingFei` as the total FEI supply minus the accumulated resistant FEI balances; the idea here is to determine the amount of “free” FEI, or FEI that is not PCV. However, the FEI balances from excluded deposits contribute to the `userCirculatingFei`, although they are clearly not “free” FEI. That leads to a wrong `protocolEquity` and a skewed collateralization ratio and might therefore have a significant impact on the economics of the system.\\nIt should be noted that even the exclusion from the total PCV leads to a `protocolEquity` and a collateralization ratio that could be considered skewed (again, it might depend on the exact reasons for exclusion), but “adding” the missing FEI to the `userCirculatingFei` distorts these numbers even more.\\nIn the extreme scenario that all deposits have been excluded, the entire Fei supply is currently reported as `userCirculatingFei`.\\n```\\n/// @notice returns the Protocol-Controlled Value, User-circulating FEI, and\\n/// Protocol Equity.\\n/// @return protocolControlledValue : the total USD value of all assets held\\n/// by the protocol.\\n/// @return userCirculatingFei : the number of FEI not owned by the protocol.\\n/// @return protocolEquity : the difference between PCV and user circulating FEI.\\n/// If there are more circulating FEI than $ in the PCV, equity is 0.\\n/// @return validityStatus : the current oracle validity status (false if any\\n/// of the oracles for tokens held in the PCV are invalid, or if\\n/// this contract is paused).\\nfunction pcvStats() public override view returns (\\n uint256 protocolControlledValue,\\n uint256 userCirculatingFei,\\n int256 protocolEquity,\\n bool validityStatus\\n) {\\n uint256 \\_protocolControlledFei = 0;\\n validityStatus = !paused();\\n\\n // For each token// rest of code\\n for (uint256 i = 0; i < tokensInPcv.length(); i++) {\\n address \\_token = tokensInPcv.at(i);\\n uint256 \\_totalTokenBalance = 0;\\n\\n // For each deposit// rest of code\\n for (uint256 j = 0; j < tokenToDeposits[\\_token].length(); j++) {\\n address \\_deposit = tokenToDeposits[\\_token].at(j);\\n\\n // ignore deposits that are excluded by the Guardian\\n if (!excludedDeposits[\\_deposit]) {\\n // read the deposit, and increment token balance/protocol fei\\n (uint256 \\_depositBalance, uint256 \\_depositFei) = IPCVDepositBalances(\\_deposit).resistantBalanceAndFei();\\n \\_totalTokenBalance += \\_depositBalance;\\n \\_protocolControlledFei += \\_depositFei;\\n }\\n }\\n\\n // If the protocol holds non-zero balance of tokens, fetch the oracle price to\\n // increment PCV by \\_totalTokenBalance \\* oracle price USD.\\n if (\\_totalTokenBalance != 0) {\\n (Decimal.D256 memory \\_oraclePrice, bool \\_oracleValid) = IOracle(tokenToOracle[\\_token]).read();\\n if (!\\_oracleValid) {\\n validityStatus = false;\\n }\\n protocolControlledValue += \\_oraclePrice.mul(\\_totalTokenBalance).asUint256();\\n }\\n }\\n\\n userCirculatingFei = fei().totalSupply() - \\_protocolControlledFei;\\n protocolEquity = int256(protocolControlledValue) - int256(userCirculatingFei);\\n}\\n```\\n | It is unclear how to fix this. One might want to exclude the FEI in excluded deposits entirely from the calculation, but not knowing the amount was the reason to exclude the deposit in the first place.\\nOne option could be to let the entity that excludes a deposit specify substitute values that should be used instead of querying the numbers from the deposit. However, it is questionable whether this approach is practical if the numbers we'd like to see as substitute values change quickly or repeatedly over time. Ultimately, the querying function itself should be fixed. Moreover, as the substitute values can dramatically impact the system economics, we'd only like to trust the Governor with this and not give this permission to a Guardian. However, the original intention was to give a role with less trust than the Governor the possibility to react quickly to a deposit that reports wrong numbers; if the exclusion of deposits becomes the Governor's privilege, such a quick and lightweight intervention isn't possible anymore.\\nIndependently, we recommend taking proper care of the situation that all deposits - or just too many - have been excluded, for example, by setting the returned `validityStatus` to `false`, as in this case, there is not enough information to compute the collateralization ratio even as a crude approximation. | null | ```\\n/// @notice returns the Protocol-Controlled Value, User-circulating FEI, and\\n/// Protocol Equity.\\n/// @return protocolControlledValue : the total USD value of all assets held\\n/// by the protocol.\\n/// @return userCirculatingFei : the number of FEI not owned by the protocol.\\n/// @return protocolEquity : the difference between PCV and user circulating FEI.\\n/// If there are more circulating FEI than $ in the PCV, equity is 0.\\n/// @return validityStatus : the current oracle validity status (false if any\\n/// of the oracles for tokens held in the PCV are invalid, or if\\n/// this contract is paused).\\nfunction pcvStats() public override view returns (\\n uint256 protocolControlledValue,\\n uint256 userCirculatingFei,\\n int256 protocolEquity,\\n bool validityStatus\\n) {\\n uint256 \\_protocolControlledFei = 0;\\n validityStatus = !paused();\\n\\n // For each token// rest of code\\n for (uint256 i = 0; i < tokensInPcv.length(); i++) {\\n address \\_token = tokensInPcv.at(i);\\n uint256 \\_totalTokenBalance = 0;\\n\\n // For each deposit// rest of code\\n for (uint256 j = 0; j < tokenToDeposits[\\_token].length(); j++) {\\n address \\_deposit = tokenToDeposits[\\_token].at(j);\\n\\n // ignore deposits that are excluded by the Guardian\\n if (!excludedDeposits[\\_deposit]) {\\n // read the deposit, and increment token balance/protocol fei\\n (uint256 \\_depositBalance, uint256 \\_depositFei) = IPCVDepositBalances(\\_deposit).resistantBalanceAndFei();\\n \\_totalTokenBalance += \\_depositBalance;\\n \\_protocolControlledFei += \\_depositFei;\\n }\\n }\\n\\n // If the protocol holds non-zero balance of tokens, fetch the oracle price to\\n // increment PCV by \\_totalTokenBalance \\* oracle price USD.\\n if (\\_totalTokenBalance != 0) {\\n (Decimal.D256 memory \\_oraclePrice, bool \\_oracleValid) = IOracle(tokenToOracle[\\_token]).read();\\n if (!\\_oracleValid) {\\n validityStatus = false;\\n }\\n protocolControlledValue += \\_oraclePrice.mul(\\_totalTokenBalance).asUint256();\\n }\\n }\\n\\n userCirculatingFei = fei().totalSupply() - \\_protocolControlledFei;\\n protocolEquity = int256(protocolControlledValue) - int256(userCirculatingFei);\\n}\\n```\\n |
BalancerLBPSwapper - init() can be front-run to potentially steal tokens | medium | The deployment process for `BalancerLBPSwapper` appears to be the following:\\ndeploy `BalancerLBPSwapper`.\\nrun `ILiquidityBootstrappingPoolFactory.create()` proving the newly deployed swapper address as the owner of the pool.\\ninitialize `BalancerLBPSwapper.init()` with the address of the newly created pool.\\nThis process may be split across multiple transactions as in the `v2Phase1.js` deployment scenario.\\nBetween step (1) and (3) there is a window of opportunity for someone to maliciously initialize contract. This should be easily detectable because calling `init()` twice should revert the second transaction. If this is not caught in the deployment script this may have more severe security implications. Otherwise, this window can be used to grief the deployment initializing it before the original initializer does forcing them to redeploy the contract or to steal any tokenSpent/tokenReceived that are owned by the contract at this time.\\nNote: It is assumed that the contract will not own a lot of tokens right after deployment rendering the scenario of stealing tokens more unlikely. However, that highly depends on the deployment script for the contract system.\\n```\\nfunction init(IWeightedPool \\_pool) external {\\n require(address(pool) == address(0), "BalancerLBPSwapper: initialized");\\n\\n pool = \\_pool;\\n IVault \\_vault = \\_pool.getVault();\\n\\n vault = \\_vault;\\n\\n // Check ownership\\n require(\\_pool.getOwner() == address(this), "BalancerLBPSwapper: contract not pool owner");\\n```\\n\\n```\\nIERC20(tokenSpent).approve(address(\\_vault), type(uint256).max);\\nIERC20(tokenReceived).approve(address(\\_vault), type(uint256).max);\\n```\\n | protect `BalancerLBPSwapper.init()` and only allow a trusted entity (e.g. the initial deployer) to call this method. | null | ```\\nfunction init(IWeightedPool \\_pool) external {\\n require(address(pool) == address(0), "BalancerLBPSwapper: initialized");\\n\\n pool = \\_pool;\\n IVault \\_vault = \\_pool.getVault();\\n\\n vault = \\_vault;\\n\\n // Check ownership\\n require(\\_pool.getOwner() == address(this), "BalancerLBPSwapper: contract not pool owner");\\n```\\n |
PCVEquityMinter and BalancerLBPSwapper - desynchronisation race | medium | There is nothing that prevents other actors from calling `BalancerLBPSwapper.swap()` `afterTime` but right before `PCVEquityMinter.mint()` would as long as the `minAmount` required for the call to pass is deposited to `BalancerLBPSwapper`.\\nBoth the `PCVEquityMinter.mint()` and `BalancerLBPSwapper.swap()` are timed (via the `afterTime` modifier) and are ideally in sync. In an ideal world the incentive to call `mint()` would be enough to ensure that both contracts are always in sync, however, a malicious actor might interfere by calling `.swap()` directly, providing the `minAmount` required for the call to pass. This will have two effects:\\ninstead of taking the newly minted FEI from `PCVEquityMinter`, existing FEI from the malicious user will be used with the pool. (instead of inflating the token the malicious actor basically pays for it)\\nthe `Timed` modifiers of both contracts will be out of sync with `BalancerLBPSwapper.swap()` being reset (and failing until it becomes available again) and `PCVEquityMinter.mint()` still being available. Furthermore, keeper-scripts (or actors that want to get the incentive) might continue to attempt to `mint()` while the call will ultimately fail in `.swap()` due to the resynchronization of `timed` (unless they simulate the calls first).\\nNote: There are not a lot of incentives to actually exploit this other than preventing protocol inflation (mint) and potentially griefing users. A malicious user will lose out on the incentivized call and has to ensure that the `minAmount` required for `.swap()` to work is available. It is, however, in the best interest of security to defuse the unpredictable racy character of the contract interaction.\\n```\\nfunction \\_afterMint() internal override {\\n IPCVSwapper(target).swap();\\n}\\n```\\n\\n```\\nfunction swap() external override afterTime whenNotPaused {\\n (\\n uint256 spentReserves,\\n uint256 receivedReserves, \\n uint256 lastChangeBlock\\n ) = getReserves();\\n\\n // Ensures no actor can change the pool contents earlier in the block\\n require(lastChangeBlock < block.number, "BalancerLBPSwapper: pool changed this block");\\n```\\n | If `BalancerLBPSwapper.swap()` is only to be called within the flows of action from a `PCVEquityMinter.mint()` it is suggested to authenticate the call and only let `PCVEquityMinter` call `.swap()` | null | ```\\nfunction \\_afterMint() internal override {\\n IPCVSwapper(target).swap();\\n}\\n```\\n |
CollateralizationOracleWrapper - the deviation threshold check in update() always returns false | medium | A call to `update()` returns a boolean flag indicating whether the update was performed on outdated data. This flag is being checked in `updateIfOutdated()` which is typically called by an incentivized keeper function.\\nThe `_isExceededDeviationThreshold` calls at the end of the `_update()` function always return `false` as they are comparing the same values (cachedProtocolControlledValue to the `_protocolControlledValue` value and `cachedProtocolControlledValue` has just been set to `_protocolControlledValue` a couple of lines before). `_isExceededDeviationThreshold` will, therefore, never detect a deviation and return `false´.\\nThere may currently be no incentive (e.g. from the keeper side) to call `update()` if the values are not outdated but they deviated too much from the target. However, anyone can force an update by calling the non-incentivized public `update()` method instead.\\n```\\n require(\\_validityStatus, "CollateralizationOracleWrapper: CollateralizationOracle is invalid");\\n\\n // set cache variables\\n cachedProtocolControlledValue = \\_protocolControlledValue;\\n cachedUserCirculatingFei = \\_userCirculatingFei;\\n cachedProtocolEquity = \\_protocolEquity;\\n\\n // reset time\\n \\_initTimed();\\n\\n // emit event\\n emit CachedValueUpdate(\\n msg.sender,\\n cachedProtocolControlledValue,\\n cachedUserCirculatingFei,\\n cachedProtocolEquity\\n );\\n\\n return outdated\\n || \\_isExceededDeviationThreshold(cachedProtocolControlledValue, \\_protocolControlledValue)\\n || \\_isExceededDeviationThreshold(cachedUserCirculatingFei, \\_userCirculatingFei);\\n}\\n```\\n | Add unit tests to check for all three return conditions (timed, deviationA, deviationB)\\nMake sure to compare the current to the stored value before updating the cached values when calling `_isExceededDeviationThreshold`. | null | ```\\n require(\\_validityStatus, "CollateralizationOracleWrapper: CollateralizationOracle is invalid");\\n\\n // set cache variables\\n cachedProtocolControlledValue = \\_protocolControlledValue;\\n cachedUserCirculatingFei = \\_userCirculatingFei;\\n cachedProtocolEquity = \\_protocolEquity;\\n\\n // reset time\\n \\_initTimed();\\n\\n // emit event\\n emit CachedValueUpdate(\\n msg.sender,\\n cachedProtocolControlledValue,\\n cachedUserCirculatingFei,\\n cachedProtocolEquity\\n );\\n\\n return outdated\\n || \\_isExceededDeviationThreshold(cachedProtocolControlledValue, \\_protocolControlledValue)\\n || \\_isExceededDeviationThreshold(cachedUserCirculatingFei, \\_userCirculatingFei);\\n}\\n```\\n |
ChainlinkOracleWrapper - latestRoundData might return stale results | medium | The oracle wrapper calls out to a chainlink oracle receiving the `latestRoundData()`. It then checks freshness by verifying that the answer is indeed for the last known round. The returned `updatedAt` timestamp is not checked.\\nIf there is a problem with chainlink starting a new round and finding consensus on the new value for the oracle (e.g. chainlink nodes abandon the oracle, chain congestion, vulnerability/attacks on the chainlink system) consumers of this contract may continue using outdated stale data (if oracles are unable to submit no new round is started)\\n```\\n/// @notice read the oracle price\\n/// @return oracle price\\n/// @return true if price is valid\\nfunction read() external view override returns (Decimal.D256 memory, bool) {\\n (uint80 roundId, int256 price,,, uint80 answeredInRound) = chainlinkOracle.latestRoundData();\\n bool valid = !paused() && price > 0 && answeredInRound == roundId;\\n\\n Decimal.D256 memory value = Decimal.from(uint256(price)).div(oracleDecimalsNormalizer);\\n return (value, valid);\\n}\\n```\\n\\n```\\n/// @notice determine if read value is stale\\n/// @return true if read value is stale\\nfunction isOutdated() external view override returns (bool) {\\n (uint80 roundId,,,, uint80 answeredInRound) = chainlinkOracle.latestRoundData();\\n return answeredInRound != roundId;\\n}\\n```\\n | Consider checking the oracle responses `updatedAt` value after calling out to `chainlinkOracle.latestRoundData()` verifying that the result is within an allowed margin of freshness. | null | ```\\n/// @notice read the oracle price\\n/// @return oracle price\\n/// @return true if price is valid\\nfunction read() external view override returns (Decimal.D256 memory, bool) {\\n (uint80 roundId, int256 price,,, uint80 answeredInRound) = chainlinkOracle.latestRoundData();\\n bool valid = !paused() && price > 0 && answeredInRound == roundId;\\n\\n Decimal.D256 memory value = Decimal.from(uint256(price)).div(oracleDecimalsNormalizer);\\n return (value, valid);\\n}\\n```\\n |
CollateralizationOracle - missing events and incomplete event information | low | The `CollateralizationOracle.setDepositExclusion` function is used to exclude and re-include deposits from collateralization calculations. Unlike the other state-changing functions in this contract, it doesn't emit an event to inform about the exclusion or re-inclusion.\\n```\\nfunction setDepositExclusion(address \\_deposit, bool \\_excluded) external onlyGuardianOrGovernor {\\n excludedDeposits[\\_deposit] = \\_excluded;\\n}\\n```\\n\\nThe `DepositAdd` event emits not only the deposit address but also the deposit's token. Despite the symmetry, the `DepositRemove` event does not emit the token.\\n```\\nevent DepositAdd(address from, address indexed deposit, address indexed token);\\nevent DepositRemove(address from, address indexed deposit);\\n```\\n | `setDepositInclusion` should emit an event that informs about the deposit and whether it was included or excluded.\\nFor symmetry reasons and because it is indeed useful information, the `DepositRemove` event could include the deposit's token. | null | ```\\nfunction setDepositExclusion(address \\_deposit, bool \\_excluded) external onlyGuardianOrGovernor {\\n excludedDeposits[\\_deposit] = \\_excluded;\\n}\\n```\\n |
RateLimited - Contract starts with a full buffer at deployment | low | A contract that inherits from `RateLimited` starts out with a full buffer when it is deployed.\\n```\\n\\_bufferStored = \\_bufferCap;\\n```\\n\\nThat means the full `bufferCap` is immediately available after deployment; it doesn't have to be built up over time. This behavior might be unexpected. | We recommend starting with an empty buffer, or - if there are valid reasons for the current implementation - at least document it clearly. | null | ```\\n\\_bufferStored = \\_bufferCap;\\n```\\n |
BalancerLBPSwapper - tokenSpent and tokenReceived should be immutable | low | Acc. to the inline comment both `tokenSpent` and `tokenReceived` should be immutable but they are not declared as such.\\n```\\n// tokenSpent and tokenReceived are immutable\\ntokenSpent = \\_tokenSpent;\\ntokenReceived = \\_tokenReceived;\\n```\\n\\n```\\n/// @notice the token to be auctioned\\naddress public override tokenSpent;\\n\\n/// @notice the token to buy\\naddress public override tokenReceived;\\n```\\n | Declare both variable `immutable`. | null | ```\\n// tokenSpent and tokenReceived are immutable\\ntokenSpent = \\_tokenSpent;\\ntokenReceived = \\_tokenReceived;\\n```\\n |
CollateralizationOracle - potentially unsafe casts | low | `protocolControlledValue` is the cumulative USD token value of all tokens in the PCV. The USD value is determined using external chainlink oracles. To mitigate some effects of attacks on chainlink to propagate to this protocol it is recommended to implement a defensive approach to handling values derived from the external source. Arithm. overflows are checked by the compiler (0.8.4), however, it does not guarantee safe casting from unsigned to signed integer. The scenario of this happening might be rather unlikely, however, there is no guarantee that the external price-feed is not taken over by malicious actors and this is when every line of defense counts.\\n```\\n//solidity 0.8.7\\n » int(uint(2\\*\\*255))\\n-57896044618658097711785492504343953926634992332820282019728792003956564819968\\n » int(uint(2\\*\\*255-2))\\n57896044618658097711785492504343953926634992332820282019728792003956564819966\\n```\\n\\n```\\nprotocolEquity = int256(protocolControlledValue) - int256(userCirculatingFei);\\n```\\n\\n```\\nprotocolControlledValue += \\_oraclePrice.mul(\\_totalTokenBalance).asUint256();\\n```\\n | Perform overflow checked SafeCast as another line of defense against oracle manipulation. | null | ```\\n//solidity 0.8.7\\n » int(uint(2\\*\\*255))\\n-57896044618658097711785492504343953926634992332820282019728792003956564819968\\n » int(uint(2\\*\\*255-2))\\n57896044618658097711785492504343953926634992332820282019728792003956564819966\\n```\\n |
FeiTimedMinter - constructor does not enforce the same boundaries as setter for frequency | low | The setter method for `frequency` enforced upper and lower bounds while the constructor does not. Users cannot trust that the `frequency` is actually set to be within bounds on deployment.\\n```\\nconstructor(\\n address \\_core,\\n address \\_target,\\n uint256 \\_incentive,\\n uint256 \\_frequency,\\n uint256 \\_initialMintAmount\\n)\\n CoreRef(\\_core)\\n Timed(\\_frequency)\\n Incentivized(\\_incentive)\\n RateLimitedMinter((\\_initialMintAmount + \\_incentive) / \\_frequency, (\\_initialMintAmount + \\_incentive), true)\\n{\\n \\_initTimed();\\n\\n \\_setTarget(\\_target);\\n \\_setMintAmount(\\_initialMintAmount);\\n}\\n```\\n\\n```\\nfunction setFrequency(uint256 newFrequency) external override onlyGovernorOrAdmin {\\n require(newFrequency >= MIN\\_MINT\\_FREQUENCY, "FeiTimedMinter: frequency low");\\n require(newFrequency <= MAX\\_MINT\\_FREQUENCY, "FeiTimedMinter: frequency high");\\n\\n \\_setDuration(newFrequency);\\n}\\n```\\n | Perform the same checks on `frequency` in the constructor as in the `setFrequency` method.\\nThis contract is also inherited by a range of contracts that might specify different boundaries to what is hardcoded in the `FeiTimedMinter`. A way to enforce bounds-checks could be to allow overriding the setter method and using the setter in the constructor as well ensuring that bounds are also checked on deployment. | null | ```\\nconstructor(\\n address \\_core,\\n address \\_target,\\n uint256 \\_incentive,\\n uint256 \\_frequency,\\n uint256 \\_initialMintAmount\\n)\\n CoreRef(\\_core)\\n Timed(\\_frequency)\\n Incentivized(\\_incentive)\\n RateLimitedMinter((\\_initialMintAmount + \\_incentive) / \\_frequency, (\\_initialMintAmount + \\_incentive), true)\\n{\\n \\_initTimed();\\n\\n \\_setTarget(\\_target);\\n \\_setMintAmount(\\_initialMintAmount);\\n}\\n```\\n |
CollateralizationOracle - swapDeposit should call internal functions to remove/add deposits | low | Instead of calling `removeDeposit` and `addDeposit`, `swapDeposit` should call its internal sister functions `_removeDeposit` and `_addDeposit` to avoid running the `onlyGovernor` checks multiple times.\\n```\\n/// @notice Swap a PCVDeposit with a new one, for instance when a new version\\n/// of a deposit (holding the same token) is deployed.\\n/// @param \\_oldDeposit : the PCVDeposit to remove from the list.\\n/// @param \\_newDeposit : the PCVDeposit to add to the list.\\nfunction swapDeposit(address \\_oldDeposit, address \\_newDeposit) external onlyGovernor {\\n removeDeposit(\\_oldDeposit);\\n addDeposit(\\_newDeposit);\\n}\\n```\\n | Call the internal functions instead. addDeposit's and removeDeposit's visibility can then be changed from `public` to `external`. | null | ```\\n/// @notice Swap a PCVDeposit with a new one, for instance when a new version\\n/// of a deposit (holding the same token) is deployed.\\n/// @param \\_oldDeposit : the PCVDeposit to remove from the list.\\n/// @param \\_newDeposit : the PCVDeposit to add to the list.\\nfunction swapDeposit(address \\_oldDeposit, address \\_newDeposit) external onlyGovernor {\\n removeDeposit(\\_oldDeposit);\\n addDeposit(\\_newDeposit);\\n}\\n```\\n |
CollateralizationOracle - misleading comments | low | According to an inline comment in `isOvercollateralized`, the validity status of `pcvStats` is ignored, while it is actually being checked.\\nSimilarly, a comment in `pcvStats` mentions that the returned `protocolEquity` is 0 if there is less PCV than circulating FEI, while in reality, `pcvStats` always returns the difference between the former and the latter, even if it is negative.\\n```\\n/// Controlled Value) than the circulating (user-owned) FEI, i.e.\\n/// a positive Protocol Equity.\\n/// Note: the validity status is ignored in this function.\\nfunction isOvercollateralized() external override view whenNotPaused returns (bool) {\\n (,, int256 \\_protocolEquity, bool \\_valid) = pcvStats();\\n require(\\_valid, "CollateralizationOracle: reading is invalid");\\n return \\_protocolEquity > 0;\\n}\\n```\\n\\n```\\n/// @return protocolEquity : the difference between PCV and user circulating FEI.\\n/// If there are more circulating FEI than $ in the PCV, equity is 0.\\n```\\n\\n```\\nprotocolEquity = int256(protocolControlledValue) - int256(userCirculatingFei);\\n```\\n | Revise the comments. | null | ```\\n/// Controlled Value) than the circulating (user-owned) FEI, i.e.\\n/// a positive Protocol Equity.\\n/// Note: the validity status is ignored in this function.\\nfunction isOvercollateralized() external override view whenNotPaused returns (bool) {\\n (,, int256 \\_protocolEquity, bool \\_valid) = pcvStats();\\n require(\\_valid, "CollateralizationOracle: reading is invalid");\\n return \\_protocolEquity > 0;\\n}\\n```\\n |
The withdrawUnstakedTokens may run out of gas | high | The `withdrawUnstakedTokens` is iterating over all batches of unstaked tokens. One user, if unstaked many times, could get their tokens stuck in the contract.\\n```\\nfunction withdrawUnstakedTokens(address staker)\\n public\\n virtual\\n override\\n whenNotPaused\\n{\\n require(staker == \\_msgSender(), "LQ20");\\n uint256 \\_withdrawBalance;\\n uint256 \\_unstakingExpirationLength = \\_unstakingExpiration[staker]\\n .length;\\n uint256 \\_counter = \\_withdrawCounters[staker];\\n for (\\n uint256 i = \\_counter;\\n i < \\_unstakingExpirationLength;\\n i = i.add(1)\\n ) {\\n //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed\\n (uint256 \\_getUnstakeTime, , ) = getUnstakeTime(\\n \\_unstakingExpiration[staker][i]\\n );\\n if (block.timestamp >= \\_getUnstakeTime) {\\n //if 21 days + epoch difference has passed, then add the balance and then mint uTokens\\n \\_withdrawBalance = \\_withdrawBalance.add(\\n \\_unstakingAmount[staker][i]\\n );\\n \\_unstakingExpiration[staker][i] = 0;\\n \\_unstakingAmount[staker][i] = 0;\\n \\_withdrawCounters[staker] = \\_withdrawCounters[staker].add(1);\\n }\\n }\\n\\n require(\\_withdrawBalance > 0, "LQ21");\\n emit WithdrawUnstakeTokens(staker, \\_withdrawBalance, block.timestamp);\\n \\_uTokens.mint(staker, \\_withdrawBalance);\\n}\\n```\\n | Resolution\\nComment from pSTAKE Finance team:\\nHave implemented a batchingLimit variable which enforces a definite number of iterations during withdrawal of unstaked tokens, instead of indefinite iterations.\\nLimit the number of processed unstaked batches, and possibly add pagination. | null | ```\\nfunction withdrawUnstakedTokens(address staker)\\n public\\n virtual\\n override\\n whenNotPaused\\n{\\n require(staker == \\_msgSender(), "LQ20");\\n uint256 \\_withdrawBalance;\\n uint256 \\_unstakingExpirationLength = \\_unstakingExpiration[staker]\\n .length;\\n uint256 \\_counter = \\_withdrawCounters[staker];\\n for (\\n uint256 i = \\_counter;\\n i < \\_unstakingExpirationLength;\\n i = i.add(1)\\n ) {\\n //get getUnstakeTime and compare it with current timestamp to check if 21 days + epoch difference has passed\\n (uint256 \\_getUnstakeTime, , ) = getUnstakeTime(\\n \\_unstakingExpiration[staker][i]\\n );\\n if (block.timestamp >= \\_getUnstakeTime) {\\n //if 21 days + epoch difference has passed, then add the balance and then mint uTokens\\n \\_withdrawBalance = \\_withdrawBalance.add(\\n \\_unstakingAmount[staker][i]\\n );\\n \\_unstakingExpiration[staker][i] = 0;\\n \\_unstakingAmount[staker][i] = 0;\\n \\_withdrawCounters[staker] = \\_withdrawCounters[staker].add(1);\\n }\\n }\\n\\n require(\\_withdrawBalance > 0, "LQ21");\\n emit WithdrawUnstakeTokens(staker, \\_withdrawBalance, block.timestamp);\\n \\_uTokens.mint(staker, \\_withdrawBalance);\\n}\\n```\\n |
The _calculatePendingRewards can run out of gas | medium | The reward rate in STokens can be changed, and the history of these changes are stored in the contract:\\n```\\nfunction setRewardRate(uint256 rewardRate)\\n public\\n virtual\\n override\\n returns (bool success)\\n{\\n // range checks for rewardRate. Since rewardRate cannot be more than 100%, the max cap\\n // is \\_valueDivisor \\* 100, which then brings the fees to 100 (percentage)\\n require(rewardRate <= \\_valueDivisor.mul(100), "ST17");\\n require(hasRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender()), "ST2");\\n \\_rewardRate.push(rewardRate);\\n \\_lastMovingRewardTimestamp.push(block.timestamp);\\n emit SetRewardRate(rewardRate);\\n\\n return true;\\n}\\n```\\n\\nWhen the reward is calculated `for` each user, all changes of the `_rewardRate` are considered. So there is a `for` loop that iterates over all changes since the last reward update. If the reward rate was changed many times, the `_calculatePendingRewards` function could run out of gas. | Provide an option to partially update the reward, so the full update can be split in multiple transactions. | null | ```\\nfunction setRewardRate(uint256 rewardRate)\\n public\\n virtual\\n override\\n returns (bool success)\\n{\\n // range checks for rewardRate. Since rewardRate cannot be more than 100%, the max cap\\n // is \\_valueDivisor \\* 100, which then brings the fees to 100 (percentage)\\n require(rewardRate <= \\_valueDivisor.mul(100), "ST17");\\n require(hasRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender()), "ST2");\\n \\_rewardRate.push(rewardRate);\\n \\_lastMovingRewardTimestamp.push(block.timestamp);\\n emit SetRewardRate(rewardRate);\\n\\n return true;\\n}\\n```\\n |
The calculateRewards should not be callable by the whitelisted contract | medium | The `calculateRewards` function should only be called for non-whitelisted addresses:\\n```\\nfunction calculateRewards(address to)\\n public\\n virtual\\n override\\n whenNotPaused\\n returns (bool success)\\n{\\n require(to == \\_msgSender(), "ST5");\\n uint256 reward = \\_calculateRewards(to);\\n emit TriggeredCalculateRewards(to, reward, block.timestamp);\\n return true;\\n}\\n```\\n\\nFor all the whitelisted addresses, the `calculateHolderRewards` function is called. But if the `calculateRewards` function is called by the whitelisted address directly, the function will execute, and the rewards will be distributed to the caller instead of the intended recipients. | Resolution\\nComment from pSTAKE Finance team:\\nHave created a require condition in Smart Contract code to disallow whitelisted contracts from calling the function\\nWhile this scenario is unlikely to happen, adding the additional check in the `calculateRewards` is a good option. | null | ```\\nfunction calculateRewards(address to)\\n public\\n virtual\\n override\\n whenNotPaused\\n returns (bool success)\\n{\\n require(to == \\_msgSender(), "ST5");\\n uint256 reward = \\_calculateRewards(to);\\n emit TriggeredCalculateRewards(to, reward, block.timestamp);\\n return true;\\n}\\n```\\n |
Presence of testnet code | medium | Based on the discussions with pStake team and in-line comments, there are a few instances of code and commented code in the code base under audit that are not finalized for mainnet deployment.\\n```\\nfunction initialize(address pauserAddress) public virtual initializer {\\n \\_\\_ERC20\\_init("pSTAKE Token", "PSTAKE");\\n \\_\\_AccessControl\\_init();\\n \\_\\_Pausable\\_init();\\n \\_setupRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender());\\n \\_setupRole(PAUSER\\_ROLE, pauserAddress);\\n // PSTAKE IS A SIMPLE ERC20 TOKEN HENCE 18 DECIMAL PLACES\\n \\_setupDecimals(18);\\n // pre-allocate some tokens to an admin address which will air drop PSTAKE tokens\\n // to each of holder contracts. This is only for testnet purpose. in Mainnet, we\\n // will use a vesting contract to allocate tokens to admin in a certain schedule\\n \\_mint(\\_msgSender(), 5000000000000000000000000);\\n}\\n```\\n\\nThe initialize function currently mints all the tokens to msg.sender, however the goal for mainnet is to use a vesting contract which is not present in the current code. | It is recommended to fully test the final code before deployment to the mainnet. | null | ```\\nfunction initialize(address pauserAddress) public virtual initializer {\\n \\_\\_ERC20\\_init("pSTAKE Token", "PSTAKE");\\n \\_\\_AccessControl\\_init();\\n \\_\\_Pausable\\_init();\\n \\_setupRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender());\\n \\_setupRole(PAUSER\\_ROLE, pauserAddress);\\n // PSTAKE IS A SIMPLE ERC20 TOKEN HENCE 18 DECIMAL PLACES\\n \\_setupDecimals(18);\\n // pre-allocate some tokens to an admin address which will air drop PSTAKE tokens\\n // to each of holder contracts. This is only for testnet purpose. in Mainnet, we\\n // will use a vesting contract to allocate tokens to admin in a certain schedule\\n \\_mint(\\_msgSender(), 5000000000000000000000000);\\n}\\n```\\n |
Sanity check on all important variables | low | Most of the functionalities have proper sanity checks when it comes to setting system-wide variables, such as whitelist addresses. However there are a few key setters that lack such sanity checks.\\nSanity check (!= address(0)) on all token contracts.\\n```\\nfunction setUTokensContract(address uAddress) public virtual override {\\n require(hasRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender()), "LP9");\\n \\_uTokens = IUTokens(uAddress);\\n emit SetUTokensContract(uAddress);\\n}\\n\\n/\\*\\*\\n \\* @dev Set 'contract address', called from constructor\\n \\* @param sAddress: stoken contract address\\n \\*\\n \\* Emits a {SetSTokensContract} event with '\\_contract' set to the stoken contract address.\\n \\*\\n \\*/\\nfunction setSTokensContract(address sAddress) public virtual override {\\n require(hasRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender()), "LP10");\\n \\_sTokens = ISTokens(sAddress);\\n emit SetSTokensContract(sAddress);\\n}\\n\\n/\\*\\*\\n \\* @dev Set 'contract address', called from constructor\\n \\* @param pstakeAddress: pStake contract address\\n \\*\\n \\* Emits a {SetPSTAKEContract} event with '\\_contract' set to the stoken contract address.\\n \\*\\n \\*/\\nfunction setPSTAKEContract(address pstakeAddress) public virtual override {\\n require(hasRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender()), "LP11");\\n \\_pstakeTokens = IPSTAKE(pstakeAddress);\\n emit SetPSTAKEContract(pstakeAddress);\\n}\\n```\\n\\nSanity check on `unstakingLockTime` to be in the acceptable range (21 hours to 21 days)\\n```\\n/\\*\\*\\n \\* @dev Set 'unstake props', called from admin\\n \\* @param unstakingLockTime: varies from 21 hours to 21 days\\n \\*\\n \\* Emits a {SetUnstakeProps} event with 'fee' set to the stake and unstake.\\n \\*\\n \\*/\\nfunction setUnstakingLockTime(uint256 unstakingLockTime)\\n public\\n virtual\\n returns (bool success)\\n{\\n require(hasRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender()), "LQ3");\\n \\_unstakingLockTime = unstakingLockTime;\\n emit SetUnstakingLockTime(unstakingLockTime);\\n return true;\\n}\\n```\\n | Resolution\\nComment from pSTAKE Finance team:\\nPost the implementation of new emission logic there have been a rearrangement of some variables, but the rest have been sanity tested and corrected | null | ```\\nfunction setUTokensContract(address uAddress) public virtual override {\\n require(hasRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender()), "LP9");\\n \\_uTokens = IUTokens(uAddress);\\n emit SetUTokensContract(uAddress);\\n}\\n\\n/\\*\\*\\n \\* @dev Set 'contract address', called from constructor\\n \\* @param sAddress: stoken contract address\\n \\*\\n \\* Emits a {SetSTokensContract} event with '\\_contract' set to the stoken contract address.\\n \\*\\n \\*/\\nfunction setSTokensContract(address sAddress) public virtual override {\\n require(hasRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender()), "LP10");\\n \\_sTokens = ISTokens(sAddress);\\n emit SetSTokensContract(sAddress);\\n}\\n\\n/\\*\\*\\n \\* @dev Set 'contract address', called from constructor\\n \\* @param pstakeAddress: pStake contract address\\n \\*\\n \\* Emits a {SetPSTAKEContract} event with '\\_contract' set to the stoken contract address.\\n \\*\\n \\*/\\nfunction setPSTAKEContract(address pstakeAddress) public virtual override {\\n require(hasRole(DEFAULT\\_ADMIN\\_ROLE, \\_msgSender()), "LP11");\\n \\_pstakeTokens = IPSTAKE(pstakeAddress);\\n emit SetPSTAKEContract(pstakeAddress);\\n}\\n```\\n |
TransactionManager - Receiver-side check also on sending side Fix | high | The functions `prepare`, `cancel`, and `fulfill` in the `TransactionManager` all have a “common part” that is executed on both the sending and the receiving chain and side-specific parts that are only executed either on the sending or on the receiving side.\\nThe following lines occur in fulfill's common part, but this should only be checked on the receiving chain. In fact, on the sending chain, we might even compare amounts of different assets.\\n```\\n// Sanity check: fee <= amount. Allow `=` in case of only wanting to execute\\n// 0-value crosschain tx, so only providing the fee amount\\nrequire(relayerFee <= txData.amount, "#F:023");\\n```\\n\\nThis could prevent a legitimate `fulfill` on the sending chain, causing a loss of funds for the router. | Resolution\\nThe Connext team claims to have fixed this in commit `4adbfd52703441ee5de655130fc2e0252eae4661`. We have not reviewed this commit or, generally, the codebase at this point.\\nMove these lines to the receiving-side part.\\nRemark\\nThe `callData` supplied to `fulfill` is not used at all on the sending chain, but the check whether its hash matches `txData.callDataHash` happens in the common part.\\n```\\n// Check provided callData matches stored hash\\nrequire(keccak256(callData) == txData.callDataHash, "#F:024");\\n```\\n\\nIn principle, this check could also be moved to the receiving-chain part, allowing the router to save some gas by calling sending-side `fulfill` with empty `callData` and skip the check. Note, however, that the `TransactionFulfilled` event will then also emit the “wrong” `callData` on the sending chain, so the off-chain code has to be able to deal with that if you want to employ this optimization. | null | ```\\n// Sanity check: fee <= amount. Allow `=` in case of only wanting to execute\\n// 0-value crosschain tx, so only providing the fee amount\\nrequire(relayerFee <= txData.amount, "#F:023");\\n```\\n |
TransactionManager - Missing nonReentrant modifier on removeLiquidity | medium | Resolution\\nThis issue has been fixed.\\nThe `removeLiquidity` function does not have a `nonReentrant` modifier.\\n```\\n/\\*\\*\\n \\* @notice This is used by any router to decrease their available\\n \\* liquidity for a given asset.\\n \\* @param shares The amount of liquidity to remove for the router in shares\\n \\* @param assetId The address (or `address(0)` if native asset) of the\\n \\* asset you're removing liquidity for\\n \\* @param recipient The address that will receive the liquidity being removed\\n \\*/\\nfunction removeLiquidity(\\n uint256 shares,\\n address assetId,\\n address payable recipient\\n) external override {\\n // Sanity check: recipient is sensible\\n require(recipient != address(0), "#RL:007");\\n\\n // Sanity check: nonzero shares\\n require(shares > 0, "#RL:035");\\n\\n // Get stored router shares\\n uint256 routerShares = issuedShares[msg.sender][assetId];\\n\\n // Get stored outstanding shares\\n uint256 outstanding = outstandingShares[assetId];\\n\\n // Sanity check: owns enough shares\\n require(routerShares >= shares, "#RL:018");\\n\\n // Convert shares to amount\\n uint256 amount = getAmountFromIssuedShares(\\n shares,\\n outstanding,\\n Asset.getOwnBalance(assetId)\\n );\\n\\n // Update router issued shares\\n // NOTE: unchecked due to require above\\n unchecked {\\n issuedShares[msg.sender][assetId] = routerShares - shares;\\n }\\n\\n // Update the total shares for asset\\n outstandingShares[assetId] = outstanding - shares;\\n\\n // Transfer from contract to specified recipient\\n Asset.transferAsset(assetId, recipient, amount);\\n\\n // Emit event\\n emit LiquidityRemoved(\\n msg.sender,\\n assetId,\\n shares,\\n amount,\\n recipient\\n );\\n}\\n```\\n\\nAssuming we're dealing with a token contract that allows execution of third-party-supplied code, that means it is possible to leave the `TransactionManager` contract in one of the functions that call into the token contract and then reenter via `removeLiquidity`. Alternatively, we can leave the contract in `removeLiquidity` and reenter through an arbitrary external function, even if it has a `nonReentrant` modifier.\\nExample\\nAssume a token contract allows the execution of third-party-supplied code in its `transfer` function before the actual balance change takes place. If a router calls `removeLiquidity` with half of their shares and then, in a reentering `removeLiquidity` call, supplies the other half of their shares, they will receive more tokens than if they had liquidated all their shares at once because the reentering call occurs after the (first half of the) shares have been burnt but before the corresponding amount of tokens has actually been transferred out of the contract, leading to an artificially increased share value in the reentering call. Similarly, reentering the contract with a `fulfill` call on the receiving chain instead of a second `removeLiquidity` would `transfer` too many tokens to the recipient due to the artificially inflated share value. | While tokens that behave as described in the example might be rare or not exist at all, caution is advised when integrating with unknown tokens or calling untrusted code in general. We strongly recommend adding a `nonReentrant` modifier to `removeLiquidity`. | null | ```\\n/\\*\\*\\n \\* @notice This is used by any router to decrease their available\\n \\* liquidity for a given asset.\\n \\* @param shares The amount of liquidity to remove for the router in shares\\n \\* @param assetId The address (or `address(0)` if native asset) of the\\n \\* asset you're removing liquidity for\\n \\* @param recipient The address that will receive the liquidity being removed\\n \\*/\\nfunction removeLiquidity(\\n uint256 shares,\\n address assetId,\\n address payable recipient\\n) external override {\\n // Sanity check: recipient is sensible\\n require(recipient != address(0), "#RL:007");\\n\\n // Sanity check: nonzero shares\\n require(shares > 0, "#RL:035");\\n\\n // Get stored router shares\\n uint256 routerShares = issuedShares[msg.sender][assetId];\\n\\n // Get stored outstanding shares\\n uint256 outstanding = outstandingShares[assetId];\\n\\n // Sanity check: owns enough shares\\n require(routerShares >= shares, "#RL:018");\\n\\n // Convert shares to amount\\n uint256 amount = getAmountFromIssuedShares(\\n shares,\\n outstanding,\\n Asset.getOwnBalance(assetId)\\n );\\n\\n // Update router issued shares\\n // NOTE: unchecked due to require above\\n unchecked {\\n issuedShares[msg.sender][assetId] = routerShares - shares;\\n }\\n\\n // Update the total shares for asset\\n outstandingShares[assetId] = outstanding - shares;\\n\\n // Transfer from contract to specified recipient\\n Asset.transferAsset(assetId, recipient, amount);\\n\\n // Emit event\\n emit LiquidityRemoved(\\n msg.sender,\\n assetId,\\n shares,\\n amount,\\n recipient\\n );\\n}\\n```\\n |
TransactionManager - Relayer may use user's cancel after expiry signature to steal user's funds by colluding with a router Acknowledged | medium | Users that are willing to have a lower trust dependency on a relayer should have the ability to opt-in only for the service that allows the relayer to withdraw back users' funds from the sending chain after expiry. However, in practice, a user is forced to opt-in for the service that refunds the router before the expiry, since the same signature is used for both services (lines 795,817 use the same signature).\\nLet's consider the case of a user willing to call `fulfill` on his own, but to use the relayer only to withdraw back his funds from the sending chain after expiry. In this case, the relayer can collude with the router and use the user's `cancel` signature (meant for withdrawing his only after expiry) as a front-running transaction for a user call to `fulfill`. This way the router will be able to withdraw both his funds and the user's funds since the user's `fulfill` signature is now public data residing in the mem-pool.\\n```\\n require(msg.sender == txData.user || recoverSignature(txData.transactionId, relayerFee, "cancel", signature) == txData.user, "#C:022");\\n\\n Asset.transferAsset(txData.sendingAssetId, payable(msg.sender), relayerFee);\\n }\\n\\n // Get the amount to refund the user\\n uint256 toRefund;\\n unchecked {\\n toRefund = amount - relayerFee;\\n }\\n\\n // Return locked funds to sending chain fallback\\n if (toRefund > 0) {\\n Asset.transferAsset(txData.sendingAssetId, payable(txData.sendingChainFallback), toRefund);\\n }\\n }\\n\\n} else {\\n // Receiver side, router liquidity is returned\\n if (txData.expiry >= block.timestamp) {\\n // Timeout has not expired and tx may only be cancelled by user\\n // Validate signature\\n require(msg.sender == txData.user || recoverSignature(txData.transactionId, relayerFee, "cancel", signature) == txData.user, "#C:022");\\n```\\n | The crucial point here is that the user must never sign a “cancel” that could be used on the receiving chain while fulfillment on the sending chain is still a possibility.\\nOr, to put it differently: A user may only sign a “cancel” that is valid on the receiving chain after sending-chain expiry or if they never have and won't ever sign a “fulfill” (or at least won't sign until sending-chain expiry — but it is pointless to sign a “fulfill” after that, so “never” is a reasonable simplification).\\nOr, finally, a more symmetric perspective on this requirement: If a user has signed “fulfill”, they must not sign a receiving-chain-valid “cancel” until sending-chain expiry, and if they have signed a receiving-chain-valid “cancel”, they must not sign a “fulfill” (until sending-chain expiry).\\nIn this sense, “cancel” signatures that are valid on the receiving chain are dangerous, while sending-side cancellations are not. So the principle stated in the previous paragraph might be easier to follow with different signatures for sending- and receiving-chain cancellations. | null | ```\\n require(msg.sender == txData.user || recoverSignature(txData.transactionId, relayerFee, "cancel", signature) == txData.user, "#C:022");\\n\\n Asset.transferAsset(txData.sendingAssetId, payable(msg.sender), relayerFee);\\n }\\n\\n // Get the amount to refund the user\\n uint256 toRefund;\\n unchecked {\\n toRefund = amount - relayerFee;\\n }\\n\\n // Return locked funds to sending chain fallback\\n if (toRefund > 0) {\\n Asset.transferAsset(txData.sendingAssetId, payable(txData.sendingChainFallback), toRefund);\\n }\\n }\\n\\n} else {\\n // Receiver side, router liquidity is returned\\n if (txData.expiry >= block.timestamp) {\\n // Timeout has not expired and tx may only be cancelled by user\\n // Validate signature\\n require(msg.sender == txData.user || recoverSignature(txData.transactionId, relayerFee, "cancel", signature) == txData.user, "#C:022");\\n```\\n |
ProposedOwnable - two-step ownership transfer should be confirmed by the new owner | medium | In order to avoid losing control of the contract, the two-step ownership transfer should be confirmed by the new owner's address instead of the current owner.\\n`acceptProposedOwner` is restricted to `onlyOwner` while ownership should be accepted by the newOwner\\n```\\n/\\*\\*\\n \\* @notice Transfers ownership of the contract to a new account (`newOwner`).\\n \\* Can only be called by the current owner.\\n \\*/\\nfunction acceptProposedOwner() public virtual onlyOwner {\\n require((block.timestamp - \\_proposedTimestamp) > \\_delay, "#APO:030");\\n \\_setOwner(\\_proposed);\\n}\\n```\\n\\nmove `renounced()` to `ProposedOwnable` as this is where it logically belongs to\\n```\\nfunction renounced() public view override returns (bool) {\\n return owner() == address(0);\\n}\\n```\\n\\n`onlyOwner` can directly access state-var `_owner` instead of spending more gas on calling `owner()`\\n```\\nmodifier onlyOwner() {\\n require(owner() == msg.sender, "#OO:029");\\n \\_;\\n}\\n```\\n | Resolution\\nAll recommendations given below have been implemented. In addition to that, the privilege to manage assets and the privilege to manage routers can now be renounced separately.\\n`onlyOwner` can directly access `_owner` (gas optimization)\\nadd a method to explicitly renounce ownership of the contract\\nmove `TransactionManager.renounced()` to `ProposedOwnable` as this is where it logically belongs to\\nchange the access control for `acceptProposedOwner` from `onlyOwner` to `require(msg.sender == _proposed)` (new owner). | null | ```\\n/\\*\\*\\n \\* @notice Transfers ownership of the contract to a new account (`newOwner`).\\n \\* Can only be called by the current owner.\\n \\*/\\nfunction acceptProposedOwner() public virtual onlyOwner {\\n require((block.timestamp - \\_proposedTimestamp) > \\_delay, "#APO:030");\\n \\_setOwner(\\_proposed);\\n}\\n```\\n |
FulfillInterpreter - Wrong order of actions in fallback handling | low | When a transaction with a `callTo` that is not `address(0)` is fulfilled, the funds to be withdrawn on the user's behalf are first transferred to the `FulfillInterpreter` instance that is associated with this `TransactionManager` instance. After that, `execute` is called on that interpreter instance, which, in turn, tries to make a call to `callTo`. If that call reverts or isn't made in the first place because `callTo` is not a contract address, the funds are transferred directly to the `receivingAddress` in the transaction (which becomes `fallbackAddress` in execute); otherwise, it's the called contract's task to transfer the previously approved funds from the interpreter.\\n```\\nbool isNative = LibAsset.isNativeAsset(assetId);\\nif (!isNative) {\\n LibAsset.increaseERC20Allowance(assetId, callTo, amount);\\n}\\n\\n// Check if the callTo is a contract\\nbool success;\\nbytes memory returnData;\\nif (Address.isContract(callTo)) {\\n // Try to execute the callData\\n // the low level call will return `false` if its execution reverts\\n (success, returnData) = callTo.call{value: isNative ? amount : 0}(callData);\\n}\\n\\n// Handle failure cases\\nif (!success) {\\n // If it fails, transfer to fallback\\n LibAsset.transferAsset(assetId, fallbackAddress, amount);\\n // Decrease allowance\\n if (!isNative) {\\n LibAsset.decreaseERC20Allowance(assetId, callTo, amount);\\n }\\n}\\n```\\n\\nFor the fallback scenario, i.e., the call isn't executed or fails, the funds are first transferred to `fallbackAddress`, and the previously increased allowance is decreased after that. If the token supports it, the recipient of the direct transfer could try to exploit that the approval hasn't been revoked yet, so the logically correct order is to decrease the allowance first and transfer the funds later. However, it should be noted that the `FulfillInterpreter` should, at any point in time, only hold the funds that are supposed to be transferred as part of the current transaction; if there are any excess funds, these are leftovers from a previous failure to withdraw everything that could have been withdrawn, so these can be considered up for grabs. Hence, this is only a minor issue. | We recommend reversing the order of actions for the fallback case: Decrease the allowance first, and transfer later. Moreover, it would be better to increase the allowance only in case a call will actually be made, i.e., if `Address.isContract(callTo)` is `true`.\\nRemark\\nThis issue was already present in the original version of the code but was missed initially and only found during the re-audit. | null | ```\\nbool isNative = LibAsset.isNativeAsset(assetId);\\nif (!isNative) {\\n LibAsset.increaseERC20Allowance(assetId, callTo, amount);\\n}\\n\\n// Check if the callTo is a contract\\nbool success;\\nbytes memory returnData;\\nif (Address.isContract(callTo)) {\\n // Try to execute the callData\\n // the low level call will return `false` if its execution reverts\\n (success, returnData) = callTo.call{value: isNative ? amount : 0}(callData);\\n}\\n\\n// Handle failure cases\\nif (!success) {\\n // If it fails, transfer to fallback\\n LibAsset.transferAsset(assetId, fallbackAddress, amount);\\n // Decrease allowance\\n if (!isNative) {\\n LibAsset.decreaseERC20Allowance(assetId, callTo, amount);\\n }\\n}\\n```\\n |
FulfillInterpreter - Missing check whether callTo address contains code | low | Resolution\\nThis issue has been fixed.\\nThe receiver-side `prepare` checks whether the `callTo` address is either zero or a contract:\\n```\\n// Check that the callTo is a contract\\n// NOTE: This cannot happen on the sending chain (different chain\\n// contexts), so a user could mistakenly create a transfer that must be\\n// cancelled if this is incorrect\\nrequire(invariantData.callTo == address(0) || Address.isContract(invariantData.callTo), "#P:031");\\n```\\n\\nHowever, as a contract may `selfdestruct` and the check is not repeated later, there is no guarantee that `callTo` still contains code when the call to this address (assuming it is non-zero) is actually executed in FulfillInterpreter.execute:\\n```\\n// Try to execute the callData\\n// the low level call will return `false` if its execution reverts\\n(bool success, bytes memory returnData) = callTo.call{value: isEther ? amount : 0}(callData);\\n\\nif (!success) {\\n // If it fails, transfer to fallback\\n Asset.transferAsset(assetId, fallbackAddress, amount);\\n // Decrease allowance\\n if (!isEther) {\\n Asset.decreaseERC20Allowance(assetId, callTo, amount);\\n }\\n}\\n```\\n\\nAs a result, if the contract at `callTo` self-destructs between `prepare` and `fulfill` (both on the receiving chain), `success` will be `true`, and the funds will probably be lost to the user.\\nA user could currently try to avoid this by checking that the contract still exists before calling `fulfill` on the receiving chain, but even then, they might get front-run by `selfdestruct`, and the situation is even worse with a relayer, so this provides no reliable protection. | Repeat the `Address.isContract` check on `callTo` before making the external call in `FulfillInterpreter.execute` and send the funds to the `fallbackAddress` if the result is `false`.\\nIt is, perhaps, debatable whether the check in `prepare` should be kept or removed. In principle, if the contract gets deployed between `prepare` and `fulfill`, that is still soon enough. However, if the `callTo` address doesn't have code at the time of `prepare`, this seems more likely to be a mistake than a “late deployment”. So unless there is a demonstrated use case for “late deployments”, failing in `prepare` (even though it's receiver-side) might still be the better choice.\\nRemark\\nIt should be noted that an unsuccessful call, i.e., a revert, is the only behavior that is recognized by `FulfillInterpreter.execute` as failure. While it is prevalent to indicate failure by reverting, this doesn't have to be the case; a well-known example is an ERC20 token that indicates a failing transfer by returning `false`.\\nA user who wants to utilize this feature has to make sure that the called contract behaves accordingly; if that is not the case, an intermediary contract may be employed, which, for example, reverts for return value `false`. | null | ```\\n// Check that the callTo is a contract\\n// NOTE: This cannot happen on the sending chain (different chain\\n// contexts), so a user could mistakenly create a transfer that must be\\n// cancelled if this is incorrect\\nrequire(invariantData.callTo == address(0) || Address.isContract(invariantData.callTo), "#P:031");\\n```\\n |
TransactionManager - Adherence to EIP-712 Won't Fix | low | `fulfill` function requires the user signature on a `transactionId`. While currently, the user SDK code is using a cryptographically secured pseudo-random function to generate the `transactionId`, it should not be counted upon and measures should be placed on the smart-contract level to ensure replay-attack protection.\\n```\\nfunction recoverSignature(\\n bytes32 transactionId,\\n uint256 relayerFee,\\n string memory functionIdentifier,\\n bytes calldata signature\\n) internal pure returns (address) {\\n // Create the signed payload\\n SignedData memory payload = SignedData({\\n transactionId: transactionId,\\n relayerFee: relayerFee,\\n functionIdentifier: functionIdentifier\\n });\\n\\n // Recover\\n return ECDSA.recover(ECDSA.toEthSignedMessageHash(keccak256(abi.encode(payload))), signature);\\n}\\n```\\n | Consider adhering to EIP-712, or at least including `address(this), block.chainId` as part of the data signed by the user. | null | ```\\nfunction recoverSignature(\\n bytes32 transactionId,\\n uint256 relayerFee,\\n string memory functionIdentifier,\\n bytes calldata signature\\n) internal pure returns (address) {\\n // Create the signed payload\\n SignedData memory payload = SignedData({\\n transactionId: transactionId,\\n relayerFee: relayerFee,\\n functionIdentifier: functionIdentifier\\n });\\n\\n // Recover\\n return ECDSA.recover(ECDSA.toEthSignedMessageHash(keccak256(abi.encode(payload))), signature);\\n}\\n```\\n |
TransactionManager - Hard-coded chain ID might lead to problems after a chain split Pending | low | The ID of the chain on which the contract is deployed is supplied as a constructor argument and stored as an `immutable` state variable:\\n```\\n/\\*\\*\\n \\* @dev The chain id of the contract, is passed in to avoid any evm issues\\n \\*/\\nuint256 public immutable chainId;\\n```\\n\\n```\\nconstructor(uint256 \\_chainId) {\\n chainId = \\_chainId;\\n interpreter = new FulfillInterpreter(address(this));\\n}\\n```\\n\\nHence, `chainId` can never change, and even after a chain split, both contracts would continue to use the same chain ID. That can have undesirable consequences. For example, a transaction that was prepared before the split could be fulfilled on both chains. | It would be better to query the chain ID directly from the chain via `block.chainId`. However, the development team informed us that they had encountered problems with this approach as some chains apparently are not implementing this correctly. They resorted to the method described above, a constructor-supplied, hard-coded value. For chains that do indeed not inform correctly about their chain ID, this is a reasonable solution. However, for the reasons outlined above, we still recommend querying the chain ID via `block.chainId` for chains that do support that — which should be the vast majority — and using the fallback mechanism only when necessary. | null | ```\\n/\\*\\*\\n \\* @dev The chain id of the contract, is passed in to avoid any evm issues\\n \\*/\\nuint256 public immutable chainId;\\n```\\n |
TribalChief - A wrong user.rewardDebt value is calculated during the withdrawFromDeposit function call | high | When withdrawing a single deposit, the reward debt is updated:\\n```\\nuint128 virtualAmountDelta = uint128( ( amount \\* poolDeposit.multiplier ) / SCALE\\_FACTOR );\\n\\n// Effects\\npoolDeposit.amount -= amount;\\nuser.rewardDebt = user.rewardDebt - toSigned128(user.virtualAmount \\* pool.accTribePerShare) / toSigned128(ACC\\_TRIBE\\_PRECISION);\\nuser.virtualAmount -= virtualAmountDelta;\\npool.virtualTotalSupply -= virtualAmountDelta;\\n```\\n\\nInstead of the `user.virtualAmount` in reward debt calculation, the `virtualAmountDelta` should be used. Because of that bug, the reward debt is much lower than it would be, which means that the reward itself will be much larger during the harvest. By making multiple deposit-withdraw actions, any user can steal all the Tribe tokens from the contract. | Use the `virtualAmountDelta` instead of the `user.virtualAmount`. | null | ```\\nuint128 virtualAmountDelta = uint128( ( amount \\* poolDeposit.multiplier ) / SCALE\\_FACTOR );\\n\\n// Effects\\npoolDeposit.amount -= amount;\\nuser.rewardDebt = user.rewardDebt - toSigned128(user.virtualAmount \\* pool.accTribePerShare) / toSigned128(ACC\\_TRIBE\\_PRECISION);\\nuser.virtualAmount -= virtualAmountDelta;\\npool.virtualTotalSupply -= virtualAmountDelta;\\n```\\n |
TribalChief - Unlocking users' funds in a pool where a multiplier has been increased is missing | medium | When a user deposits funds to a pool, the current multiplier in use for this pool is being stored locally for this deposit. The value that is used later in a withdrawal operation is the local one, and not the one that is changing when a `governor` calls `governorAddPoolMultiplier`. It means that a decrease in the multiplier value for a given pool does not affect users that already deposited, but an increase does. Users that had already deposited should have the right to withdraw their funds when the multiplier for their pool increases by the `governor`.\\n```\\nfunction governorAddPoolMultiplier(\\n uint256 \\_pid,\\n uint64 lockLength,\\n uint64 newRewardsMultiplier\\n) external onlyGovernor {\\n PoolInfo storage pool = poolInfo[\\_pid];\\n uint256 currentMultiplier = rewardMultipliers[\\_pid][lockLength];\\n // if the new multplier is less than the current multiplier,\\n // then, you need to unlock the pool to allow users to withdraw\\n if (newRewardsMultiplier < currentMultiplier) {\\n pool.unlocked = true;\\n }\\n rewardMultipliers[\\_pid][lockLength] = newRewardsMultiplier;\\n\\n emit LogPoolMultiplier(\\_pid, lockLength, newRewardsMultiplier);\\n}\\n```\\n | Replace the `<` operator with `>` in `TribalChief` line 152. | null | ```\\nfunction governorAddPoolMultiplier(\\n uint256 \\_pid,\\n uint64 lockLength,\\n uint64 newRewardsMultiplier\\n) external onlyGovernor {\\n PoolInfo storage pool = poolInfo[\\_pid];\\n uint256 currentMultiplier = rewardMultipliers[\\_pid][lockLength];\\n // if the new multplier is less than the current multiplier,\\n // then, you need to unlock the pool to allow users to withdraw\\n if (newRewardsMultiplier < currentMultiplier) {\\n pool.unlocked = true;\\n }\\n rewardMultipliers[\\_pid][lockLength] = newRewardsMultiplier;\\n\\n emit LogPoolMultiplier(\\_pid, lockLength, newRewardsMultiplier);\\n}\\n```\\n |
TribalChief - Unsafe down-castings | medium | `TribalChief` consists of multiple unsafe down-casting operations. While the usage of types that can be packed into a single storage slot is more gas efficient, it may introduce hidden risks in some cases that can lead to loss of funds.\\nVarious instances in `TribalChief`, including (but not necessarily only) :\\n```\\nuser.rewardDebt = int128(user.virtualAmount \\* pool.accTribePerShare) / toSigned128(ACC\\_TRIBE\\_PRECISION);\\n```\\n\\n```\\npool.accTribePerShare = uint128(pool.accTribePerShare + ((tribeReward \\* ACC\\_TRIBE\\_PRECISION) / virtualSupply));\\n```\\n\\n```\\nuserPoolData.rewardDebt += int128(virtualAmountDelta \\* pool.accTribePerShare) / toSigned128(ACC\\_TRIBE\\_PRECISION);\\n```\\n | Given the time constraints of this audit engagement, we could not verify the implications and provide mitigation actions for each of the unsafe down-castings operations. However, we do recommend to either use numeric types that use 256 bits, or to add proper validation checks and handle these scenarios to avoid silent over/under-flow errors. Keep in mind that reverting these scenarios can sometimes lead to a denial of service, which might be harmful in some cases. | null | ```\\nuser.rewardDebt = int128(user.virtualAmount \\* pool.accTribePerShare) / toSigned128(ACC\\_TRIBE\\_PRECISION);\\n```\\n |
TribalChief - Governor decrease of pool's allocation point should unlock depositors' funds | low | When the `TribalChief` governor decreases the ratio between the allocation point (PoolInfo.allocPoint) and the total allocation point (totalAllocPoint) for a specific pool (either be directly decreasing `PoolInfo.allocPoint` of a given pool, or by increasing this value for other pools), the total reward for this pool is decreased as well. Depositors should be able to withdraw their funds immediately after this kind of change.\\n```\\nfunction set(uint256 \\_pid, uint128 \\_allocPoint, IRewarder \\_rewarder, bool overwrite) public onlyGovernor {\\n totalAllocPoint = (totalAllocPoint - poolInfo[\\_pid].allocPoint) + \\_allocPoint;\\n poolInfo[\\_pid].allocPoint = \\_allocPoint.toUint64();\\n\\n if (overwrite) {\\n rewarder[\\_pid] = \\_rewarder;\\n }\\n\\n emit LogSetPool(\\_pid, \\_allocPoint, overwrite ? \\_rewarder : rewarder[\\_pid], overwrite);\\n}\\n```\\n | Make sure that depositors' funds are unlocked for pools that affected negatively by calling `TribalChief.set`. | null | ```\\nfunction set(uint256 \\_pid, uint128 \\_allocPoint, IRewarder \\_rewarder, bool overwrite) public onlyGovernor {\\n totalAllocPoint = (totalAllocPoint - poolInfo[\\_pid].allocPoint) + \\_allocPoint;\\n poolInfo[\\_pid].allocPoint = \\_allocPoint.toUint64();\\n\\n if (overwrite) {\\n rewarder[\\_pid] = \\_rewarder;\\n }\\n\\n emit LogSetPool(\\_pid, \\_allocPoint, overwrite ? \\_rewarder : rewarder[\\_pid], overwrite);\\n}\\n```\\n |
TribalChief - new block reward retrospectively takes effect on pools that have not been updated recently | low | When the governor updates the block reward `tribalChiefTribePerBlock` the new reward is applied for the outstanding duration of blocks in `updatePool`. This means, if a pool hasn't updated in a while (unlikely) the new block reward is retrospectively applied to the pending duration instead of starting from when the block reward changed.\\nrewards calculation\\n```\\nif (virtualSupply > 0) {\\n uint256 blocks = block.number - pool.lastRewardBlock;\\n uint256 tribeReward = (blocks \\* tribePerBlock() \\* pool.allocPoint) / totalAllocPoint;\\n pool.accTribePerShare = uint128(pool.accTribePerShare + ((tribeReward \\* ACC\\_TRIBE\\_PRECISION) / virtualSupply));\\n}\\n```\\n\\nupdating the block reward\\n```\\n/// @notice Allows governor to change the amount of tribe per block\\n/// @param newBlockReward The new amount of tribe per block to distribute\\nfunction updateBlockReward(uint256 newBlockReward) external onlyGovernor {\\n tribalChiefTribePerBlock = newBlockReward;\\n emit NewTribePerBlock(newBlockReward);\\n}\\n```\\n | It is recommended to update pools before changing the block reward. Document and make users aware that the new reward is applied to the outstanding duration when calling `updatePool`. | null | ```\\nif (virtualSupply > 0) {\\n uint256 blocks = block.number - pool.lastRewardBlock;\\n uint256 tribeReward = (blocks \\* tribePerBlock() \\* pool.allocPoint) / totalAllocPoint;\\n pool.accTribePerShare = uint128(pool.accTribePerShare + ((tribeReward \\* ACC\\_TRIBE\\_PRECISION) / virtualSupply));\\n}\\n```\\n |
TribalChief - resetRewards should emit an event | low | The method `resetRewards` silently resets a pools tribe allocation.\\n```\\n/// @notice Reset the given pool's TRIBE allocation to 0 and unlock the pool. Can only be called by the governor or guardian.\\n/// @param \\_pid The index of the pool. See `poolInfo`. \\nfunction resetRewards(uint256 \\_pid) public onlyGuardianOrGovernor {\\n // set the pool's allocation points to zero\\n totalAllocPoint = (totalAllocPoint - poolInfo[\\_pid].allocPoint);\\n poolInfo[\\_pid].allocPoint = 0;\\n \\n // unlock all staked tokens in the pool\\n poolInfo[\\_pid].unlocked = true;\\n\\n // erase any IRewarder mapping\\n rewarder[\\_pid] = IRewarder(address(0));\\n}\\n```\\n | For transparency and to create an easily accessible audit trail of events consider emitting an event when resetting a pools allocation. | null | ```\\n/// @notice Reset the given pool's TRIBE allocation to 0 and unlock the pool. Can only be called by the governor or guardian.\\n/// @param \\_pid The index of the pool. See `poolInfo`. \\nfunction resetRewards(uint256 \\_pid) public onlyGuardianOrGovernor {\\n // set the pool's allocation points to zero\\n totalAllocPoint = (totalAllocPoint - poolInfo[\\_pid].allocPoint);\\n poolInfo[\\_pid].allocPoint = 0;\\n \\n // unlock all staked tokens in the pool\\n poolInfo[\\_pid].unlocked = true;\\n\\n // erase any IRewarder mapping\\n rewarder[\\_pid] = IRewarder(address(0));\\n}\\n```\\n |
TribalChief - Unlocking users' funds in a pool where a multiplier has been increased is missing | medium | When a user deposits funds to a pool, the current multiplier in use for this pool is being stored locally for this deposit. The value that is used later in a withdrawal operation is the local one, and not the one that is changing when a `governor` calls `governorAddPoolMultiplier`. It means that a decrease in the multiplier value for a given pool does not affect users that already deposited, but an increase does. Users that had already deposited should have the right to withdraw their funds when the multiplier for their pool increases by the `governor`.\\n```\\nfunction governorAddPoolMultiplier(\\n uint256 \\_pid,\\n uint64 lockLength,\\n uint64 newRewardsMultiplier\\n) external onlyGovernor {\\n PoolInfo storage pool = poolInfo[\\_pid];\\n uint256 currentMultiplier = rewardMultipliers[\\_pid][lockLength];\\n // if the new multplier is less than the current multiplier,\\n // then, you need to unlock the pool to allow users to withdraw\\n if (newRewardsMultiplier < currentMultiplier) {\\n pool.unlocked = true;\\n }\\n rewardMultipliers[\\_pid][lockLength] = newRewardsMultiplier;\\n\\n emit LogPoolMultiplier(\\_pid, lockLength, newRewardsMultiplier);\\n}\\n```\\n | Replace the `<` operator with `>` in `TribalChief` line 152. | null | ```\\nfunction governorAddPoolMultiplier(\\n uint256 \\_pid,\\n uint64 lockLength,\\n uint64 newRewardsMultiplier\\n) external onlyGovernor {\\n PoolInfo storage pool = poolInfo[\\_pid];\\n uint256 currentMultiplier = rewardMultipliers[\\_pid][lockLength];\\n // if the new multplier is less than the current multiplier,\\n // then, you need to unlock the pool to allow users to withdraw\\n if (newRewardsMultiplier < currentMultiplier) {\\n pool.unlocked = true;\\n }\\n rewardMultipliers[\\_pid][lockLength] = newRewardsMultiplier;\\n\\n emit LogPoolMultiplier(\\_pid, lockLength, newRewardsMultiplier);\\n}\\n```\\n |
TribalChief - Governor decrease of pool's allocation point should unlock depositors' funds | low | When the `TribalChief` governor decreases the ratio between the allocation point (PoolInfo.allocPoint) and the total allocation point (totalAllocPoint) for a specific pool (either be directly decreasing `PoolInfo.allocPoint` of a given pool, or by increasing this value for other pools), the total reward for this pool is decreased as well. Depositors should be able to withdraw their funds immediately after this kind of change.\\n```\\nfunction set(uint256 \\_pid, uint128 \\_allocPoint, IRewarder \\_rewarder, bool overwrite) public onlyGovernor {\\n totalAllocPoint = (totalAllocPoint - poolInfo[\\_pid].allocPoint) + \\_allocPoint;\\n poolInfo[\\_pid].allocPoint = \\_allocPoint.toUint64();\\n\\n if (overwrite) {\\n rewarder[\\_pid] = \\_rewarder;\\n }\\n\\n emit LogSetPool(\\_pid, \\_allocPoint, overwrite ? \\_rewarder : rewarder[\\_pid], overwrite);\\n}\\n```\\n | Make sure that depositors' funds are unlocked for pools that affected negatively by calling `TribalChief.set`. | null | ```\\nfunction set(uint256 \\_pid, uint128 \\_allocPoint, IRewarder \\_rewarder, bool overwrite) public onlyGovernor {\\n totalAllocPoint = (totalAllocPoint - poolInfo[\\_pid].allocPoint) + \\_allocPoint;\\n poolInfo[\\_pid].allocPoint = \\_allocPoint.toUint64();\\n\\n if (overwrite) {\\n rewarder[\\_pid] = \\_rewarder;\\n }\\n\\n emit LogSetPool(\\_pid, \\_allocPoint, overwrite ? \\_rewarder : rewarder[\\_pid], overwrite);\\n}\\n```\\n |
IdleCDO._deposit() allows re-entrancy from hookable tokens. | medium | The function `IdleCDO._deposit()` updates the system's internal accounting and mints shares to the caller, then transfers the deposited funds from the user. Some token standards, such as ERC777, allow a callback to the source of the funds before the balances are updated in `transferFrom()`. This callback could be used to re-enter the protocol while already holding the minted tranche tokens and at a point where the system accounting reflects a receipt of funds that has not yet occurred.\\nWhile an attacker could not interact with `IdleCDO.withdraw()` within this callback because of the `_checkSameTx()` restriction, they would be able to interact with the rest of the protocol.\\n```\\nfunction \\_deposit(uint256 \\_amount, address \\_tranche) internal returns (uint256 \\_minted) {\\n // check that we are not depositing more than the contract available limit\\n \\_guarded(\\_amount);\\n // set \\_lastCallerBlock hash\\n \\_updateCallerBlock();\\n // check if strategyPrice decreased\\n \\_checkDefault();\\n // interest accrued since last depositXX/withdrawXX/harvest is splitted between AA and BB\\n // according to trancheAPRSplitRatio. NAVs of AA and BB are updated and tranche\\n // prices adjusted accordingly\\n \\_updateAccounting();\\n // mint tranche tokens according to the current tranche price\\n \\_minted = \\_mintShares(\\_amount, msg.sender, \\_tranche);\\n // get underlyings from sender\\n IERC20Detailed(token).safeTransferFrom(msg.sender, address(this), \\_amount);\\n}\\n```\\n | Move the `transferFrom()` action in `_deposit()` to immediately after `_updateCallerBlock()`. | null | ```\\nfunction \\_deposit(uint256 \\_amount, address \\_tranche) internal returns (uint256 \\_minted) {\\n // check that we are not depositing more than the contract available limit\\n \\_guarded(\\_amount);\\n // set \\_lastCallerBlock hash\\n \\_updateCallerBlock();\\n // check if strategyPrice decreased\\n \\_checkDefault();\\n // interest accrued since last depositXX/withdrawXX/harvest is splitted between AA and BB\\n // according to trancheAPRSplitRatio. NAVs of AA and BB are updated and tranche\\n // prices adjusted accordingly\\n \\_updateAccounting();\\n // mint tranche tokens according to the current tranche price\\n \\_minted = \\_mintShares(\\_amount, msg.sender, \\_tranche);\\n // get underlyings from sender\\n IERC20Detailed(token).safeTransferFrom(msg.sender, address(this), \\_amount);\\n}\\n```\\n |
IdleCDO.virtualPrice() and _updatePrices() yield different prices in a number of cases | medium | The function `IdleCDO.virtualPrice()` is used to determine the current price of a tranche. Similarly, `IdleCDO._updatePrices()` is used to store the latest price of a tranche, as well as update other parts of the system accounting. There are a number of cases where the prices yielded by these two functions differ. While these are primarily corner cases that are not obviously exploitable in practice, potential violations of key accounting invariants should always be considered serious.\\nAdditionally, the use of two separate implementations of the same calculation suggest the potential for more undiscovered discrepancies, possibly of higher consequence.\\nAs an example, in `_updatePrices()` the precision loss from splitting the strategy returns favors BB tranche holders. In `virtualPrice()` both branches of the price calculation incur precision loss, favoring the `IdleCDO` contract itself.\\n`_updatePrices()`\\n```\\nif (BBTotSupply == 0) {\\n // if there are no BB holders, all gain to AA\\n AAGain = gain;\\n} else if (AATotSupply == 0) {\\n // if there are no AA holders, all gain to BB\\n BBGain = gain;\\n} else {\\n // split the gain between AA and BB holders according to trancheAPRSplitRatio\\n AAGain = gain \\* trancheAPRSplitRatio / FULL\\_ALLOC;\\n BBGain = gain - AAGain;\\n}\\n```\\n\\n`virtualPrice()`\\n```\\nif (\\_tranche == AATranche) {\\n // calculate gain for AA tranche\\n // trancheGain (AAGain) = gain \\* trancheAPRSplitRatio / FULL\\_ALLOC;\\n trancheNAV = lastNAVAA + (gain \\* \\_trancheAPRSplitRatio / FULL\\_ALLOC);\\n} else {\\n // calculate gain for BB tranche\\n // trancheGain (BBGain) = gain \\* (FULL\\_ALLOC - trancheAPRSplitRatio) / FULL\\_ALLOC;\\n trancheNAV = lastNAVBB + (gain \\* (FULL\\_ALLOC - \\_trancheAPRSplitRatio) / FULL\\_ALLOC);\\n}\\n```\\n | Implement a single method that determines the current price for a tranche, and use this same implementation anywhere the price is needed. | null | ```\\nif (BBTotSupply == 0) {\\n // if there are no BB holders, all gain to AA\\n AAGain = gain;\\n} else if (AATotSupply == 0) {\\n // if there are no AA holders, all gain to BB\\n BBGain = gain;\\n} else {\\n // split the gain between AA and BB holders according to trancheAPRSplitRatio\\n AAGain = gain \\* trancheAPRSplitRatio / FULL\\_ALLOC;\\n BBGain = gain - AAGain;\\n}\\n```\\n |
IdleCDO.harvest() allows price manipulation in certain circumstances | medium | The function `IdleCDO.harvest()` uses Uniswap to liquidate rewards earned by the contract's strategy, then updates the relevant positions and internal accounting. This function can only be called by the contract `owner` or the designated `rebalancer` address, and it accepts an array which indicates the minimum buy amounts for the liquidation of each reward token.\\nThe purpose of permissioning this method and specifying minimum buy amounts is to prevent a sandwiching attack from manipulating the reserves of the Uniswap pools and forcing the `IdleCDO` contract to incur loss due to price slippage.\\nHowever, this does not effectively prevent price manipulation in all cases. Because the contract sells it's entire balance of redeemed rewards for the specified minimum buy amount, this approach does not enforce a minimum price for the executed trades. If the balance of `IdleCDO` or the amount of claimable rewards increases between the submission of the `harvest()` transaction and its execution, it may be possible to perform a profitable sandwiching attack while still satisfying the required minimum buy amounts.\\nThe viability of this exploit depends on how effectively an attacker can increase the amount of rewards tokens to be sold without incurring an offsetting loss. The strategy contracts used by `IdleCDO` are expected to vary widely in their implementations, and this manipulation could potentially be done either through direct interaction with the protocol or as part of a flashbots bundle containing a large position adjustment from an honest user.\\n```\\nfunction harvest(bool \\_skipRedeem, bool \\_skipIncentivesUpdate, bool[] calldata \\_skipReward, uint256[] calldata \\_minAmount) external {\\n require(msg.sender == rebalancer || msg.sender == owner(), "IDLE:!AUTH");\\n```\\n\\n```\\n// approve the uniswap router to spend our reward\\nIERC20Detailed(rewardToken).safeIncreaseAllowance(address(\\_uniRouter), \\_currentBalance);\\n// do the uniswap trade\\n\\_uniRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(\\n \\_currentBalance,\\n \\_minAmount[i],\\n \\_path,\\n address(this),\\n block.timestamp + 1\\n);\\n```\\n | Update `IdleCDO.harvest()` to enforce a minimum price rather than a minimum buy amount. One method of doing so would be taking an additional array parameter indicating the amount of each token to sell in exchange for the respective buy amount. | null | ```\\nfunction harvest(bool \\_skipRedeem, bool \\_skipIncentivesUpdate, bool[] calldata \\_skipReward, uint256[] calldata \\_minAmount) external {\\n require(msg.sender == rebalancer || msg.sender == owner(), "IDLE:!AUTH");\\n```\\n |
Missing Sanity checks | low | The implementation of `initialize()` functions are missing some sanity checks. The proper checks are implemented in some of the setter functions but missing in some others.\\nMissing sanity check for `!= address(0)`\\n```\\ntoken = \\_guardedToken;\\nstrategy = \\_strategy;\\nstrategyToken = IIdleCDOStrategy(\\_strategy).strategyToken();\\nrebalancer = \\_rebalancer;\\n```\\n\\n```\\nguardian = \\_owner;\\n```\\n\\n```\\naddress \\_currAAStaking = AAStaking;\\naddress \\_currBBStaking = BBStaking;\\n```\\n\\n```\\nidleCDO = \\_idleCDO;\\ntranche = \\_trancheToken;\\nrewards = \\_rewards;\\ngovernanceRecoveryFund = \\_governanceRecoveryFund;\\n```\\n | Resolution\\nThe development team has addressed this concern in commit `a1d5dac0ad5f562d4c75bff99e770d92bcc2a72f`. This change has not been reviewed by the audit team.\\nAdd sanity checks before assigning system variables. | null | ```\\ntoken = \\_guardedToken;\\nstrategy = \\_strategy;\\nstrategyToken = IIdleCDOStrategy(\\_strategy).strategyToken();\\nrebalancer = \\_rebalancer;\\n```\\n |
Frontrunning attacks by the owner | high | There are few possible attack vectors by the owner:\\nAll strategies have fees from rewards. In addition to that, the PancakeSwap strategy has deposit fees. The default deposit fees equal zero; the maximum is limited to 5%:\\n```\\nuint256 constant MAXIMUM\\_DEPOSIT\\_FEE = 5e16; // 5%\\nuint256 constant DEFAULT\\_DEPOSIT\\_FEE = 0e16; // 0%\\n \\nuint256 constant MAXIMUM\\_PERFORMANCE\\_FEE = 50e16; // 50%\\nuint256 constant DEFAULT\\_PERFORMANCE\\_FEE = 10e16; // 10%\\n```\\n\\nWhen a user deposits tokens, expecting to have zero deposit fees, the `owner` can frontrun the deposit and increase fees to 5%. If the deposit size is big enough, that may be a significant amount of money. 2. In the `gulp` function, the reward tokens are exchanged for the reserve tokens on the exchange:\\n```\\nfunction gulp(uint256 \\_minRewardAmount) external onlyEOAorWhitelist nonReentrant\\n{\\n uint256 \\_pendingReward = \\_getPendingReward();\\n if (\\_pendingReward > 0) {\\n \\_withdraw(0);\\n }\\n {\\n uint256 \\_totalReward = Transfers.\\_getBalance(rewardToken);\\n uint256 \\_feeReward = \\_totalReward.mul(performanceFee) / 1e18;\\n Transfers.\\_pushFunds(rewardToken, collector, \\_feeReward);\\n }\\n if (rewardToken != routingToken) {\\n require(exchange != address(0), "exchange not set");\\n uint256 \\_totalReward = Transfers.\\_getBalance(rewardToken);\\n Transfers.\\_approveFunds(rewardToken, exchange, \\_totalReward);\\n IExchange(exchange).convertFundsFromInput(rewardToken, routingToken, \\_totalReward, 1);\\n }\\n if (routingToken != reserveToken) {\\n require(exchange != address(0), "exchange not set");\\n uint256 \\_totalRouting = Transfers.\\_getBalance(routingToken);\\n Transfers.\\_approveFunds(routingToken, exchange, \\_totalRouting);\\n IExchange(exchange).joinPoolFromInput(reserveToken, routingToken, \\_totalRouting, 1);\\n }\\n uint256 \\_totalBalance = Transfers.\\_getBalance(reserveToken);\\n require(\\_totalBalance >= \\_minRewardAmount, "high slippage");\\n \\_deposit(\\_totalBalance);\\n}\\n```\\n\\nThe `owner` can change the `exchange` parameter to the malicious address that steals tokens. The `owner` then calls `gulp` with `_minRewardAmount==0`, and all the rewards will be stolen. The same attack can be implemented in fee collectors and the buyback contract. | Resolution\\nThe client communicated this issue was addressed in commit 34c6b355795027d27ae6add7360e61eb6b01b91b.\\nUse a timelock to avoid instant changes of the parameters. | null | ```\\nuint256 constant MAXIMUM\\_DEPOSIT\\_FEE = 5e16; // 5%\\nuint256 constant DEFAULT\\_DEPOSIT\\_FEE = 0e16; // 0%\\n \\nuint256 constant MAXIMUM\\_PERFORMANCE\\_FEE = 50e16; // 50%\\nuint256 constant DEFAULT\\_PERFORMANCE\\_FEE = 10e16; // 10%\\n```\\n |
Expected amounts of tokens in the withdraw function | medium | Every `withdraw` function in the strategy contracts is calculating the expected amount of the returned tokens before withdrawing them:\\n```\\nfunction withdraw(uint256 \\_shares, uint256 \\_minAmount) external onlyEOAorWhitelist nonReentrant\\n{\\n address \\_from = msg.sender;\\n (uint256 \\_amount, uint256 \\_withdrawalAmount, uint256 \\_netAmount) = \\_calcAmountFromShares(\\_shares);\\n require(\\_netAmount >= \\_minAmount, "high slippage");\\n \\_burn(\\_from, \\_shares);\\n \\_withdraw(\\_amount);\\n Transfers.\\_pushFunds(reserveToken, \\_from, \\_withdrawalAmount);\\n}\\n```\\n\\nAfter that, the contract is trying to transfer this pre-calculated amount to the `msg.sender`. It is never checked whether the intended amount was actually transferred to the strategy contract. If the amount is lower, that may result in reverting the `withdraw` function all the time and locking up tokens.\\nEven though we did not find any specific case of returning a different amount of tokens, it is still a good idea to handle this situation to minimize relying on the security of the external contracts. | Resolution\\nClient's statement : “This issue did not really need fixing. The mitigation was already in place by depositing a tiny amount of the reserve into the contract, if necessary”\\nThere are a few options how to mitigate the issue:\\nDouble-check the balance difference before and after the MasterChef's `withdraw` function is called.\\nHandle this situation in the emergency mode (https://github.com/ConsenSys/growthdefi-audit-2021-06/issues/11). | null | ```\\nfunction withdraw(uint256 \\_shares, uint256 \\_minAmount) external onlyEOAorWhitelist nonReentrant\\n{\\n address \\_from = msg.sender;\\n (uint256 \\_amount, uint256 \\_withdrawalAmount, uint256 \\_netAmount) = \\_calcAmountFromShares(\\_shares);\\n require(\\_netAmount >= \\_minAmount, "high slippage");\\n \\_burn(\\_from, \\_shares);\\n \\_withdraw(\\_amount);\\n Transfers.\\_pushFunds(reserveToken, \\_from, \\_withdrawalAmount);\\n}\\n```\\n |
The capping mechanism for Panther token leads to increased fees | medium | Panther token has a cap in transfer sizes, so any transfer in the contract is limited beforehand:\\n```\\nfunction gulp(uint256 \\_minRewardAmount) external onlyEOAorWhitelist nonReentrant\\n{\\n uint256 \\_pendingReward = \\_getPendingReward();\\n if (\\_pendingReward > 0) {\\n \\_withdraw(0);\\n }\\n uint256 \\_\\_totalReward = Transfers.\\_getBalance(rewardToken);\\n (uint256 \\_feeReward, uint256 \\_retainedReward) = \\_capFeeAmount(\\_\\_totalReward.mul(performanceFee) / 1e18);\\n Transfers.\\_pushFunds(rewardToken, buyback, \\_feeReward);\\n if (rewardToken != routingToken) {\\n require(exchange != address(0), "exchange not set");\\n uint256 \\_totalReward = Transfers.\\_getBalance(rewardToken);\\n \\_totalReward = \\_capTransferAmount(rewardToken, \\_totalReward, \\_retainedReward);\\n Transfers.\\_approveFunds(rewardToken, exchange, \\_totalReward);\\n IExchange(exchange).convertFundsFromInput(rewardToken, routingToken, \\_totalReward, 1);\\n }\\n if (routingToken != reserveToken) {\\n require(exchange != address(0), "exchange not set");\\n uint256 \\_totalRouting = Transfers.\\_getBalance(routingToken);\\n \\_totalRouting = \\_capTransferAmount(routingToken, \\_totalRouting, \\_retainedReward);\\n Transfers.\\_approveFunds(routingToken, exchange, \\_totalRouting);\\n IExchange(exchange).joinPoolFromInput(reserveToken, routingToken, \\_totalRouting, 1);\\n }\\n uint256 \\_totalBalance = Transfers.\\_getBalance(reserveToken);\\n \\_totalBalance = \\_capTransferAmount(reserveToken, \\_totalBalance, \\_retainedReward);\\n require(\\_totalBalance >= \\_minRewardAmount, "high slippage");\\n \\_deposit(\\_totalBalance);\\n}\\n```\\n\\nFees here are calculated from the full amount of rewards (__totalReward ):\\n```\\n(uint256 \\_feeReward, uint256 \\_retainedReward) = \\_capFeeAmount(\\_\\_totalReward.mul(performanceFee) / 1e18);\\n```\\n\\nBut in fact, if the amount of the rewards is too big, it will be capped, and the residuals will be “taxed” again during the next call of the `gulp` function. That behavior leads to multiple taxations of the same tokens, which means increased fees. | Resolution\\nThe client communicated this issue was addressed in commit 34c6b355795027d27ae6add7360e61eb6b01b91b.\\nThe best solution would be to cap `__totalReward` first and then calculate fees from the capped value. | null | ```\\nfunction gulp(uint256 \\_minRewardAmount) external onlyEOAorWhitelist nonReentrant\\n{\\n uint256 \\_pendingReward = \\_getPendingReward();\\n if (\\_pendingReward > 0) {\\n \\_withdraw(0);\\n }\\n uint256 \\_\\_totalReward = Transfers.\\_getBalance(rewardToken);\\n (uint256 \\_feeReward, uint256 \\_retainedReward) = \\_capFeeAmount(\\_\\_totalReward.mul(performanceFee) / 1e18);\\n Transfers.\\_pushFunds(rewardToken, buyback, \\_feeReward);\\n if (rewardToken != routingToken) {\\n require(exchange != address(0), "exchange not set");\\n uint256 \\_totalReward = Transfers.\\_getBalance(rewardToken);\\n \\_totalReward = \\_capTransferAmount(rewardToken, \\_totalReward, \\_retainedReward);\\n Transfers.\\_approveFunds(rewardToken, exchange, \\_totalReward);\\n IExchange(exchange).convertFundsFromInput(rewardToken, routingToken, \\_totalReward, 1);\\n }\\n if (routingToken != reserveToken) {\\n require(exchange != address(0), "exchange not set");\\n uint256 \\_totalRouting = Transfers.\\_getBalance(routingToken);\\n \\_totalRouting = \\_capTransferAmount(routingToken, \\_totalRouting, \\_retainedReward);\\n Transfers.\\_approveFunds(routingToken, exchange, \\_totalRouting);\\n IExchange(exchange).joinPoolFromInput(reserveToken, routingToken, \\_totalRouting, 1);\\n }\\n uint256 \\_totalBalance = Transfers.\\_getBalance(reserveToken);\\n \\_totalBalance = \\_capTransferAmount(reserveToken, \\_totalBalance, \\_retainedReward);\\n require(\\_totalBalance >= \\_minRewardAmount, "high slippage");\\n \\_deposit(\\_totalBalance);\\n}\\n```\\n |
The _capFeeAmount function is not working as intended | medium | Panther token has a limit on the transfer size. Because of that, all the Panther transfer values in the `PantherSwapCompoundingStrategyToken` are also capped beforehand. The following function is called to cap the size of fees:\\n```\\nfunction \\_capFeeAmount(uint256 \\_amount) internal view returns (uint256 \\_capped, uint256 \\_retained)\\n{\\n \\_retained = 0;\\n uint256 \\_limit = \\_calcMaxRewardTransferAmount();\\n if (\\_amount > \\_limit) {\\n \\_amount = \\_limit;\\n \\_retained = \\_amount.sub(\\_limit);\\n }\\n return (\\_amount, \\_retained);\\n}\\n```\\n\\nThis function should return the capped amount and the amount of retained tokens. But because the `_amount` is changed before calculating the `_retained`, the retained amount will always be 0. | Calculate the `retained` value before changing the `amount`. | null | ```\\nfunction \\_capFeeAmount(uint256 \\_amount) internal view returns (uint256 \\_capped, uint256 \\_retained)\\n{\\n \\_retained = 0;\\n uint256 \\_limit = \\_calcMaxRewardTransferAmount();\\n if (\\_amount > \\_limit) {\\n \\_amount = \\_limit;\\n \\_retained = \\_amount.sub(\\_limit);\\n }\\n return (\\_amount, \\_retained);\\n}\\n```\\n |
Stale split ratios in UniversalBuyback | medium | The `gulp` and `pendingBurning` functions of the `UniversalBuyback` contract use the hardcoded, constant values of `DEFAULT_REWARD_BUYBACK1_SHARE` and `DEFAULT_REWARD_BUYBACK2_SHARE` to determine the ratio the trade value is split with.\\nConsequently, any call to `setRewardSplit` to set a new ratio will be ineffective but still result in a `ChangeRewardSplit` event being emitted. This event can deceive system operators and users as it does not reflect the correct values of the contract.\\n```\\nuint256 \\_amount1 = \\_balance.mul(DEFAULT\\_REWARD\\_BUYBACK1\\_SHARE) / 1e18;\\nuint256 \\_amount2 = \\_balance.mul(DEFAULT\\_REWARD\\_BUYBACK2\\_SHARE) / 1e18;\\n```\\n\\n```\\nuint256 \\_amount1 = \\_balance.mul(DEFAULT\\_REWARD\\_BUYBACK1\\_SHARE) / 1e18;\\nuint256 \\_amount2 = \\_balance.mul(DEFAULT\\_REWARD\\_BUYBACK2\\_SHARE) / 1e18;\\n```\\n | Instead of the default values, `rewardBuyback1Share` and `rewardBuyback2Share` should be used. | null | ```\\nuint256 \\_amount1 = \\_balance.mul(DEFAULT\\_REWARD\\_BUYBACK1\\_SHARE) / 1e18;\\nuint256 \\_amount2 = \\_balance.mul(DEFAULT\\_REWARD\\_BUYBACK2\\_SHARE) / 1e18;\\n```\\n |
Exchange owner might steal users' funds using reentrancy | medium | The practice of pulling funds from a user (by using safeTransferFrom) and then later pushing (some) of the funds back to the user occurs in various places in the `Exchange` contract. In case one of the used token contracts (or one of its dependent calls) externally calls the `Exchange` owner, the owner may utilize that to call back `Exchange.recoverLostFunds` and drain (some) user funds.\\n```\\nfunction convertFundsFromInput(address \\_from, address \\_to, uint256 \\_inputAmount, uint256 \\_minOutputAmount) external override returns (uint256 \\_outputAmount)\\n{\\n address \\_sender = msg.sender;\\n Transfers.\\_pullFunds(\\_from, \\_sender, \\_inputAmount);\\n \\_inputAmount = Math.\\_min(\\_inputAmount, Transfers.\\_getBalance(\\_from)); // deals with potential transfer tax\\n \\_outputAmount = UniswapV2ExchangeAbstraction.\\_convertFundsFromInput(router, \\_from, \\_to, \\_inputAmount, \\_minOutputAmount);\\n \\_outputAmount = Math.\\_min(\\_outputAmount, Transfers.\\_getBalance(\\_to)); // deals with potential transfer tax\\n Transfers.\\_pushFunds(\\_to, \\_sender, \\_outputAmount);\\n return \\_outputAmount;\\n}\\n```\\n\\n```\\nfunction joinPoolFromInput(address \\_pool, address \\_token, uint256 \\_inputAmount, uint256 \\_minOutputShares) external override returns (uint256 \\_outputShares)\\n{\\n address \\_sender = msg.sender;\\n Transfers.\\_pullFunds(\\_token, \\_sender, \\_inputAmount);\\n \\_inputAmount = Math.\\_min(\\_inputAmount, Transfers.\\_getBalance(\\_token)); // deals with potential transfer tax\\n \\_outputShares = UniswapV2LiquidityPoolAbstraction.\\_joinPoolFromInput(router, \\_pool, \\_token, \\_inputAmount, \\_minOutputShares);\\n \\_outputShares = Math.\\_min(\\_outputShares, Transfers.\\_getBalance(\\_pool)); // deals with potential transfer tax\\n Transfers.\\_pushFunds(\\_pool, \\_sender, \\_outputShares);\\n return \\_outputShares;\\n}\\n```\\n\\n```\\nfunction convertFundsFromOutput(address \\_from, address \\_to, uint256 \\_outputAmount, uint256 \\_maxInputAmount) external override returns (uint256 \\_inputAmount)\\n{\\n address \\_sender = msg.sender;\\n Transfers.\\_pullFunds(\\_from, \\_sender, \\_maxInputAmount);\\n \\_maxInputAmount = Math.\\_min(\\_maxInputAmount, Transfers.\\_getBalance(\\_from)); // deals with potential transfer tax\\n \\_inputAmount = UniswapV2ExchangeAbstraction.\\_convertFundsFromOutput(router, \\_from, \\_to, \\_outputAmount, \\_maxInputAmount);\\n uint256 \\_refundAmount = \\_maxInputAmount - \\_inputAmount;\\n \\_refundAmount = Math.\\_min(\\_refundAmount, Transfers.\\_getBalance(\\_from)); // deals with potential transfer tax\\n Transfers.\\_pushFunds(\\_from, \\_sender, \\_refundAmount);\\n \\_outputAmount = Math.\\_min(\\_outputAmount, Transfers.\\_getBalance(\\_to)); // deals with potential transfer tax\\n Transfers.\\_pushFunds(\\_to, \\_sender, \\_outputAmount);\\n return \\_inputAmount;\\n}\\n```\\n\\n```\\nfunction recoverLostFunds(address \\_token) external onlyOwner\\n{\\n uint256 \\_balance = Transfers.\\_getBalance(\\_token);\\n Transfers.\\_pushFunds(\\_token, treasury, \\_balance);\\n}\\n```\\n | Reentrancy guard protection should be added to `Exchange.convertFundsFromInput`, `Exchange.convertFundsFromOutput`, `Exchange.joinPoolFromInput`, `Exchange.recoverLostFunds` at least, and in general to all public/external functions since gas price considerations are less relevant for contracts deployed on BSC. | null | ```\\nfunction convertFundsFromInput(address \\_from, address \\_to, uint256 \\_inputAmount, uint256 \\_minOutputAmount) external override returns (uint256 \\_outputAmount)\\n{\\n address \\_sender = msg.sender;\\n Transfers.\\_pullFunds(\\_from, \\_sender, \\_inputAmount);\\n \\_inputAmount = Math.\\_min(\\_inputAmount, Transfers.\\_getBalance(\\_from)); // deals with potential transfer tax\\n \\_outputAmount = UniswapV2ExchangeAbstraction.\\_convertFundsFromInput(router, \\_from, \\_to, \\_inputAmount, \\_minOutputAmount);\\n \\_outputAmount = Math.\\_min(\\_outputAmount, Transfers.\\_getBalance(\\_to)); // deals with potential transfer tax\\n Transfers.\\_pushFunds(\\_to, \\_sender, \\_outputAmount);\\n return \\_outputAmount;\\n}\\n```\\n |
Exchange owner might steal users' funds using reentrancy | medium | The practice of pulling funds from a user (by using safeTransferFrom) and then later pushing (some) of the funds back to the user occurs in various places in the `Exchange` contract. In case one of the used token contracts (or one of its dependent calls) externally calls the `Exchange` owner, the owner may utilize that to call back `Exchange.recoverLostFunds` and drain (some) user funds.\\n```\\nfunction convertFundsFromInput(address \\_from, address \\_to, uint256 \\_inputAmount, uint256 \\_minOutputAmount) external override returns (uint256 \\_outputAmount)\\n{\\n address \\_sender = msg.sender;\\n Transfers.\\_pullFunds(\\_from, \\_sender, \\_inputAmount);\\n \\_inputAmount = Math.\\_min(\\_inputAmount, Transfers.\\_getBalance(\\_from)); // deals with potential transfer tax\\n \\_outputAmount = UniswapV2ExchangeAbstraction.\\_convertFundsFromInput(router, \\_from, \\_to, \\_inputAmount, \\_minOutputAmount);\\n \\_outputAmount = Math.\\_min(\\_outputAmount, Transfers.\\_getBalance(\\_to)); // deals with potential transfer tax\\n Transfers.\\_pushFunds(\\_to, \\_sender, \\_outputAmount);\\n return \\_outputAmount;\\n}\\n```\\n\\n```\\nfunction joinPoolFromInput(address \\_pool, address \\_token, uint256 \\_inputAmount, uint256 \\_minOutputShares) external override returns (uint256 \\_outputShares)\\n{\\n address \\_sender = msg.sender;\\n Transfers.\\_pullFunds(\\_token, \\_sender, \\_inputAmount);\\n \\_inputAmount = Math.\\_min(\\_inputAmount, Transfers.\\_getBalance(\\_token)); // deals with potential transfer tax\\n \\_outputShares = UniswapV2LiquidityPoolAbstraction.\\_joinPoolFromInput(router, \\_pool, \\_token, \\_inputAmount, \\_minOutputShares);\\n \\_outputShares = Math.\\_min(\\_outputShares, Transfers.\\_getBalance(\\_pool)); // deals with potential transfer tax\\n Transfers.\\_pushFunds(\\_pool, \\_sender, \\_outputShares);\\n return \\_outputShares;\\n}\\n```\\n\\n```\\nfunction convertFundsFromOutput(address \\_from, address \\_to, uint256 \\_outputAmount, uint256 \\_maxInputAmount) external override returns (uint256 \\_inputAmount)\\n{\\n address \\_sender = msg.sender;\\n Transfers.\\_pullFunds(\\_from, \\_sender, \\_maxInputAmount);\\n \\_maxInputAmount = Math.\\_min(\\_maxInputAmount, Transfers.\\_getBalance(\\_from)); // deals with potential transfer tax\\n \\_inputAmount = UniswapV2ExchangeAbstraction.\\_convertFundsFromOutput(router, \\_from, \\_to, \\_outputAmount, \\_maxInputAmount);\\n uint256 \\_refundAmount = \\_maxInputAmount - \\_inputAmount;\\n \\_refundAmount = Math.\\_min(\\_refundAmount, Transfers.\\_getBalance(\\_from)); // deals with potential transfer tax\\n Transfers.\\_pushFunds(\\_from, \\_sender, \\_refundAmount);\\n \\_outputAmount = Math.\\_min(\\_outputAmount, Transfers.\\_getBalance(\\_to)); // deals with potential transfer tax\\n Transfers.\\_pushFunds(\\_to, \\_sender, \\_outputAmount);\\n return \\_inputAmount;\\n}\\n```\\n\\n```\\nfunction recoverLostFunds(address \\_token) external onlyOwner\\n{\\n uint256 \\_balance = Transfers.\\_getBalance(\\_token);\\n Transfers.\\_pushFunds(\\_token, treasury, \\_balance);\\n}\\n```\\n | Reentrancy guard protection should be added to `Exchange.convertFundsFromInput`, `Exchange.convertFundsFromOutput`, `Exchange.joinPoolFromInput`, `Exchange.recoverLostFunds` at least, and in general to all public/external functions since gas price considerations are less relevant for contracts deployed on BSC. | null | ```\\nfunction convertFundsFromInput(address \\_from, address \\_to, uint256 \\_inputAmount, uint256 \\_minOutputAmount) external override returns (uint256 \\_outputAmount)\\n{\\n address \\_sender = msg.sender;\\n Transfers.\\_pullFunds(\\_from, \\_sender, \\_inputAmount);\\n \\_inputAmount = Math.\\_min(\\_inputAmount, Transfers.\\_getBalance(\\_from)); // deals with potential transfer tax\\n \\_outputAmount = UniswapV2ExchangeAbstraction.\\_convertFundsFromInput(router, \\_from, \\_to, \\_inputAmount, \\_minOutputAmount);\\n \\_outputAmount = Math.\\_min(\\_outputAmount, Transfers.\\_getBalance(\\_to)); // deals with potential transfer tax\\n Transfers.\\_pushFunds(\\_to, \\_sender, \\_outputAmount);\\n return \\_outputAmount;\\n}\\n```\\n |
Yearn: Re-entrancy attack during deposit | high | During the deposit in the `supplyTokenTo` function, the token transfer is happening after the shares are minted and before tokens are deposited to the yearn vault:\\n```\\nfunction supplyTokenTo(uint256 \\_amount, address to) override external {\\n uint256 shares = \\_tokenToShares(\\_amount);\\n\\n \\_mint(to, shares);\\n\\n // NOTE: we have to deposit after calculating shares to mint\\n token.safeTransferFrom(msg.sender, address(this), \\_amount);\\n\\n \\_depositInVault();\\n\\n emit SuppliedTokenTo(msg.sender, shares, \\_amount, to);\\n}\\n```\\n\\nIf the token allows the re-entrancy (e.g., ERC-777), the attacker can do one more transaction during the token transfer and call the `supplyTokenTo` function again. This second call will be done with already modified shares from the first deposit but non-modified token balances. That will lead to an increased amount of shares minted during the `supplyTokenTo`. By using that technique, it's possible to steal funds from other users of the contract. | Have the re-entrancy guard on all the external functions. | null | ```\\nfunction supplyTokenTo(uint256 \\_amount, address to) override external {\\n uint256 shares = \\_tokenToShares(\\_amount);\\n\\n \\_mint(to, shares);\\n\\n // NOTE: we have to deposit after calculating shares to mint\\n token.safeTransferFrom(msg.sender, address(this), \\_amount);\\n\\n \\_depositInVault();\\n\\n emit SuppliedTokenTo(msg.sender, shares, \\_amount, to);\\n}\\n```\\n |
Yearn: Partial deposits are not processed properly | high | The deposit is usually made with all the token balance of the contract:\\n```\\n// this will deposit full balance (for cases like not enough room in Vault)\\nreturn v.deposit();\\n```\\n\\nThe Yearn vault contract has a limit of how many tokens can be deposited there. If the deposit hits the limit, only part of the tokens is deposited (not to exceed the limit). That case is not handled properly, the shares are minted as if all the tokens are accepted, and the “change” is not transferred back to the caller:\\n```\\nfunction supplyTokenTo(uint256 \\_amount, address to) override external {\\n uint256 shares = \\_tokenToShares(\\_amount);\\n\\n \\_mint(to, shares);\\n\\n // NOTE: we have to deposit after calculating shares to mint\\n token.safeTransferFrom(msg.sender, address(this), \\_amount);\\n\\n \\_depositInVault();\\n\\n emit SuppliedTokenTo(msg.sender, shares, \\_amount, to);\\n}\\n```\\n | Handle the edge cases properly. | null | ```\\n// this will deposit full balance (for cases like not enough room in Vault)\\nreturn v.deposit();\\n```\\n |
Sushi: redeemToken redeems less than it should | medium | The `redeemToken` function takes as argument the amount of SUSHI to redeem. Because the SushiBar's `leave` function - which has to be called to achieve this goal - takes an amount of xSUSHI that is to be burned in exchange for SUSHI, `redeemToken` has to compute the amount of xSUSHI that will result in a return of as many SUSHI tokens as were requested.\\n```\\n/// @notice Redeems tokens from the yield source from the msg.sender, it burn yield bearing tokens and return token to the sender.\\n/// @param amount The amount of `token()` to withdraw. Denominated in `token()` as above.\\n/// @return The actual amount of tokens that were redeemed.\\nfunction redeemToken(uint256 amount) public override returns (uint256) {\\n ISushiBar bar = ISushiBar(sushiBar);\\n ISushi sushi = ISushi(sushiAddr);\\n\\n uint256 totalShares = bar.totalSupply();\\n uint256 barSushiBalance = sushi.balanceOf(address(bar));\\n uint256 requiredShares = amount.mul(totalShares).div(barSushiBalance);\\n\\n uint256 barBeforeBalance = bar.balanceOf(address(this));\\n uint256 sushiBeforeBalance = sushi.balanceOf(address(this));\\n\\n bar.leave(requiredShares);\\n\\n uint256 barAfterBalance = bar.balanceOf(address(this));\\n uint256 sushiAfterBalance = sushi.balanceOf(address(this));\\n\\n uint256 barBalanceDiff = barBeforeBalance.sub(barAfterBalance);\\n uint256 sushiBalanceDiff = sushiAfterBalance.sub(sushiBeforeBalance);\\n\\n balances[msg.sender] = balances[msg.sender].sub(barBalanceDiff);\\n sushi.transfer(msg.sender, sushiBalanceDiff);\\n return (sushiBalanceDiff);\\n}\\n```\\n\\nBecause the necessary calculations involve division and amounts have to be integral values, it is usually not possible to get the exact amount of SUSHI tokens that were requested. More precisely, let `a` denote the total supply of xSUSHI and `b` the SushiBar's balance of SUSHI at `a` certain point in time. If the SushiBar's `leave` function is supplied with `x` xSUSHI, then it will transfer floor(x * `b` / a) SUSHI. (We assume throughout this discussion that the numbers involved are small enough such that no overflow occurs and that `a` and `b` are not zero.)\\nHence, if `y` is the amount of SUSHI requested, it would make sense to call `leave` with the biggest number `x` that satisfies floor(x * b / a) <= `y` or the smallest number `x` that satisfies `floor(x * b / a) >= y`. Which of the two is “better” or “correct” needs to be specified, based on the requirements of the caller of `redeemToken`. It seems plausible, though, that the first variant is the one that makes more sense in this context, and the current implementation of `redeemToken` supports this hypothesis. It calls `leave` with `x1 := floor(y * a / b)`, which gives us floor(x1 * b / a) <= `y`. However, `x1` is not necessarily the biggest number that satisfies the relation, so the caller of `redeemToken` might end up with less SUSHI than they could have gotten while still not exceeding `y`.\\nThe correct amount to call `leave` with isx2 := floor((y * a + a - 1) / b) = max { x | floor(x * b / a) <= y }. Since `|x2 - x1| <= 1`, the difference in SUSHI is at most `floor(b / a)`. Nevertheless, even this small difference might subvert fairly reasonable expectations. For example, if someone queries `balanceOfToken` and immediately after that feeds the result into `redeemToken`, they might very well expect to redeem exactly the given amount and not less; it's their current balance, after all. However, that's not always the case with the current implementation. | Calculate `requiredShares` based on the formula above (x2). We also recommend dealing in a clean way with the special cases `totalShares == 0` and `barSushiBalance == 0`. | null | ```\\n/// @notice Redeems tokens from the yield source from the msg.sender, it burn yield bearing tokens and return token to the sender.\\n/// @param amount The amount of `token()` to withdraw. Denominated in `token()` as above.\\n/// @return The actual amount of tokens that were redeemed.\\nfunction redeemToken(uint256 amount) public override returns (uint256) {\\n ISushiBar bar = ISushiBar(sushiBar);\\n ISushi sushi = ISushi(sushiAddr);\\n\\n uint256 totalShares = bar.totalSupply();\\n uint256 barSushiBalance = sushi.balanceOf(address(bar));\\n uint256 requiredShares = amount.mul(totalShares).div(barSushiBalance);\\n\\n uint256 barBeforeBalance = bar.balanceOf(address(this));\\n uint256 sushiBeforeBalance = sushi.balanceOf(address(this));\\n\\n bar.leave(requiredShares);\\n\\n uint256 barAfterBalance = bar.balanceOf(address(this));\\n uint256 sushiAfterBalance = sushi.balanceOf(address(this));\\n\\n uint256 barBalanceDiff = barBeforeBalance.sub(barAfterBalance);\\n uint256 sushiBalanceDiff = sushiAfterBalance.sub(sushiBeforeBalance);\\n\\n balances[msg.sender] = balances[msg.sender].sub(barBalanceDiff);\\n sushi.transfer(msg.sender, sushiBalanceDiff);\\n return (sushiBalanceDiff);\\n}\\n```\\n |
Sushi: balanceOfToken underestimates balance | medium | The `balanceOfToken` computation is too pessimistic, i.e., it can underestimate the current balance slightly.\\n```\\n/// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.\\n/// @return The underlying balance of asset tokens\\nfunction balanceOfToken(address addr) public override returns (uint256) {\\n if (balances[addr] == 0) return 0;\\n ISushiBar bar = ISushiBar(sushiBar);\\n\\n uint256 shares = bar.balanceOf(address(this));\\n uint256 totalShares = bar.totalSupply();\\n\\n uint256 sushiBalance =\\n shares.mul(ISushi(sushiAddr).balanceOf(address(sushiBar))).div(\\n totalShares\\n );\\n uint256 sourceShares = bar.balanceOf(address(this));\\n\\n return (balances[addr].mul(sushiBalance).div(sourceShares));\\n}\\n```\\n\\nFirst, it calculates the amount of SUSHI that “belongs to” the yield source contract (sushiBalance), and then it determines the fraction of that amount that would be owed to the address in question. However, the “belongs to” above is a purely theoretical concept; it never happens that the yield source contract as a whole redeems and then distributes that amount among its shareholders; instead, if a shareholder redeems tokens, their request is passed through to the `SushiBar`. So in reality, there's no reason for this two-step process, and the holder's balance of SUSHI is more accurately computed as `balances[addr].mul(ISushi(sushiAddr).balanceOf(address(sushiBar))).div(totalShares)`, which can be greater than what `balanceOfToken` currently returns. Note that this is the amount of SUSHI that `addr` could withdraw directly from the `SushiBar`, based on their amount of shares. Observe also that if we sum these numbers up over all holders in the yield source contract, the result is smaller than or equal to `sushiBalance`. So the sum still doesn't exceed what “belongs to” the yield source contract. | The `balanceOfToken` function should use the formula above. | null | ```\\n/// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.\\n/// @return The underlying balance of asset tokens\\nfunction balanceOfToken(address addr) public override returns (uint256) {\\n if (balances[addr] == 0) return 0;\\n ISushiBar bar = ISushiBar(sushiBar);\\n\\n uint256 shares = bar.balanceOf(address(this));\\n uint256 totalShares = bar.totalSupply();\\n\\n uint256 sushiBalance =\\n shares.mul(ISushi(sushiAddr).balanceOf(address(sushiBar))).div(\\n totalShares\\n );\\n uint256 sourceShares = bar.balanceOf(address(this));\\n\\n return (balances[addr].mul(sushiBalance).div(sourceShares));\\n}\\n```\\n |
Yearn: Redundant approve call | low | The approval for token transfer is done in the following way:\\n```\\nif(token.allowance(address(this), address(v)) < token.balanceOf(address(this))) {\\n token.safeApprove(address(v), 0);\\n token.safeApprove(address(v), type(uint256).max);\\n}\\n```\\n\\nSince the approval will be equal to the maximum value, there's no need to make zero-value approval first. | Change two `safeApprove` to one regular `approve` with the maximum value. | null | ```\\nif(token.allowance(address(this), address(v)) < token.balanceOf(address(this))) {\\n token.safeApprove(address(v), 0);\\n token.safeApprove(address(v), type(uint256).max);\\n}\\n```\\n |
Sushi: Some state variables should be immutable and have more specific types | low | The state variables `sushiBar` and `sushiAddr` are initialized in the contract's constructor and never changed afterward.\\n```\\ncontract SushiYieldSource is IYieldSource {\\n using SafeMath for uint256;\\n address public sushiBar;\\n address public sushiAddr;\\n mapping(address => uint256) public balances;\\n\\n constructor(address \\_sushiBar, address \\_sushiAddr) public {\\n sushiBar = \\_sushiBar;\\n sushiAddr = \\_sushiAddr;\\n }\\n```\\n\\nThey should be immutable; that would save some gas and make it clear that they won't (and can't) be changed once the contract has been deployed.\\nMoreover, they would better have more specific interface types than `address`, i.e., `ISushiBar` for `sushiBar` and `ISushi` for `sushiAddr`. That would be safer and make the code more readable. | Make these two state variables `immutable` and change their types as indicated above. Remove the corresponding explicit type conversions in the rest of the contract, and add explicit conversions to type `address` where necessary. | null | ```\\ncontract SushiYieldSource is IYieldSource {\\n using SafeMath for uint256;\\n address public sushiBar;\\n address public sushiAddr;\\n mapping(address => uint256) public balances;\\n\\n constructor(address \\_sushiBar, address \\_sushiAddr) public {\\n sushiBar = \\_sushiBar;\\n sushiAddr = \\_sushiAddr;\\n }\\n```\\n |
Sushi: Unnecessary balance queries | low | In function `redeemToken`, `barBalanceDiff` is always the same as `requiredShares` because the SushiBar's `leave` function burns exactly `requiredShares` xSUSHI.\\n```\\nuint256 barBeforeBalance = bar.balanceOf(address(this));\\nuint256 sushiBeforeBalance = sushi.balanceOf(address(this));\\n\\nbar.leave(requiredShares);\\n\\nuint256 barAfterBalance = bar.balanceOf(address(this));\\nuint256 sushiAfterBalance = sushi.balanceOf(address(this));\\n\\nuint256 barBalanceDiff = barBeforeBalance.sub(barAfterBalance);\\nuint256 sushiBalanceDiff = sushiAfterBalance.sub(sushiBeforeBalance);\\n\\nbalances[msg.sender] = balances[msg.sender].sub(barBalanceDiff);\\n```\\n | Use `requiredShares` instead of `barBalanceDiff`, and remove the unnecessary queries and variables. | null | ```\\nuint256 barBeforeBalance = bar.balanceOf(address(this));\\nuint256 sushiBeforeBalance = sushi.balanceOf(address(this));\\n\\nbar.leave(requiredShares);\\n\\nuint256 barAfterBalance = bar.balanceOf(address(this));\\nuint256 sushiAfterBalance = sushi.balanceOf(address(this));\\n\\nuint256 barBalanceDiff = barBeforeBalance.sub(barAfterBalance);\\nuint256 sushiBalanceDiff = sushiAfterBalance.sub(sushiBeforeBalance);\\n\\nbalances[msg.sender] = balances[msg.sender].sub(barBalanceDiff);\\n```\\n |
Sushi: Unnecessary function declaration in interface | low | The `ISushiBar` interface declares a `transfer` function.\\n```\\ninterface ISushiBar {\\n function enter(uint256 \\_amount) external;\\n\\n function leave(uint256 \\_share) external;\\n\\n function totalSupply() external view returns (uint256);\\n\\n function balanceOf(address account) external view returns (uint256);\\n\\n function transfer(address recipient, uint256 amount)\\n external\\n returns (bool);\\n}\\n```\\n\\nHowever, this function is never used, so it could be removed from the interface. Other functions that the `SushiBar` provides but are not used (approve, for example) aren't part of the interface either. | Remove the `transfer` declaration from the `ISushiBar` interface. | null | ```\\ninterface ISushiBar {\\n function enter(uint256 \\_amount) external;\\n\\n function leave(uint256 \\_share) external;\\n\\n function totalSupply() external view returns (uint256);\\n\\n function balanceOf(address account) external view returns (uint256);\\n\\n function transfer(address recipient, uint256 amount)\\n external\\n returns (bool);\\n}\\n```\\n |
Simplify the harvest method in each SinglePlus | low | The `BadgerSBTCCrvPlus` single plus contract implements a custom `harvest` method.\\n```\\n/\\*\\*\\n \\* @dev Harvest additional yield from the investment.\\n \\* Only governance or strategist can call this function.\\n \\*/\\nfunction harvest(address[] calldata \\_tokens, uint256[] calldata \\_cumulativeAmounts, uint256 \\_index, uint256 \\_cycle,\\n```\\n\\nThis method can only be called by the strategist because of the `onlyStrategist` modifier.\\nThis method has a few steps which take one asset and transform it into another asset a few times.\\nIt first claims the Badger tokens:\\n```\\n// 1. Harvest from Badger Tree\\nIBadgerTree(BADGER\\_TREE).claim(\\_tokens, \\_cumulativeAmounts, \\_index, \\_cycle, \\_merkleProof, \\_amountsToClaim);\\n```\\n\\nThen it transforms the Badger tokens into WBTC using Uniswap.\\n```\\n// 2. Sushi: Badger --> WBTC\\nuint256 \\_badger = IERC20Upgradeable(BADGER).balanceOf(address(this));\\nif (\\_badger > 0) {\\n IERC20Upgradeable(BADGER).safeApprove(SUSHISWAP, 0);\\n IERC20Upgradeable(BADGER).safeApprove(SUSHISWAP, \\_badger);\\n\\n address[] memory \\_path = new address[](2);\\n \\_path[0] = BADGER;\\n \\_path[1] = WBTC;\\n\\n IUniswapRouter(SUSHISWAP).swapExactTokensForTokens(\\_badger, uint256(0), \\_path, address(this), block.timestamp.add(1800));\\n}\\n```\\n\\nThis step can be simplified in two ways.\\nFirst, the `safeApprove` method isn't useful because its usage is not recommended anymore.\\nThe OpenZeppelin version 4 implementation states the method is deprecated and its usage is discouraged.\\n```\\n\\* @dev Deprecated. This function has issues similar to the ones found in\\n\\* {IERC20-approve}, and its usage is discouraged.\\n```\\n\\n```\\n \\* @dev Deprecated. This function has issues similar to the ones found in\\n \\* {IERC20-approve}, and its usage is discouraged.\\n```\\n\\nAnother step is swapping the tokens on Uniswap.\\n```\\nIUniswapRouter(SUSHISWAP).swapExactTokensForTokens(\\_badger, uint256(0), \\_path, address(this), block.timestamp.add(1800));\\n```\\n\\nIn this case, the last argument `block.timestamp.add(1800)` is the deadline. This is useful when the transaction is sent to the network and a deadline is needed to expire the transaction. However, the execution is right now and there's no need for a future expiration date.\\nRemoving the safe math addition will have the same end effect, the tokens will be swapped and the call is not at risk to expire. | Resolution\\nComment from NUTS Finance team:\\nWe have replaced all safeApprove() usage with approve() and used block.timestamp as the expiration date.\\nDo not use safe math when sending the expiration date. Use `block.timestamp` for the same effect and a reduced gas cost.\\nApply the same principles for other Single Plus Tokens. | null | ```\\n/\\*\\*\\n \\* @dev Harvest additional yield from the investment.\\n \\* Only governance or strategist can call this function.\\n \\*/\\nfunction harvest(address[] calldata \\_tokens, uint256[] calldata \\_cumulativeAmounts, uint256 \\_index, uint256 \\_cycle,\\n```\\n |
Reduce complexity in modifiers related to governance and strategist | low | The modifier onlyGovernance:\\n```\\nmodifier onlyGovernance() {\\n \\_checkGovernance();\\n \\_;\\n}\\n```\\n\\nCalls the internal function _checkGovernance:\\n```\\nfunction \\_checkGovernance() internal view {\\n require(msg.sender == governance, "not governance");\\n}\\n```\\n\\nThere is no other case where the internal method `_checkGovernance` is called directly.\\nOne can reduce complexity by removing the internal function and moving its code directly in the modifier. This will increase code size but reduce gas used and code complexity.\\nThere are multiple similar instances:\\n```\\nfunction \\_checkStrategist() internal view {\\n require(msg.sender == governance || strategists[msg.sender], "not strategist");\\n}\\n\\nmodifier onlyStrategist {\\n \\_checkStrategist();\\n \\_;\\n}\\n```\\n\\n```\\nfunction \\_checkGovernance() internal view {\\n require(msg.sender == governance, "not governance");\\n}\\n\\nmodifier onlyGovernance() {\\n \\_checkGovernance();\\n \\_;\\n}\\n```\\n\\n```\\nfunction \\_checkGovernance() internal view {\\n require(msg.sender == IGaugeController(controller).governance(), "not governance");\\n}\\n\\nmodifier onlyGovernance() {\\n \\_checkGovernance();\\n \\_;\\n}\\n```\\n | Consider removing the internal function and including its body in the modifier directly if the code size is not an issue. | null | ```\\nmodifier onlyGovernance() {\\n \\_checkGovernance();\\n \\_;\\n}\\n```\\n |
zAuction - incomplete / dead code zWithdraw and zDeposit | high | The code generally does not appear to be production-ready. The methods `zWithdraw` and `zDeposit` do not appear to be properly implemented. `zWithdraw` rather burns `ETH` balance than withdrawing it for an account (missing transfer) and `zDeposit` manipulates an accounts balance but never receives the `ETH` amount it credits to an account.\\n```\\n function zDeposit(address to) external payable onlyZauction {\\n ethbalance[to] = SafeMath.add(ethbalance[to], msg.value);\\n emit zDeposited(to, msg.value);\\n }\\n\\n function zWithdraw(address from, uint256 amount) external onlyZauction {\\n ethbalance[from] = SafeMath.sub(ethbalance[from], amount);\\n emit zWithdrew(from, amount);\\n }\\n```\\n | Resolution\\nobsolete with changes from zer0-os/[email protected]135b2aa removing the `zAccountAccountant`.\\nThe methods do not seem to be used by the zAuction contract. It is highly discouraged from shipping incomplete implementations in productive code. Remove dead/unreachable code. Fix the implementations to perform proper accounting before reintroducing them if they are called by zAuction. | null | ```\\n function zDeposit(address to) external payable onlyZauction {\\n ethbalance[to] = SafeMath.add(ethbalance[to], msg.value);\\n emit zDeposited(to, msg.value);\\n }\\n\\n function zWithdraw(address from, uint256 amount) external onlyZauction {\\n ethbalance[from] = SafeMath.sub(ethbalance[from], amount);\\n emit zWithdrew(from, amount);\\n }\\n```\\n |
zAuction - Unpredictable behavior for users due to admin front running or general bad timing | high | An administrator of `zAuctionAccountant` contract can update the `zAuction` contract without warning. This has the potential to violate a security goal of the system.\\nSpecifically, privileged roles could use front running to make malicious changes just ahead of incoming transactions, or purely accidental negative effects could occur due to the unfortunate timing of changes.\\nIn general users of the system should have assurances about the behavior of the action they're about to take.\\nupdating the `zAuction` takes effect immediately. This has the potential to fail acceptance of bids by sellers on the now outdated `zAuction` contract as interaction with the accountant contract is now rejected. This forces bidders to reissue their bids in order for the seller to be able to accept them using the Accountant contract. This may also be used by admins to selectively censor the acceptance of accountant based bids by changing the active `zAuction` address.\\n```\\n function SetZauction(address zauctionaddress) external onlyAdmin{\\n zauction = zauctionaddress;\\n emit ZauctionSet(zauctionaddress);\\n }\\n\\n function SetAdmin(address newadmin) external onlyAdmin{\\n admin = newadmin;\\n emit AdminSet(msg.sender, newadmin);\\n }\\n```\\n\\nUpgradeable contracts may introduce the same unpredictability issues where the proxyUpgradeable owner may divert execution to a new zNS registrar implementation selectively for certain transactions or without prior notice to users. | The underlying issue is that users of the system can't be sure what the behavior of a function call will be, and this is because the behavior can change at any time.\\nWe recommend giving the user advance notice of changes with a time lock. For example, make all system-parameter and upgrades require two steps with a mandatory time window between them. The first step merely broadcasts to users that a particular change is coming, and the second step commits that change after a suitable waiting period. This allows users that do not accept the change to withdraw immediately.\\nValidate arguments before updating contract addresses (at least != current/0x0). Consider implementing a 2-step admin ownership transfer (transfer+accept) to avoid losing control of the contract by providing the wrong `ETH` address. | null | ```\\n function SetZauction(address zauctionaddress) external onlyAdmin{\\n zauction = zauctionaddress;\\n emit ZauctionSet(zauctionaddress);\\n }\\n\\n function SetAdmin(address newadmin) external onlyAdmin{\\n admin = newadmin;\\n emit AdminSet(msg.sender, newadmin);\\n }\\n```\\n |
zAuction, zNS - Bids cannot be cancelled, never expire, and the auction lifecycle is unclear | high | The lifecycle of a bid both for `zAuction` and `zNS` is not clear, and has many flaws.\\n`zAuction` - Consider the case where a bid is placed, then the underlying asset in being transferred to a new owner. The new owner can now force to sell the asset even though it's might not be relevant anymore.\\n`zAuction` - Once a bid was accepted and the asset was transferred, all other bids need to be invalidated automatically, otherwise and old bid might be accepted even after the formal auction is over.\\n`zAuction`, `zNS` - There is no way for the bidder to cancel an old bid. That might be useful in the event of a significant change in market trend, where the old pricing is no longer relevant. Currently, in order to cancel a bid, the bidder can either withdraw his ether balance from the `zAuctionAccountant`, or disapprove `WETH` which requires an extra transaction that might be front-runned by the seller.\\n```\\nfunction acceptBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n IERC721 nftcontract = IERC721(nftaddress);\\n accountant.Exchange(bidder, msg.sender, bid);\\n nftcontract.transferFrom(msg.sender, bidder, tokenid);\\n emit BidAccepted(bidder, msg.sender, bid, nftaddress, tokenid);\\n}\\n```\\n\\n```\\n function fulfillDomainBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n uint256 royaltyAmount,\\n string memory bidIPFSHash,\\n string memory name,\\n string memory metadata,\\n bytes memory signature,\\n bool lockOnCreation,\\n address recipient\\n) external {\\n bytes32 recoveredBidHash = createBid(parentId, bidAmount, bidIPFSHash, name);\\n address recoveredBidder = recover(recoveredBidHash, signature);\\n require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist");\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled");\\n infinity.safeTransferFrom(recoveredBidder, controller, bidAmount);\\n uint256 id = registrar.registerDomain(parentId, name, controller, recoveredBidder);\\n registrar.setDomainMetadataUri(id, metadata);\\n registrar.setDomainRoyaltyAmount(id, royaltyAmount);\\n registrar.transferFrom(controller, recoveredBidder, id);\\n if (lockOnCreation) {\\n registrar.lockDomainMetadataForOwner(id);\\n }\\n approvedBids[hashOfSig] = false;\\n emit DomainBidFulfilled(\\n metadata,\\n name,\\n recoveredBidder,\\n id,\\n parentId\\n );\\n}\\n```\\n | Consider adding an expiration field to the message signed by the bidder both for `zAuction` and `zNS`. Consider adding auction control, creating an `auctionId`, and have users bid on specific auctions. By adding this id to the signed message, all other bids are invalidated automatically and users would have to place new bids for a new auction. Optionally allow users to cancel bids explicitly.\\n | null | ```\\nfunction acceptBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n IERC721 nftcontract = IERC721(nftaddress);\\n accountant.Exchange(bidder, msg.sender, bid);\\n nftcontract.transferFrom(msg.sender, bidder, tokenid);\\n emit BidAccepted(bidder, msg.sender, bid, nftaddress, tokenid);\\n}\\n```\\n |
zAuction - pot. initialization fronrunning and unnecessary init function | medium | The `zAuction` initialization method is unprotected and while only being executable once, can be called by anyone. This might allow someone to monitor the mempool for new deployments of this contract and fron-run the initialization to initialize it with different parameters.\\nA mitigating factor is that this condition can be detected by the deployer as subsequent calls to `init()` will fail.\\nNote: this doesn't adhere to common interface naming convention/oz naming convention where this method would be called `initialize`.\\nNote: that zNS in contrast relies on ou/initializable pattern with proper naming.\\nNote: that this function might not be necessary at all and should be replaced by a constructor instead, as the contract is not used with a proxy pattern.\\n```\\nfunction init(address accountantaddress) external {\\n require(!initialized);\\n initialized = true;\\n accountant = zAuctionAccountant(accountantaddress);\\n}\\n```\\n | The contract is not used in a proxy pattern, hence, the initialization should be performed in the `constructor` instead. | null | ```\\nfunction init(address accountantaddress) external {\\n require(!initialized);\\n initialized = true;\\n accountant = zAuctionAccountant(accountantaddress);\\n}\\n```\\n |
zAuction - unclear upgrade path | medium | `zAuction` appears to implement an upgrade path for the auction system via `zAuctionAccountant`. `zAuction` itself does not hold any value. The `zAuctionAccountant` can be configured to allow only one `zAution` contract to interact with it. The update of the contract reference takes effect immediately (https://github.com/ConsenSys/zer0-zauction-audit-2021-05/issues/7).\\nAcceptance of bids via the accountant on the old contract immediately fail after an admin updates the referenced `zAuction` contract while `WETH` bids may still continue. This may create an unfavorable scenario where two contracts may be active in parallel accepting `WETH` bids.\\nIt should also be noted that 2nd layer bids (signed data) using the accountant for the old contract will not be acceptable anymore.\\n```\\nfunction SetZauction(address zauctionaddress) external onlyAdmin{\\n zauction = zauctionaddress;\\n emit ZauctionSet(zauctionaddress);\\n}\\n```\\n | Consider re-thinking the upgrade path. Avoid keeping multiple versions of the auction contact active. | null | ```\\nfunction SetZauction(address zauctionaddress) external onlyAdmin{\\n zauction = zauctionaddress;\\n emit ZauctionSet(zauctionaddress);\\n}\\n```\\n |
zAuction, zNS - gas griefing by spamming offchain fake bids Acknowledged | medium | The execution status of both `zAuction.acceptBid` and `StakingController.fulfillDomainBid` transactions depend on the bidder, as his approval is needed, his signature is being validated, etc. However, these transactions can be submitted by accounts that are different from the bidder account, or for accounts that do not have the required funds/deposits available, luring the account that has to perform the on-chain call into spending gas on a transaction that is deemed to fail (gas griefing). E.g. posting high-value fake bids for zAuction without having funds deposited or `WETH` approved.\\n```\\n function fulfillDomainBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n uint256 royaltyAmount,\\n string memory bidIPFSHash,\\n string memory name,\\n string memory metadata,\\n bytes memory signature,\\n bool lockOnCreation,\\n address recipient\\n) external {\\n bytes32 recoveredBidHash = createBid(parentId, bidAmount, bidIPFSHash, name);\\n address recoveredBidder = recover(recoveredBidHash, signature);\\n require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist");\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled");\\n infinity.safeTransferFrom(recoveredBidder, controller, bidAmount);\\n uint256 id = registrar.registerDomain(parentId, name, controller, recoveredBidder);\\n registrar.setDomainMetadataUri(id, metadata);\\n registrar.setDomainRoyaltyAmount(id, royaltyAmount);\\n registrar.transferFrom(controller, recoveredBidder, id);\\n if (lockOnCreation) {\\n registrar.lockDomainMetadataForOwner(id);\\n }\\n approvedBids[hashOfSig] = false;\\n emit DomainBidFulfilled(\\n metadata,\\n name,\\n recoveredBidder,\\n id,\\n parentId\\n );\\n}\\n```\\n\\n```\\nfunction acceptBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n IERC721 nftcontract = IERC721(nftaddress);\\n accountant.Exchange(bidder, msg.sender, bid);\\n nftcontract.transferFrom(msg.sender, bidder, tokenid);\\n emit BidAccepted(bidder, msg.sender, bid, nftaddress, tokenid);\\n}\\n```\\n | Revert early for checks that depend on the bidder before performing gas-intensive computations.\\nConsider adding a dry-run validation for off-chain components before transaction submission. | null | ```\\n function fulfillDomainBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n uint256 royaltyAmount,\\n string memory bidIPFSHash,\\n string memory name,\\n string memory metadata,\\n bytes memory signature,\\n bool lockOnCreation,\\n address recipient\\n) external {\\n bytes32 recoveredBidHash = createBid(parentId, bidAmount, bidIPFSHash, name);\\n address recoveredBidder = recover(recoveredBidHash, signature);\\n require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist");\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled");\\n infinity.safeTransferFrom(recoveredBidder, controller, bidAmount);\\n uint256 id = registrar.registerDomain(parentId, name, controller, recoveredBidder);\\n registrar.setDomainMetadataUri(id, metadata);\\n registrar.setDomainRoyaltyAmount(id, royaltyAmount);\\n registrar.transferFrom(controller, recoveredBidder, id);\\n if (lockOnCreation) {\\n registrar.lockDomainMetadataForOwner(id);\\n }\\n approvedBids[hashOfSig] = false;\\n emit DomainBidFulfilled(\\n metadata,\\n name,\\n recoveredBidder,\\n id,\\n parentId\\n );\\n}\\n```\\n |
zAuction - hardcoded ropsten token address | low | The auction contract hardcodes the WETH ERC20 token address. this address will not be functional when deploying to mainnet.\\n```\\n IERC20 weth = IERC20(address(0xc778417E063141139Fce010982780140Aa0cD5Ab)); // rinkeby weth\\n```\\n | Resolution\\nAddressed with zer0-os/[email protected]135b2aa and the following statement:\\n5.30 weth address in constructor\\nNote: does not perform input validation as recommended\\nConsider taking the used `WETH` token address as a constructor argument. Avoid code changes to facilitate testing! Perform input validation on arguments rejecting `address(0x0)` to facilitate the detection of potential misconfiguration in the deployment pipeline. | null | ```\\n IERC20 weth = IERC20(address(0xc778417E063141139Fce010982780140Aa0cD5Ab)); // rinkeby weth\\n```\\n |
zAuction - accountant allows zero value withdrawals/deposits/exchange | low | Zero value transfers effectively perform a no-operation sometimes followed by calling out to the recipient of the withdrawal.\\nA transfer where `from==to` or where the value is `0` is ineffective.\\n```\\nfunction Withdraw(uint256 amount) external {\\n ethbalance[msg.sender] = SafeMath.sub(ethbalance[msg.sender], amount);\\n payable(msg.sender).transfer(amount);\\n emit Withdrew(msg.sender, amount);\\n}\\n```\\n\\n```\\nfunction Deposit() external payable {\\n ethbalance[msg.sender] = SafeMath.add(ethbalance[msg.sender], msg.value);\\n emit Deposited(msg.sender, msg.value);\\n}\\n```\\n\\n```\\n function zDeposit(address to) external payable onlyZauction {\\n ethbalance[to] = SafeMath.add(ethbalance[to], msg.value);\\n emit zDeposited(to, msg.value);\\n }\\n\\n function zWithdraw(address from, uint256 amount) external onlyZauction {\\n ethbalance[from] = SafeMath.sub(ethbalance[from], amount);\\n emit zWithdrew(from, amount);\\n }\\n\\n function Exchange(address from, address to, uint256 amount) external onlyZauction {\\n ethbalance[from] = SafeMath.sub(ethbalance[from], amount);\\n ethbalance[to] = SafeMath.add(ethbalance[to], amount);\\n emit zExchanged(from, to, amount);\\n }\\n```\\n | Consider rejecting ineffective withdrawals (zero value) or at least avoid issuing a zero value `ETH` transfers. Avoid emitting successful events for ineffective calls to not trigger 3rd party components on noop's. | null | ```\\nfunction Withdraw(uint256 amount) external {\\n ethbalance[msg.sender] = SafeMath.sub(ethbalance[msg.sender], amount);\\n payable(msg.sender).transfer(amount);\\n emit Withdrew(msg.sender, amount);\\n}\\n```\\n |
zAuction - seller should not be able to accept their own bid | low | A seller can accept their own bid which is an ineffective action that is emitting an event.\\n```\\nfunction acceptBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n IERC721 nftcontract = IERC721(nftaddress);\\n accountant.Exchange(bidder, msg.sender, bid);\\n nftcontract.transferFrom(msg.sender, bidder, tokenid);\\n emit BidAccepted(bidder, msg.sender, bid, nftaddress, tokenid);\\n}\\n\\n/// @dev 'true' in the hash here is the eth/weth switch\\nfunction acceptWethBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid, true))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n IERC721 nftcontract = IERC721(nftaddress);\\n weth.transferFrom(bidder, msg.sender, bid);\\n nftcontract.transferFrom(msg.sender, bidder, tokenid);\\n emit WethBidAccepted(bidder, msg.sender, bid, nftaddress, tokenid);\\n}\\n```\\n | Disallow transfers to self. | null | ```\\nfunction acceptBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n IERC721 nftcontract = IERC721(nftaddress);\\n accountant.Exchange(bidder, msg.sender, bid);\\n nftcontract.transferFrom(msg.sender, bidder, tokenid);\\n emit BidAccepted(bidder, msg.sender, bid, nftaddress, tokenid);\\n}\\n\\n/// @dev 'true' in the hash here is the eth/weth switch\\nfunction acceptWethBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid, true))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n IERC721 nftcontract = IERC721(nftaddress);\\n weth.transferFrom(bidder, msg.sender, bid);\\n nftcontract.transferFrom(msg.sender, bidder, tokenid);\\n emit WethBidAccepted(bidder, msg.sender, bid, nftaddress, tokenid);\\n}\\n```\\n |
zBanc - DynamicLiquidTokenConverter ineffective reentrancy protection | high | `reduceWeight` calls `_protected()` in an attempt to protect from reentrant calls but this check is insufficient as it will only check for the `locked` statevar but never set it. A potential for direct reentrancy might be present when an erc-777 token is used as reserve.\\nIt is assumed that the developer actually wanted to use the `protected` modifier that sets the lock before continuing with the method.\\n```\\nfunction reduceWeight(IERC20Token \\_reserveToken)\\n public\\n validReserve(\\_reserveToken)\\n ownerOnly\\n{\\n \\_protected();\\n```\\n\\n```\\ncontract ReentrancyGuard {\\n // true while protected code is being executed, false otherwise\\n bool private locked = false;\\n\\n /\\*\\*\\n \\* @dev ensures instantiation only by sub-contracts\\n \\*/\\n constructor() internal {}\\n\\n // protects a function against reentrancy attacks\\n modifier protected() {\\n \\_protected();\\n locked = true;\\n \\_;\\n locked = false;\\n }\\n\\n // error message binary size optimization\\n function \\_protected() internal view {\\n require(!locked, "ERR\\_REENTRANCY");\\n }\\n}\\n```\\n | To mitigate potential attack vectors from reentrant calls remove the call to `_protected()` and decorate the function with `protected` instead. This will properly set the lock before executing the function body rejecting reentrant calls. | null | ```\\nfunction reduceWeight(IERC20Token \\_reserveToken)\\n public\\n validReserve(\\_reserveToken)\\n ownerOnly\\n{\\n \\_protected();\\n```\\n |
zBanc - DynamicLiquidTokenConverter input validation | medium | Check that the value in `PPM` is within expected bounds before updating system settings that may lead to functionality not working correctly. For example, setting out-of-bounds values for `stepWeight` or `setMinimumWeight` may make calls to `reduceWeight` fail. These values are usually set in the beginning of the lifecycle of the contract and misconfiguration may stay unnoticed until trying to reduce the weights. The settings can be fixed, however, by setting the contract inactive and updating it with valid settings. Setting the contract to inactive may temporarily interrupt the normal operation of the contract which may be unfavorable.\\nBoth functions allow the full `uint32` range to be used, which, interpreted as `PPM` would range from `0%` to `4.294,967295%`\\n```\\nfunction setMinimumWeight(uint32 \\_minimumWeight)\\n public\\n ownerOnly\\n inactive\\n{\\n //require(\\_minimumWeight > 0, "Min weight 0");\\n //\\_validReserveWeight(\\_minimumWeight);\\n minimumWeight = \\_minimumWeight;\\n emit MinimumWeightUpdated(\\_minimumWeight);\\n}\\n```\\n\\n```\\nfunction setStepWeight(uint32 \\_stepWeight)\\n public\\n ownerOnly\\n inactive\\n{\\n //require(\\_stepWeight > 0, "Step weight 0");\\n //\\_validReserveWeight(\\_stepWeight);\\n stepWeight = \\_stepWeight;\\n emit StepWeightUpdated(\\_stepWeight);\\n}\\n```\\n | Reintroduce the checks for `_validReserveWeight` to check that a percent value denoted in `PPM` is within valid bounds `_weight > 0 && _weight <= PPM_RESOLUTION`. There is no need to separately check for the value to be `>0` as this is already ensured by `_validReserveWeight`.\\nNote that there is still room for misconfiguration (step size too high, min-step too high), however, this would at least allow to catch obviously wrong and often erroneously passed parameters early. | null | ```\\nfunction setMinimumWeight(uint32 \\_minimumWeight)\\n public\\n ownerOnly\\n inactive\\n{\\n //require(\\_minimumWeight > 0, "Min weight 0");\\n //\\_validReserveWeight(\\_minimumWeight);\\n minimumWeight = \\_minimumWeight;\\n emit MinimumWeightUpdated(\\_minimumWeight);\\n}\\n```\\n |
zBanc - DynamicLiquidTokenConverter introduces breaking changes to the underlying bancorprotocol base | medium | Introducing major changes to the complex underlying smart contract system that zBanc was forked from(bancorprotocol) may result in unnecessary complexity to be added. Complexity usually increases the attack surface and potentially introduces software misbehavior. Therefore, it is recommended to focus on reducing the changes to the base system as much as possible and comply with the interfaces and processes of the system instead of introducing diverging behavior.\\nFor example, `DynamicLiquidTokenConverterFactory` does not implement the `ITypedConverterFactory` while other converters do. Furthermore, this interface and the behavior may be expected to only perform certain tasks e.g. when called during an upgrade process. Not adhering to the base systems expectations may result in parts of the system failing to function for the new convertertype. Changes introduced to accommodate the custom behavior/interfaces may result in parts of the system failing to operate with existing converters. This risk is best to be avoided.\\nIn the case of `DynamicLiquidTokenConverterFactory` the interface is imported but not implemented at all (unused import). The reason for this is likely because the function `createConverter` in `DynamicLiquidTokenConverterFactory` does not adhere to the bancor-provided interface anymore as it is doing way more than “just” creating and returning a new converter. This can create problems when trying to upgrade the converter as the upgraded expected the shared interface to be exposed unless the update mechanisms are modified as well.\\nIn general, the factories `createConverter` method appears to perform more tasks than comparable type factories. It is questionable if this is needed but may be required by the design of the system. We would, however, highly recommend to not diverge from how other converters are instantiated unless it is required to provide additional security guarantees (i.e. the token was instantiated by the factory and is therefore trusted).\\nThe `ConverterUpgrader` changed in a way that it now can only work with the `DynamicLiquidTokenconverter` instead of the more generalized `IConverter` interface. This probably breaks the update for all other converter types in the system.\\nThe severity is estimated to be medium based on the fact that the development team seems to be aware of the breaking changes but the direction of the design of the system was not yet decided.\\nunused import\\nconverterType should be external as it is not called from within the same or inherited contracts\\n```\\nfunction converterType() public pure returns (uint16) {\\n return 3;\\n}\\n```\\n\\ncreateToken can be external and is actually creating a token and converter that is using that token (the converter is not returned)(consider renaming to createTokenAndConverter)\\n```\\n{\\n DSToken token = new DSToken(\\_name, \\_symbol, \\_decimals);\\n\\n token.issue(msg.sender, \\_initialSupply);\\n\\n emit NewToken(token);\\n\\n createConverter(\\n token,\\n \\_reserveToken,\\n \\_reserveWeight,\\n \\_reserveBalance,\\n \\_registry,\\n \\_maxConversionFee,\\n \\_minimumWeight,\\n \\_stepWeight,\\n \\_marketCapThreshold\\n );\\n\\n return token;\\n}\\n```\\n\\nthe upgrade interface changed and now requires the converter to be a `DynamicLiquidTokenConverter`. Other converters may potentially fail to upgrade unless they implement the called interfaces.\\n```\\n function upgradeOld(DynamicLiquidTokenConverter \\_converter, bytes32 \\_version) public {\\n \\_version;\\n DynamicLiquidTokenConverter converter = DynamicLiquidTokenConverter(\\_converter);\\n address prevOwner = converter.owner();\\n acceptConverterOwnership(converter);\\n DynamicLiquidTokenConverter newConverter = createConverter(converter);\\n \\n copyReserves(converter, newConverter);\\n copyConversionFee(converter, newConverter);\\n transferReserveBalances(converter, newConverter);\\n IConverterAnchor anchor = converter.token();\\n \\n // get the activation status before it's being invalidated\\n bool activate = isV28OrHigherConverter(converter) && converter.isActive();\\n \\n if (anchor.owner() == address(converter)) {\\n converter.transferTokenOwnership(address(newConverter));\\n newConverter.acceptAnchorOwnership();\\n }\\n\\n handleTypeSpecificData(converter, newConverter, activate);\\n converter.transferOwnership(prevOwner);\\n \\n newConverter.transferOwnership(prevOwner);\\n \\n emit ConverterUpgrade(address(converter), address(newConverter));\\n }\\n```\\n\\n```\\nfunction upgradeOld(\\n IConverter \\_converter,\\n bytes32 /\\* \\_version \\*/\\n) public {\\n // the upgrader doesn't require the version for older converters\\n upgrade(\\_converter, 0);\\n}\\n```\\n | It is a fundamental design decision to either follow the bancorsystems converter API or diverge into a more customized system with a different design, functionality, or even security assumptions. From the current documentation, it is unclear which way the development team wants to go.\\nHowever, we highly recommend re-evaluating whether the newly introduced type and components should comply with the bancor API (recommended; avoid unnecessary changes to the underlying system,) instead of changing the API for the new components. Decide if the new factory should adhere to the usually commonly shared `ITypedConverterFactory` (recommended) and if not, remove the import and provide a new custom shared interface. It is highly recommended to comply and use the bancor systems extensibility mechanisms as intended, keeping the previously audited bancor code in-tact and voiding unnecessary re-assessments of the security impact of changes. | null | ```\\nfunction converterType() public pure returns (uint16) {\\n return 3;\\n}\\n```\\n |
zBanc - DynamicLiquidTokenConverter isActive should only be returned if converter is fully configured and converter parameters should only be updateable while converter is inactive | medium | By default, a converter is `active` once the anchor ownership was transferred. This is true for converters that do not require to be properly set up with additional parameters before they can be used.\\n```\\n/\\*\\*\\n \\* @dev returns true if the converter is active, false otherwise\\n \\*\\n \\* @return true if the converter is active, false otherwise\\n\\*/\\nfunction isActive() public view virtual override returns (bool) {\\n return anchor.owner() == address(this);\\n}\\n```\\n\\nFor a simple converter, this might be sufficient. If a converter requires additional setup steps (e.g. setting certain internal variables, an oracle, limits, etc.) it should return `inactive` until the setup completes. This is to avoid that users are interacting with (or even pot. frontrunning) a partially configured converter as this may have unexpected outcomes.\\nFor example, the `LiquidityPoolV2Converter` overrides the `isActive` method to require additional variables be set (oracle) to actually be in `active` state.\\n```\\n \\* @dev returns true if the converter is active, false otherwise\\n \\*\\n \\* @return true if the converter is active, false otherwise\\n\\*/\\nfunction isActive() public view override returns (bool) {\\n return super.isActive() && address(priceOracle) != address(0);\\n}\\n```\\n\\nAdditionally, settings can only be updated while the contract is `inactive` which will be the case during an upgrade. This ensures that the `owner` cannot adjust settings at will for an active contract.\\n```\\nfunction activate(\\n IERC20Token \\_primaryReserveToken,\\n IChainlinkPriceOracle \\_primaryReserveOracle,\\n IChainlinkPriceOracle \\_secondaryReserveOracle)\\n public\\n inactive\\n ownerOnly\\n validReserve(\\_primaryReserveToken)\\n notThis(address(\\_primaryReserveOracle))\\n notThis(address(\\_secondaryReserveOracle))\\n validAddress(address(\\_primaryReserveOracle))\\n validAddress(address(\\_secondaryReserveOracle))\\n{\\n```\\n\\nThe `DynamicLiquidTokenConverter` is following a different approach. It inherits the default `isActive` which sets the contract active right after anchor ownership is transferred. This kind of breaks the upgrade process for `DynamicLiquidTokenConverter` as settings cannot be updated while the contract is active (as anchor ownership might be transferred before updating values). To unbreak this behavior a new authentication modifier was added, that allows updates for the upgrade contradict while the contract is active. Now this is a behavior that should be avoided as settings should be predictable while a contract is active. Instead it would make more sense initially set all the custom settings of the converter to zero (uninitialized) and require them to be set and only the return the contract as active. The behavior basically mirrors the upgrade process of `LiquidityPoolV2Converter`.\\n```\\n modifier ifActiveOnlyUpgrader(){\\n if(isActive()){\\n require(owner == addressOf(CONVERTER\\_UPGRADER), "ERR\\_ACTIVE\\_NOTUPGRADER");\\n }\\n \\_;\\n }\\n```\\n\\nPre initialized variables should be avoided. The marketcap threshold can only be set by the calling entity as it may be very different depending on the type of reserve (eth, token).\\n```\\nuint32 public minimumWeight = 30000;\\nuint32 public stepWeight = 10000;\\nuint256 public marketCapThreshold = 10000 ether;\\nuint256 public lastWeightAdjustmentMarketCap = 0;\\n```\\n\\nHere's one of the setter functions that can be called while the contract is active (only by the upgrader contract but changing the ACL commonly followed with other converters).\\n```\\nfunction setMarketCapThreshold(uint256 \\_marketCapThreshold)\\n public\\n ownerOnly\\n ifActiveOnlyUpgrader\\n{\\n marketCapThreshold = \\_marketCapThreshold;\\n emit MarketCapThresholdUpdated(\\_marketCapThreshold);\\n}\\n```\\n | Align the upgrade process as much as possible to how `LiquidityPoolV2Converter` performs it. Comply with the bancor API.\\noverride `isActive` and require the contracts main variables to be set.\\ndo not pre initialize the contracts settings to “some” values. Require them to be set by the caller (and perform input validation)\\nmirror the upgrade process of `LiquidityPoolV2Converter` and instead of `activate` call the setter functions that set the variables. After setting the last var and anchor ownership been transferred, the contract should return active. | null | ```\\n/\\*\\*\\n \\* @dev returns true if the converter is active, false otherwise\\n \\*\\n \\* @return true if the converter is active, false otherwise\\n\\*/\\nfunction isActive() public view virtual override returns (bool) {\\n return anchor.owner() == address(this);\\n}\\n```\\n |
zBanc - inconsistent DynamicContractRegistry, admin risks | medium | `DynamicContractRegistry` is a wrapper registry that allows the zBanc to use the custom upgrader contract while still providing access to the normal bancor registry.\\nFor this to work, the registry owner can add or override any registry setting. Settings that don't exist in this contract are attempted to be retrieved from an underlying registry (contractRegistry).\\n```\\nfunction registerAddress(bytes32 \\_contractName, address \\_contractAddress)\\n public\\n ownerOnly\\n validAddress(\\_contractAddress)\\n{\\n```\\n\\nIf the item does not exist in the registry, the request is forwarded to the underlying registry.\\n```\\nfunction addressOf(bytes32 \\_contractName) public view override returns (address) {\\n if(items[\\_contractName].contractAddress != address(0)){\\n return items[\\_contractName].contractAddress;\\n }else{\\n return contractRegistry.addressOf(\\_contractName);\\n }\\n}\\n```\\n\\nAccording to the documentation this registry is owned by zer0 admins and this means users have to trust zer0 admins to play fair.\\nTo handle this, we deploy our own ConverterUpgrader and ContractRegistry owned by zer0 admins who can register new addresses\\nThe owner of the registry (zer0 admins) can change the underlying registry contract at will. The owner can also add new or override any settings that already exist in the underlying registry. This may for example allow a malicious owner to change the upgrader contract in an attempt to potentially steal funds from a token converter or upgrade to a new malicious contract. The owner can also front-run registry calls changing registry settings and thus influencing the outcome. Such an event will not go unnoticed as events are emitted.\\nIt should also be noted that `itemCount` will return only the number of items in the wrapper registry but not the number of items in the underlying registry. This may have an unpredictable effect on components consuming this information.\\n```\\n/\\*\\*\\n \\* @dev returns the number of items in the registry\\n \\*\\n \\* @return number of items\\n\\*/\\nfunction itemCount() public view returns (uint256) {\\n return contractNames.length;\\n}\\n```\\n | Resolution\\nThe client acknowledged the admin risk and addressed the `itemCount` concerns by exposing another method that only returns the overridden entries. The following statement was provided:\\n5.10 - keeping this pattern which matches the bancor pattern, and noting the DCR should be owned by a DAO, which is our plan. solved itemCount issue - Added dcrItemCount and made itemCount call the bancor registry's itemCount, so unpredictable behavior due to the count should be eliminated.\\nRequire the owner/zer0 admins to be a DAO or multisig and enforce 2-step (notify->wait->upgrade) registry updates (e.g. by requiring voting or timelocks in the admin contract). Provide transparency about who is the owner of the registry as this may not be clear for everyone. Evaluate the impact of `itemCount` only returning the number of settings in the wrapper not taking into account entries in the subcontract (including pot. overlaps). | null | ```\\nfunction registerAddress(bytes32 \\_contractName, address \\_contractAddress)\\n public\\n ownerOnly\\n validAddress(\\_contractAddress)\\n{\\n```\\n |
zBanc - DynamicLiquidTokenConverter consider using PPM_RESOLUTION instead of hardcoding integer literals | low | `getMarketCap` calculates the reserve's market capitalization as `reserveBalance * `1e6` / weight` where `1e6` should be expressed as the constant `PPM_RESOLUTION`.\\n```\\nfunction getMarketCap(IERC20Token \\_reserveToken)\\n public\\n view\\n returns(uint256)\\n{\\n Reserve storage reserve = reserves[\\_reserveToken];\\n return reserveBalance(\\_reserveToken).mul(1e6).div(reserve.weight);\\n}\\n```\\n | Avoid hardcoding integer literals directly into source code when there is a better expression available. In this case `1e6` is used because weights are denoted in percent to base `PPM_RESOLUTION` (=100%). | null | ```\\nfunction getMarketCap(IERC20Token \\_reserveToken)\\n public\\n view\\n returns(uint256)\\n{\\n Reserve storage reserve = reserves[\\_reserveToken];\\n return reserveBalance(\\_reserveToken).mul(1e6).div(reserve.weight);\\n}\\n```\\n |
zBanc - DynamicLiquidTokenConverter avoid potential converter type overlap with bancor Acknowledged | low | The system is forked frombancorprotocol/contracts-solidity. As such, it is very likely that security vulnerabilities reported to bancorprotocol upstream need to be merged into the zer0/zBanc fork if they also affect this codebase. There is also a chance that security fixes will only be available with feature releases or that the zer0 development team wants to merge upstream features into the zBanc codebase.\\nzBanc introduced `converterType=3` for the `DynamicLiquidTokenConverter` as `converterType=1` and `converterType=2` already exist in the bancorprotocol codebase. Now, since it is unclear if `DynamicLiquidTokenConverter` will be merged into bancorprotocol there is a chance that bancor introduces new types that overlap with the `DynamicLiquidTokenConverter` converter type (3). It is therefore suggested to map the `DynamicLiquidTokenConverter` to a converterType that is unlikely to create an overlap with the system it was forked from. E.g. use converter type id `1001` instead of `3` (Note: converterType is an uint16).\\nNote that the current master of the bancorprotocol already appears to defined converterType 3 and 4: https://github.com/bancorprotocol/contracts-solidity/blob/5f4c53ebda784751c3a90b06aa2c85e9fdb36295/solidity/test/helpers/Converter.js#L51-L54\\nThe new custom converter\\n```\\nfunction converterType() public pure override returns (uint16) {\\n return 3;\\n}\\n```\\n\\nConverterTypes from the bancor base system\\n```\\nfunction converterType() public pure override returns (uint16) {\\n return 1;\\n}\\n```\\n\\n```\\n\\*/\\nfunction converterType() public pure override returns (uint16) {\\n return 2;\\n}\\n```\\n | Choose a converterType id for this custom implementation that does not overlap with the codebase the system was forked from. e.g. `uint16(-1)` or `1001` instead of `3` which might already be used upstream. | null | ```\\nfunction converterType() public pure override returns (uint16) {\\n return 3;\\n}\\n```\\n |
zDAO Token - Specification violation - Snapshots are never taken Partially Addressed | high | Resolution\\nAddressed with zer0-os/[email protected]81946d4 by exposing the `_snapshot()` method to a dedicated snapshot role (likely to be a DAO) and the owner of the contract.\\nWe would like to note that we informed the client that depending on how the snapshot method is used and how predictably snapshots are consumed this might open up a frontrunning vector where someone observing that a `_snapshot()` is about to be taken might sandwich the snapshot call, accumulate a lot of stake (via 2nd markets, lending platforms), and returning it right after it's been taken. The risk of losing funds may be rather low (especially if performed by a miner) and the benefit from a DAO proposal using this snapshot might outweigh it. It is still recommended to increase the number of snapshots taken or take them on a regular basis (e.g. with every first transaction to the contract in a block) to make it harder to sandwich the snapshot taking.\\nAccording to the zDAO Token specification the DAO token should implement a snapshot functionality to allow it being used for DAO governance votings.\\nAny transfer, mint, or burn operation should result in a snapshot of the token balances of involved users being taken.\\nWhile the corresponding functionality is implemented and appears to update balances for snapshots, `_snapshot()` is never called, therefore, the snapshot is never taken. e.g. attempting to call `balanceOfAt` always results in an error as no snapshot is available.\\n```\\ncontract ZeroDAOToken is\\n OwnableUpgradeable,\\n ERC20Upgradeable,\\n ERC20PausableUpgradeable,\\n ERC20SnapshotUpgradeable\\n{\\n```\\n\\n```\\n\\_updateAccountSnapshot(sender);\\n```\\n\\nNote that this is an explicit requirement as per specification but unit tests do not seem to attempt calls to `balanceOfAt` at all. | Actually, take a snapshot by calling `_snapshot()` once per block when executing the first transaction in a new block. Follow the openzeppeling documentation for ERC20Snapshot. | null | ```\\ncontract ZeroDAOToken is\\n OwnableUpgradeable,\\n ERC20Upgradeable,\\n ERC20PausableUpgradeable,\\n ERC20SnapshotUpgradeable\\n{\\n```\\n |
zDAO-Token - Revoking vesting tokens right before cliff period expiration might be delayed/front-runned | low | The owner of `TokenVesting` contract has the right to revoke the vesting of tokens for any `beneficiary`. By doing so, the amount of tokens that are already vested and weren't released yet are being transferred to the `beneficiary`, and the rest are being transferred to the owner. The `beneficiary` is expected to receive zero tokens in case the revocation transaction was executed before the cliff period is over. Although unlikely, the `beneficiary` may front run this revocation transaction by delaying the revocation (and) or inserting a release transaction right before that, thus withdrawing the vested amount.\\n```\\nfunction release(address beneficiary) public {\\n uint256 unreleased = getReleasableAmount(beneficiary);\\n require(unreleased > 0, "Nothing to release");\\n\\n TokenAward storage award = getTokenAwardStorage(beneficiary);\\n award.released += unreleased;\\n\\n targetToken.safeTransfer(beneficiary, unreleased);\\n\\n emit Released(beneficiary, unreleased);\\n}\\n\\n/\\*\\*\\n \\* @notice Allows the owner to revoke the vesting. Tokens already vested\\n \\* are transfered to the beneficiary, the rest are returned to the owner.\\n \\* @param beneficiary Who the tokens are being released to\\n \\*/\\nfunction revoke(address beneficiary) public onlyOwner {\\n TokenAward storage award = getTokenAwardStorage(beneficiary);\\n\\n require(award.revocable, "Cannot be revoked");\\n require(!award.revoked, "Already revoked");\\n\\n // Figure out how many tokens were owed up until revocation\\n uint256 unreleased = getReleasableAmount(beneficiary);\\n award.released += unreleased;\\n\\n uint256 refund = award.amount - award.released;\\n\\n // Mark award as revoked\\n award.revoked = true;\\n award.amount = award.released;\\n\\n // Transfer owed vested tokens to beneficiary\\n targetToken.safeTransfer(beneficiary, unreleased);\\n // Transfer unvested tokens to owner (revoked amount)\\n targetToken.safeTransfer(owner(), refund);\\n\\n emit Released(beneficiary, unreleased);\\n emit Revoked(beneficiary, refund);\\n}\\n```\\n | The issue described above is possible, but very unlikely. However, the `TokenVesting` owner should be aware of that, and make sure not to revoke vested tokens closely to cliff period ending. | null | ```\\nfunction release(address beneficiary) public {\\n uint256 unreleased = getReleasableAmount(beneficiary);\\n require(unreleased > 0, "Nothing to release");\\n\\n TokenAward storage award = getTokenAwardStorage(beneficiary);\\n award.released += unreleased;\\n\\n targetToken.safeTransfer(beneficiary, unreleased);\\n\\n emit Released(beneficiary, unreleased);\\n}\\n\\n/\\*\\*\\n \\* @notice Allows the owner to revoke the vesting. Tokens already vested\\n \\* are transfered to the beneficiary, the rest are returned to the owner.\\n \\* @param beneficiary Who the tokens are being released to\\n \\*/\\nfunction revoke(address beneficiary) public onlyOwner {\\n TokenAward storage award = getTokenAwardStorage(beneficiary);\\n\\n require(award.revocable, "Cannot be revoked");\\n require(!award.revoked, "Already revoked");\\n\\n // Figure out how many tokens were owed up until revocation\\n uint256 unreleased = getReleasableAmount(beneficiary);\\n award.released += unreleased;\\n\\n uint256 refund = award.amount - award.released;\\n\\n // Mark award as revoked\\n award.revoked = true;\\n award.amount = award.released;\\n\\n // Transfer owed vested tokens to beneficiary\\n targetToken.safeTransfer(beneficiary, unreleased);\\n // Transfer unvested tokens to owner (revoked amount)\\n targetToken.safeTransfer(owner(), refund);\\n\\n emit Released(beneficiary, unreleased);\\n emit Revoked(beneficiary, refund);\\n}\\n```\\n |
zDAO-Token - Vested tokens revocation depends on claiming state | low | The owner of the `TokenVesting` contract can revoke the vesting of tokens for any beneficiary by calling `TokenVesting.revoke` only for tokens that have already been claimed using `MerkleTokenVesting.claimAward`. Although anyone can call `MerkleTokenVesting.claimAward` for a given beneficiary, in practice it is mostly the beneficiary's responsibility. This design decision, however, incentivizes the beneficiary to delay the call to `MerkleTokenVesting.claimAward` up to the point when he wishes to cash out, to avoid potential revocation. To revoke vesting tokens the owner will have to claim the award on the beneficiary's behalf first (which might be a gas burden), then call `TokenVesting.revoke`.\\n```\\nfunction revoke(address beneficiary) public onlyOwner {\\n TokenAward storage award = getTokenAwardStorage(beneficiary);\\n\\n require(award.revocable, "Cannot be revoked");\\n require(!award.revoked, "Already revoked");\\n\\n // Figure out how many tokens were owed up until revocation\\n uint256 unreleased = getReleasableAmount(beneficiary);\\n award.released += unreleased;\\n\\n uint256 refund = award.amount - award.released;\\n\\n // Mark award as revoked\\n award.revoked = true;\\n award.amount = award.released;\\n\\n // Transfer owed vested tokens to beneficiary\\n targetToken.safeTransfer(beneficiary, unreleased);\\n // Transfer unvested tokens to owner (revoked amount)\\n targetToken.safeTransfer(owner(), refund);\\n\\n emit Released(beneficiary, unreleased);\\n emit Revoked(beneficiary, refund);\\n}\\n```\\n | Make sure that the potential owner of a `TokenVesting` contract is aware of this potential issue, and has the required processes in place to handle it. | null | ```\\nfunction revoke(address beneficiary) public onlyOwner {\\n TokenAward storage award = getTokenAwardStorage(beneficiary);\\n\\n require(award.revocable, "Cannot be revoked");\\n require(!award.revoked, "Already revoked");\\n\\n // Figure out how many tokens were owed up until revocation\\n uint256 unreleased = getReleasableAmount(beneficiary);\\n award.released += unreleased;\\n\\n uint256 refund = award.amount - award.released;\\n\\n // Mark award as revoked\\n award.revoked = true;\\n award.amount = award.released;\\n\\n // Transfer owed vested tokens to beneficiary\\n targetToken.safeTransfer(beneficiary, unreleased);\\n // Transfer unvested tokens to owner (revoked amount)\\n targetToken.safeTransfer(owner(), refund);\\n\\n emit Released(beneficiary, unreleased);\\n emit Revoked(beneficiary, refund);\\n}\\n```\\n |
zNS - Domain bid might be approved by non owner account | high | The spec allows anyone to place a bid for a domain, while only parent domain owners are allowed to approve a bid. Bid placement is actually enforced and purely informational. In practice, `approveDomainBid` allows any parent domain owner to approve bids (signatures) for any other domain even if they do not own it. Once approved, anyone can call `fulfillDomainBid` to create a domain.\\n```\\nfunction approveDomainBid(\\n uint256 parentId,\\n string memory bidIPFSHash,\\n bytes memory signature\\n) external authorizedOwner(parentId) {\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n approvedBids[hashOfSig] = true;\\n emit DomainBidApproved(bidIPFSHash);\\n}\\n```\\n | Resolution\\nAddressed with zer0-os/[email protected] by storing the domain request data on-chain.\\nConsider adding a validation check that allows only the parent domain owner to approve bids on one of its domains. Reconsider the design of the system introducing more on-chain guarantees for bids. | null | ```\\nfunction approveDomainBid(\\n uint256 parentId,\\n string memory bidIPFSHash,\\n bytes memory signature\\n) external authorizedOwner(parentId) {\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n approvedBids[hashOfSig] = true;\\n emit DomainBidApproved(bidIPFSHash);\\n}\\n```\\n |
zAuction, zNS - Bids cannot be cancelled, never expire, and the auction lifecycle is unclear | high | The lifecycle of a bid both for `zAuction` and `zNS` is not clear, and has many flaws.\\n`zAuction` - Consider the case where a bid is placed, then the underlying asset in being transferred to a new owner. The new owner can now force to sell the asset even though it's might not be relevant anymore.\\n`zAuction` - Once a bid was accepted and the asset was transferred, all other bids need to be invalidated automatically, otherwise and old bid might be accepted even after the formal auction is over.\\n`zAuction`, `zNS` - There is no way for the bidder to cancel an old bid. That might be useful in the event of a significant change in market trend, where the old pricing is no longer relevant. Currently, in order to cancel a bid, the bidder can either withdraw his ether balance from the `zAuctionAccountant`, or disapprove `WETH` which requires an extra transaction that might be front-runned by the seller.\\n```\\nfunction acceptBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n IERC721 nftcontract = IERC721(nftaddress);\\n accountant.Exchange(bidder, msg.sender, bid);\\n nftcontract.transferFrom(msg.sender, bidder, tokenid);\\n emit BidAccepted(bidder, msg.sender, bid, nftaddress, tokenid);\\n}\\n```\\n\\n```\\n function fulfillDomainBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n uint256 royaltyAmount,\\n string memory bidIPFSHash,\\n string memory name,\\n string memory metadata,\\n bytes memory signature,\\n bool lockOnCreation,\\n address recipient\\n) external {\\n bytes32 recoveredBidHash = createBid(parentId, bidAmount, bidIPFSHash, name);\\n address recoveredBidder = recover(recoveredBidHash, signature);\\n require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist");\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled");\\n infinity.safeTransferFrom(recoveredBidder, controller, bidAmount);\\n uint256 id = registrar.registerDomain(parentId, name, controller, recoveredBidder);\\n registrar.setDomainMetadataUri(id, metadata);\\n registrar.setDomainRoyaltyAmount(id, royaltyAmount);\\n registrar.transferFrom(controller, recoveredBidder, id);\\n if (lockOnCreation) {\\n registrar.lockDomainMetadataForOwner(id);\\n }\\n approvedBids[hashOfSig] = false;\\n emit DomainBidFulfilled(\\n metadata,\\n name,\\n recoveredBidder,\\n id,\\n parentId\\n );\\n}\\n```\\n | Consider adding an expiration field to the message signed by the bidder both for `zAuction` and `zNS`. Consider adding auction control, creating an `auctionId`, and have users bid on specific auctions. By adding this id to the signed message, all other bids are invalidated automatically and users would have to place new bids for a new auction. Optionally allow users to cancel bids explicitly.\\n | null | ```\\nfunction acceptBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n IERC721 nftcontract = IERC721(nftaddress);\\n accountant.Exchange(bidder, msg.sender, bid);\\n nftcontract.transferFrom(msg.sender, bidder, tokenid);\\n emit BidAccepted(bidder, msg.sender, bid, nftaddress, tokenid);\\n}\\n```\\n |
zNS - Insufficient protection against replay attacks | high | There is no dedicated data structure to prevent replay attacks on `StakingController`. `approvedBids` mapping offers only partial mitigation, due to the fact that after a domain bid is fulfilled, the only mechanism in place to prevent a replay attack is the `Registrar` contract that might be replaced in the case where `StakingController` is being re-deployed with a different `Registrar` instance. Additionally, the digital signature used for domain bids does not identify the buyer request uniquely enough. The bidder's signature could be replayed in future similar contracts that are deployed with a different registrar or in a different network.\\n```\\nfunction createBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n string memory bidIPFSHash,\\n string memory name\\n) public pure returns(bytes32) {\\n return keccak256(abi.encode(parentId, bidAmount, bidIPFSHash, name));\\n}\\n```\\n | Consider adding a dedicated mapping to store the a unique identifier of a bid, as well as adding `address(this)`, `block.chainId`, `registrar` and `nonce` to the message that is being signed by the bidder. | null | ```\\nfunction createBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n string memory bidIPFSHash,\\n string memory name\\n) public pure returns(bytes32) {\\n return keccak256(abi.encode(parentId, bidAmount, bidIPFSHash, name));\\n}\\n```\\n |
zNS - domain name collisions | high | Domain registration accepts an empty (zero-length) name. This may allow a malicious entity to register two different NFT's for the same visually indinstinguishable text representation of a domain. Similar to this the domain name is mapped to an NFT via a subgraph that connects parent names to the new subdomain using a domain separation character (dot/slash/…). Someone might be able to register `a.b` to `cats.cool` which might resolve to the same domain as if someone registers `cats.cool.a` and then `cats.cool.a.b`.\\n`0/cats/` = `0xfe`\\n`0/cats/<empty-string/` = `0xfe.keccak("")`\\n```\\nfunction registerDomain(\\n uint256 parentId,\\n string memory name,\\n address domainOwner,\\n address minter\\n) external override onlyController returns (uint256) {\\n // Create the child domain under the parent domain\\n uint256 labelHash = uint256(keccak256(bytes(name)));\\n address controller = msg.sender;\\n\\n // Domain parents must exist\\n require(\\_exists(parentId), "Zer0 Registrar: No parent");\\n\\n // Calculate the new domain's id and create it\\n uint256 domainId =\\n uint256(keccak256(abi.encodePacked(parentId, labelHash)));\\n \\_createDomain(domainId, domainOwner, minter, controller);\\n\\n emit DomainCreated(domainId, name, labelHash, parentId, minter, controller);\\n\\n return domainId;\\n```\\n | Disallow empty subdomain names. Disallow domain separators in names (in the offchain component or smart contract). | null | ```\\nfunction registerDomain(\\n uint256 parentId,\\n string memory name,\\n address domainOwner,\\n address minter\\n) external override onlyController returns (uint256) {\\n // Create the child domain under the parent domain\\n uint256 labelHash = uint256(keccak256(bytes(name)));\\n address controller = msg.sender;\\n\\n // Domain parents must exist\\n require(\\_exists(parentId), "Zer0 Registrar: No parent");\\n\\n // Calculate the new domain's id and create it\\n uint256 domainId =\\n uint256(keccak256(abi.encodePacked(parentId, labelHash)));\\n \\_createDomain(domainId, domainOwner, minter, controller);\\n\\n emit DomainCreated(domainId, name, labelHash, parentId, minter, controller);\\n\\n return domainId;\\n```\\n |
zAuction, zNS - gas griefing by spamming offchain fake bids Acknowledged | medium | The execution status of both `zAuction.acceptBid` and `StakingController.fulfillDomainBid` transactions depend on the bidder, as his approval is needed, his signature is being validated, etc. However, these transactions can be submitted by accounts that are different from the bidder account, or for accounts that do not have the required funds/deposits available, luring the account that has to perform the on-chain call into spending gas on a transaction that is deemed to fail (gas griefing). E.g. posting high-value fake bids for zAuction without having funds deposited or `WETH` approved.\\n```\\n function fulfillDomainBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n uint256 royaltyAmount,\\n string memory bidIPFSHash,\\n string memory name,\\n string memory metadata,\\n bytes memory signature,\\n bool lockOnCreation,\\n address recipient\\n) external {\\n bytes32 recoveredBidHash = createBid(parentId, bidAmount, bidIPFSHash, name);\\n address recoveredBidder = recover(recoveredBidHash, signature);\\n require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist");\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled");\\n infinity.safeTransferFrom(recoveredBidder, controller, bidAmount);\\n uint256 id = registrar.registerDomain(parentId, name, controller, recoveredBidder);\\n registrar.setDomainMetadataUri(id, metadata);\\n registrar.setDomainRoyaltyAmount(id, royaltyAmount);\\n registrar.transferFrom(controller, recoveredBidder, id);\\n if (lockOnCreation) {\\n registrar.lockDomainMetadataForOwner(id);\\n }\\n approvedBids[hashOfSig] = false;\\n emit DomainBidFulfilled(\\n metadata,\\n name,\\n recoveredBidder,\\n id,\\n parentId\\n );\\n}\\n```\\n\\n```\\nfunction acceptBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n IERC721 nftcontract = IERC721(nftaddress);\\n accountant.Exchange(bidder, msg.sender, bid);\\n nftcontract.transferFrom(msg.sender, bidder, tokenid);\\n emit BidAccepted(bidder, msg.sender, bid, nftaddress, tokenid);\\n}\\n```\\n | Revert early for checks that depend on the bidder before performing gas-intensive computations.\\nConsider adding a dry-run validation for off-chain components before transaction submission. | null | ```\\n function fulfillDomainBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n uint256 royaltyAmount,\\n string memory bidIPFSHash,\\n string memory name,\\n string memory metadata,\\n bytes memory signature,\\n bool lockOnCreation,\\n address recipient\\n) external {\\n bytes32 recoveredBidHash = createBid(parentId, bidAmount, bidIPFSHash, name);\\n address recoveredBidder = recover(recoveredBidHash, signature);\\n require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist");\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled");\\n infinity.safeTransferFrom(recoveredBidder, controller, bidAmount);\\n uint256 id = registrar.registerDomain(parentId, name, controller, recoveredBidder);\\n registrar.setDomainMetadataUri(id, metadata);\\n registrar.setDomainRoyaltyAmount(id, royaltyAmount);\\n registrar.transferFrom(controller, recoveredBidder, id);\\n if (lockOnCreation) {\\n registrar.lockDomainMetadataForOwner(id);\\n }\\n approvedBids[hashOfSig] = false;\\n emit DomainBidFulfilled(\\n metadata,\\n name,\\n recoveredBidder,\\n id,\\n parentId\\n );\\n}\\n```\\n |
zNS - anyone can front-run fulfillDomainBid to lock the domain setting or set different metadata | medium | Anyone observing a call to `fulfillDomainBid` can front-run this call for the original bidder, provide different metadata/royalty amount, or lock the metadata, as these parameters are not part of the bidder's signature. The impact is limited as both metadata, royalty amount, and lock state can be changed by the domain owner after creation.\\n```\\n function fulfillDomainBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n uint256 royaltyAmount,\\n string memory bidIPFSHash,\\n string memory name,\\n string memory metadata,\\n bytes memory signature,\\n bool lockOnCreation,\\n address recipient\\n) external {\\n bytes32 recoveredBidHash = createBid(parentId, bidAmount, bidIPFSHash, name);\\n address recoveredBidder = recover(recoveredBidHash, signature);\\n require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist");\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled");\\n infinity.safeTransferFrom(recoveredBidder, controller, bidAmount);\\n uint256 id = registrar.registerDomain(parentId, name, controller, recoveredBidder);\\n registrar.setDomainMetadataUri(id, metadata);\\n registrar.setDomainRoyaltyAmount(id, royaltyAmount);\\n registrar.transferFrom(controller, recoveredBidder, id);\\n if (lockOnCreation) {\\n registrar.lockDomainMetadataForOwner(id);\\n }\\n```\\n | Consider adding `metadata`, `royaltyAmount`, and `lockOnCreation` to the message signed by the bidder if the parent should have some control over `metadata` and lockstatus and restrict access to this function to `msg.sender==recoveredbidder`. | null | ```\\n function fulfillDomainBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n uint256 royaltyAmount,\\n string memory bidIPFSHash,\\n string memory name,\\n string memory metadata,\\n bytes memory signature,\\n bool lockOnCreation,\\n address recipient\\n) external {\\n bytes32 recoveredBidHash = createBid(parentId, bidAmount, bidIPFSHash, name);\\n address recoveredBidder = recover(recoveredBidHash, signature);\\n require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist");\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled");\\n infinity.safeTransferFrom(recoveredBidder, controller, bidAmount);\\n uint256 id = registrar.registerDomain(parentId, name, controller, recoveredBidder);\\n registrar.setDomainMetadataUri(id, metadata);\\n registrar.setDomainRoyaltyAmount(id, royaltyAmount);\\n registrar.transferFrom(controller, recoveredBidder, id);\\n if (lockOnCreation) {\\n registrar.lockDomainMetadataForOwner(id);\\n }\\n```\\n |
zNS- Using a digital signature as a hash preimage | medium | Using the encoded signature (r,s,v) or the hash of the signature to prevent replay or track if signatures have been seen/used is not recommended in general, as it may introduce signature malleability issues, as two different signature params (r,s,v) may be producable that validly sign the same data.\\nThe impact for this codebase, however, is limited, due to the fact that openzeppelins `ECDSA` wrapper library is used which checks for malleable `ECDSA` signatures (high s value). We still decided to keep this as a medium issue to raise awareness, that it is bad practice to rely on the hash of signatures instead of the hash of the actual signed data for checks.\\nIn another instance in zAuction, a global random nonce is used to prevent replay attacks. This is suboptimal and instead, the hash of the signed data (including a nonce) should be used.\\n```\\n function fulfillDomainBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n uint256 royaltyAmount,\\n string memory bidIPFSHash,\\n string memory name,\\n string memory metadata,\\n bytes memory signature,\\n bool lockOnCreation,\\n address recipient\\n) external {\\n bytes32 recoveredBidHash = createBid(parentId, bidAmount, bidIPFSHash, name);\\n address recoveredBidder = recover(recoveredBidHash, signature);\\n require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist");\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled");\\n infinity.safeTransferFrom(recoveredBidder, controller, bidAmount);\\n uint256 id = registrar.registerDomain(parentId, name, controller, recoveredBidder);\\n registrar.setDomainMetadataUri(id, metadata);\\n registrar.setDomainRoyaltyAmount(id, royaltyAmount);\\n registrar.transferFrom(controller, recoveredBidder, id);\\n if (lockOnCreation) {\\n registrar.lockDomainMetadataForOwner(id);\\n }\\n approvedBids[hashOfSig] = false;\\n emit DomainBidFulfilled(\\n metadata,\\n name,\\n recoveredBidder,\\n id,\\n parentId\\n );\\n}\\n```\\n\\n```\\nfunction acceptBid(bytes memory signature, uint256 rand, address bidder, uint256 bid, address nftaddress, uint256 tokenid) external {\\n address recoveredbidder = recover(toEthSignedMessageHash(keccak256(abi.encode(rand, address(this), block.chainid, bid, nftaddress, tokenid))), signature);\\n require(bidder == recoveredbidder, 'zAuction: incorrect bidder');\\n require(!randUsed[rand], 'Random nonce already used');\\n randUsed[rand] = true;\\n```\\n | Consider creating the bid identifier by hashing the concatenation of all bid parameters instead. Ensure to add replay protection https://github.com/ConsenSys/zer0-zns-audit-2021-05/issues/19. Always check for the hash of the signed data instead of the hash of the encoded signature to track whether a signature has been seen before.\\nConsider implementing Ethereum typed structured data hashing and signing according to EIP-712. | null | ```\\n function fulfillDomainBid(\\n uint256 parentId,\\n uint256 bidAmount,\\n uint256 royaltyAmount,\\n string memory bidIPFSHash,\\n string memory name,\\n string memory metadata,\\n bytes memory signature,\\n bool lockOnCreation,\\n address recipient\\n) external {\\n bytes32 recoveredBidHash = createBid(parentId, bidAmount, bidIPFSHash, name);\\n address recoveredBidder = recover(recoveredBidHash, signature);\\n require(recipient == recoveredBidder, "ZNS: bid info doesnt match/exist");\\n bytes32 hashOfSig = keccak256(abi.encode(signature));\\n require(approvedBids[hashOfSig] == true, "ZNS: has been fullfilled");\\n infinity.safeTransferFrom(recoveredBidder, controller, bidAmount);\\n uint256 id = registrar.registerDomain(parentId, name, controller, recoveredBidder);\\n registrar.setDomainMetadataUri(id, metadata);\\n registrar.setDomainRoyaltyAmount(id, royaltyAmount);\\n registrar.transferFrom(controller, recoveredBidder, id);\\n if (lockOnCreation) {\\n registrar.lockDomainMetadataForOwner(id);\\n }\\n approvedBids[hashOfSig] = false;\\n emit DomainBidFulfilled(\\n metadata,\\n name,\\n recoveredBidder,\\n id,\\n parentId\\n );\\n}\\n```\\n |
zNS - Registrar skips __ERC721Pausable_init() | low | The initialization function of registrar skips the chained initializer `__ERC721Pausable_init` to initialize `__ERC721_init("Zer0 Name Service", "ZNS")`. This basically skips the following initialization calls:\\n```\\nabstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable {\\n function \\_\\_ERC721Pausable\\_init() internal initializer {\\n \\_\\_Context\\_init\\_unchained(); \\n \\_\\_ERC165\\_init\\_unchained();\\n \\_\\_Pausable\\_init\\_unchained();\\n \\_\\_ERC721Pausable\\_init\\_unchained();\\n }\\n```\\n\\n```\\nfunction initialize() public initializer {\\n \\_\\_Ownable\\_init();\\n \\_\\_ERC721\\_init("Zer0 Name Service", "ZNS");\\n\\n // create the root domain\\n \\_createDomain(0, msg.sender, msg.sender, address(0));\\n}\\n```\\n | consider calling the missing initializers to register the interface for erc165 if needed. | null | ```\\nabstract contract ERC721PausableUpgradeable is Initializable, ERC721Upgradeable, PausableUpgradeable {\\n function \\_\\_ERC721Pausable\\_init() internal initializer {\\n \\_\\_Context\\_init\\_unchained(); \\n \\_\\_ERC165\\_init\\_unchained();\\n \\_\\_Pausable\\_init\\_unchained();\\n \\_\\_ERC721Pausable\\_init\\_unchained();\\n }\\n```\\n |
zNS - Registrar is ERC721PausableUpgradeable but there is no way to actually pause it | low | The registrar is ownable and pausable but the functionality to pause the contract is not implemented.\\n```\\ncontract Registrar is\\n IRegistrar,\\n OwnableUpgradeable,\\n ERC721PausableUpgradeable\\n{\\n```\\n | Simplification is key. Remove the pausable functionality if the contract is not meant to be paused or consider implementing an external `pause()` function decorated `onlyOwner`. | null | ```\\ncontract Registrar is\\n IRegistrar,\\n OwnableUpgradeable,\\n ERC721PausableUpgradeable\\n{\\n```\\n |
zNS - Avoid no-ops | low | Code paths that are causing transactions to be ended with an ineffective outcome or no-operation (no actual state changes) are not advisable, as they consume more gas, hide misconfiguration or error cases (e.g. adding the same controller multiple times), and may impact other processes that rely upon transaction's logs.\\nReject adding an already existing controller, and removing non existing controller.\\n```\\n/\\*\\*\\n @notice Authorizes a controller to control the registrar\\n @param controller The address of the controller\\n \\*/\\nfunction addController(address controller) external override onlyOwner {\\n controllers[controller] = true;\\n emit ControllerAdded(controller);\\n}\\n\\n/\\*\\*\\n @notice Unauthorizes a controller to control the registrar\\n @param controller The address of the controller\\n \\*/\\nfunction removeController(address controller) external override onlyOwner {\\n controllers[controller] = false;\\n emit ControllerRemoved(controller);\\n}\\n```\\n | Consider reverting code paths that end up in ineffective outcomes (i.e. no-operation) as early as possible. | null | ```\\n/\\*\\*\\n @notice Authorizes a controller to control the registrar\\n @param controller The address of the controller\\n \\*/\\nfunction addController(address controller) external override onlyOwner {\\n controllers[controller] = true;\\n emit ControllerAdded(controller);\\n}\\n\\n/\\*\\*\\n @notice Unauthorizes a controller to control the registrar\\n @param controller The address of the controller\\n \\*/\\nfunction removeController(address controller) external override onlyOwner {\\n controllers[controller] = false;\\n emit ControllerRemoved(controller);\\n}\\n```\\n |
RocketRewardPool - Unpredictable staking rewards as stake can be added just before claiming and rewards may be paid to to operators that do not provide a service to the system Partially Addressed | high | Nodes/TrustedNodes earn rewards based on the current share of the effective RPL stake provided backing the number of Minipools they run. The reward is paid out regardless of when the effective node stake was provided, as long as it is present just before the call to `claim()`. This means the reward does not take into account how long the stake was provided. The effective RPL stake is the nodes RPL stake capped at a maximum of `halfDepositUserAmount * 150% * nr_of_minipools(node) / RPLPrice`. If the node does not run any Minipools, the effective RPL stake is zero.\\nSince effective stake can be added just before calling the `claim()` method (effectively trying to get a reward for a period that passed without RPL being staked for the full duration), this might create an unpredictable outcome for other participants, as adding significant stake (requires creating Minipools and staking the max per pool; the stake is locked for at least the duration of a reward period rpl.rewards.claim.period.blocks) shifts the shares users get for the fixed total amount of rewards. This can be unfair if the first users claimed their reward, and then someone is artificially inflating the total amount of shares by adding more stake to get a bigger part of the remaining reward. However, this comes at the cost of the registered node having to create more Minipools to stake more, requiring an initial deposit (16ETH, or 0ETH under certain circumstances for trusted nodes) by the actor attempting to get a larger share of the rewards. The risk of losing funds for this actor, however, is rather low, as they can immediately `dissolve()` and `close()` the Minipool to refund their node deposit as `NETH` right after claiming the reward only losing the gas spent on the various transactions.\\nThis can be extended to a node operator creating a Minipool and staking the maximum amount before calling `claim` to remove the Minipool right after, freeing up the `ETH` that was locked in the Minipool until the next reward period starts. The node operator is not providing any service to the network, loses some value in `ETH` for gas but may compensate that with the RPL staking rewards. If the node amassed a significant amount of RPL stake, they might even try to flash-loan enough `ETH` to spawn Minipools to inflate their effective stake and earn most of the rewards to return the loan RPL profit.\\n```\\n-- reward period ends -- front-run other claimers to maximize profits\\n[create x minipools]\\n[stake to max effective RPL for amount of minipools; locked for 14 days]\\n[claim rewards for inflated effective RPL stake]\\n[dissolve(), close() minipools -> refund NETH]\\n[burn NETH for ETH]\\n// rest of code wait 14 days\\n[withdraw stake OR start again creating Minipools, claiming rewards while the Minipools are dissolved right after, freeing the ETH]\\n```\\n\\nBy staking just before claiming, the node effectively can earn rewards for 2 reward periods by only staking RPL for the duration of one period (claim the previous period, leave it in for 14 days, claim another period, withdraw).\\nThe stake can be withdrawn at the earliest 14 days after staking. However, it can be added back at any time, and the stake addition takes effect immediately. This allows for optimizing the staking reward as follows (assuming we front-run other claimers to maximize profits and perform all transactions in one block):\\n```\\n[stake max effective amount for the number of minipools]\\n[claim() to claim the previous period even though we did not provide any stake for the duration]\\n[optionally dissolve Minipools unlocking ETH]\\n-- stake is locked for at least 14 days --\\n-- 14 days forward - new reward period started --\\n[claim() the period]\\n[withdraw() (leaving min pool stake OR everything if we dissolve all the Minipool)]\\n[lend RPL to other platforms and earn interest]\\n-- 14 days forward -new reward period started --\\n[get RPL back from another platform]\\n[stake & create minipools to inflate effective stake]\\n[claim()]\\n[optionally dissolve Minipools to unlock node ETH]\\n-- stake is locked for at least 14 days --\\n-- 14 days forward - new reward period started --\\n[claim() the period]\\n[withdraw() (leaving min pool stake OR everything if we dissolve all the Minipools)]\\n[lend RPL to other platforms and earn interest]\\n// rest of code\\n```\\n\\nNote that `withdraw()` can be called right at the time the new reward period starts:\\n```\\nrequire(block.number.sub(getNodeRPLStakedBlock(msg.sender)) >= rocketDAOProtocolSettingsRewards.getRewardsClaimIntervalBlocks(), "The withdrawal cooldown period has not passed");\\n// Get & check node's current RPL stake\\n```\\n\\nA node may choose to register and stake some RPL to collect rewards but never actually provide registered node duties, e.g., operating a Minipool.\\nNode shares for a passed reward epoch are unpredictable as nodes may change their stake (adding) after/before users claim their rewards.\\nA node can maximize its rewards by adding stake just before claiming it\\nA node can stake to claim rewards, wait 14 days, withdraw, lend on a platform and return the stake in time to claim the next period. | Review the incentive model for the RPL rewards. Consider adjusting it so that nodes that provide a service get a better share of the rewards. Consider accruing rewards for the duration the stake was provided instead of taking a snapshot whenever the node calls `claim()`. Require stake to be locked for > 14 days instead of >=14 days (withdraw()) or have users skip the first reward period after staking. | null | ```\\n-- reward period ends -- front-run other claimers to maximize profits\\n[create x minipools]\\n[stake to max effective RPL for amount of minipools; locked for 14 days]\\n[claim rewards for inflated effective RPL stake]\\n[dissolve(), close() minipools -> refund NETH]\\n[burn NETH for ETH]\\n// rest of code wait 14 days\\n[withdraw stake OR start again creating Minipools, claiming rewards while the Minipools are dissolved right after, freeing the ETH]\\n```\\n |
Prefer using abi.encode in TokenDistributor | medium | The method `_hashLeaf` is called when a user claims their airdrop.\\n```\\n// can we repoduce leaf hash included in the claim?\\nrequire(\\_hashLeaf(user\\_id, user\\_amount, leaf), 'TokenDistributor: Leaf Hash Mismatch.');\\n```\\n\\nThis method receives the `user_id` and the `user_amount` as arguments.\\n```\\n/\\*\\*\\n\\* @notice hash user\\_id + claim amount together & compare results to leaf hash \\n\\* @return boolean true on match\\n\\*/\\nfunction \\_hashLeaf(uint32 user\\_id, uint256 user\\_amount, bytes32 leaf) private returns (bool) {\\n```\\n\\nThese arguments are abi encoded and hashed together to produce a unique hash.\\n```\\nbytes32 leaf\\_hash = keccak256(abi.encodePacked(keccak256(abi.encodePacked(user\\_id, user\\_amount))));\\n```\\n\\nThis hash is checked against the third argument for equality.\\n```\\nreturn leaf == leaf\\_hash;\\n```\\n\\nIf the hash matches the third argument, it returns true and considers the provided `user_id` and `user_amount` are correct.\\nHowever, packing differently sized arguments may produce collisions.\\nThe Solidity documentation states that packing dynamic types will produce collisions, but this is also the case if packing `uint32` and `uint256`.\\nBelow there's an example showing that packing `uint32` and `uint256` in both orders can produce collisions with carefully picked values.\\n```\\nlibrary Encode {\\n function encode32Plus256(uint32 \\_a, uint256 \\_b) public pure returns (bytes memory) {\\n return abi.encodePacked(\\_a, \\_b);\\n }\\n \\n function encode256Plus32(uint256 \\_a, uint32 \\_b) public pure returns (bytes memory) {\\n return abi.encodePacked(\\_a, \\_b);\\n }\\n}\\n\\ncontract Hash {\\n function checkEqual() public pure returns (bytes32, bytes32) {\\n // Pack 1\\n uint32 a1 = 0x12345678;\\n uint256 b1 = 0x99999999999999999999999999999999999999999999999999999999FFFFFFFF;\\n \\n // Pack 2\\n uint256 a2 = 0x1234567899999999999999999999999999999999999999999999999999999999;\\n uint32 b2 = 0xFFFFFFFF;\\n \\n // Encode these 2 different values\\n bytes memory packed1 = Encode.encode32Plus256(a1, b1);\\n bytes memory packed2 = Encode.encode256Plus32(a2, b2);\\n \\n // Check if the packed encodings match\\n require(keccak256(packed1) == keccak256(packed2), "Hash of representation should match");\\n \\n // The hashes are the same\\n // 0x9e46e582607c5c6e05587dacf66d311c4ced0819378a41d4b4c5adf99d72408e\\n return (\\n keccak256(packed1),\\n keccak256(packed2)\\n );\\n }\\n}\\n```\\n\\nChanging `abi.encodePacked` to `abi.encode` in the library will make the transaction fail with error message `Hash of representation should match`. | Resolution\\nFixed in gitcoinco/governance#7\\nUnless there's a specific use case to use `abi.encodePacked`, you should always use `abi.encode`. You might need a few more bytes in the transaction data, but it prevents collisions. Similar fix can be achieved by using `unit256` for both values to be packed to prevent any possible collisions. | null | ```\\n// can we repoduce leaf hash included in the claim?\\nrequire(\\_hashLeaf(user\\_id, user\\_amount, leaf), 'TokenDistributor: Leaf Hash Mismatch.');\\n```\\n |
Simplify claim tokens for a gas discount and less code | low | The method `claimTokens` in `TokenDistributor` needs to do a few checks before it can distribute the tokens.\\nA few of these checks can be simplified and optimized.\\nThe method `hashMatch` can be removed because it's only used once and the contents can be moved directly into the parent method.\\n```\\n// can we reproduce the same hash from the raw claim metadata?\\nrequire(hashMatch(user\\_id, user\\_address, user\\_amount, delegate\\_address, leaf, eth\\_signed\\_message\\_hash\\_hex), 'TokenDistributor: Hash Mismatch.');\\n```\\n\\nBecause this method also uses a few other internal calls, they also need to be moved into the parent method.\\n```\\nreturn getDigest(claim) == eth\\_signed\\_message\\_hash\\_hex;\\n```\\n\\n```\\nhashClaim(claim)\\n```\\n\\nMoving the code directly in the parent method and removing them will improve gas costs for users.\\nThe structure `Claim` can also be removed because it's not used anywhere else in the code. | Consider simplifying `claimTokens` and remove unused methods. | null | ```\\n// can we reproduce the same hash from the raw claim metadata?\\nrequire(hashMatch(user\\_id, user\\_address, user\\_amount, delegate\\_address, leaf, eth\\_signed\\_message\\_hash\\_hex), 'TokenDistributor: Hash Mismatch.');\\n```\\n |
Rename method _hashLeaf to something that represents the validity of the leaf | low | The method `_hashLeaf` accepts 3 arguments.\\n```\\nfunction \\_hashLeaf(uint32 user\\_id, uint256 user\\_amount, bytes32 leaf) private returns (bool) {\\n```\\n\\nThe arguments `user_id` and `user_amount` are used to create a keccak256 hash.\\n```\\nbytes32 leaf\\_hash = keccak256(abi.encodePacked(keccak256(abi.encodePacked(user\\_id, user\\_amount))));\\n```\\n\\nThis hash is then checked if it matches the third argument.\\n```\\nreturn leaf == leaf\\_hash;\\n```\\n\\nThe result of the equality is returned by the method.\\nThe name of the method is confusing because it should say that it returns true if the leaf is considered valid. | Resolution\\nClosed because the method was removed in gitcoinco/governance#4\\nConsider renaming the method to something like `isValidLeafHash`. | null | ```\\nfunction \\_hashLeaf(uint32 user\\_id, uint256 user\\_amount, bytes32 leaf) private returns (bool) {\\n```\\n |
Method returns bool but result is never used in TokenDistributor.claimTokens | low | The method `_delegateTokens` is called when a user claims their tokens to automatically delegate the claimed tokens to their own address or to a different one.\\n```\\n\\_delegateTokens(user\\_address, delegate\\_address);\\n```\\n\\nThe method accepts the addresses of the delegator and the delegate and returns a boolean.\\n```\\n/\\*\\*\\n\\* @notice execute call on token contract to delegate tokens \\n\\* @return boolean true on success \\n\\*/\\nfunction \\_delegateTokens(address delegator, address delegatee) private returns (bool) {\\n GTCErc20 GTCToken = GTCErc20(token);\\n GTCToken.delegateOnDist(delegator, delegatee);\\n return true; \\n} \\n```\\n\\nBut this boolean is never used. | Remove the returned boolean because it's always returned as `true` anyway and the transaction will be a bit cheaper. | null | ```\\n\\_delegateTokens(user\\_address, delegate\\_address);\\n```\\n |
Improve efficiency by using immutable in TreasuryVester | low | The `TreasuryVester` contract when deployed has a few fixed storage variables.\\n```\\ngtc = gtc\\_;\\n```\\n\\n```\\nvestingAmount = vestingAmount\\_;\\nvestingBegin = vestingBegin\\_;\\nvestingCliff = vestingCliff\\_;\\nvestingEnd = vestingEnd\\_;\\n```\\n\\nThese storage variables are defined in the contract.\\n```\\naddress public gtc;\\n```\\n\\n```\\nuint public vestingAmount;\\nuint public vestingBegin;\\nuint public vestingCliff;\\nuint public vestingEnd;\\n```\\n\\nBut they are never changed. | Resolution\\nFixed in gitcoinco/governance#5\\nConsider setting storage variables as `immutable` type for a considerable gas improvement. | null | ```\\ngtc = gtc\\_;\\n```\\n |
RocketDaoNodeTrusted - DAO takeover during deployment/bootstrapping | high | The initial deployer of the `RocketStorage` contract is set as the Guardian/Bootstrapping role. This guardian can bootstrap the TrustedNode and Protocol DAO, add members, upgrade components, change settings.\\nRight after deploying the DAO contract the member count is zero. The Guardian can now begin calling any of the bootstrapping functions to add members, change settings, upgrade components, interact with the treasury, etc. The bootstrapping configuration by the Guardian is unlikely to all happen within one transaction which might allow other parties to interact with the system while it is being set up.\\n`RocketDaoNodeTrusted` also implements a recovery mode that allows any registered node to invite themselves directly into the DAO without requiring approval from the Guardian or potential other DAO members as long as the total member count is below `daoMemberMinCount` (3). The Guardian itself is not counted as a DAO member as it is a supervisory role.\\n```\\n/\\*\\*\\*\\* Recovery \\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*/\\n \\n// In an explicable black swan scenario where the DAO loses more than the min membership required (3), this method can be used by a regular node operator to join the DAO\\n// Must have their ID, email, current RPL bond amount available and must be called by their current registered node account\\nfunction memberJoinRequired(string memory \\_id, string memory \\_email) override public onlyLowMemberMode onlyRegisteredNode(msg.sender) onlyLatestContract("rocketDAONodeTrusted", address(this)) {\\n // Ok good to go, lets add them\\n (bool successPropose, bytes memory responsePropose) = getContractAddress('rocketDAONodeTrustedProposals').call(abi.encodeWithSignature("proposalInvite(string,string,address)", \\_id, \\_email, msg.sender));\\n // Was there an error?\\n require(successPropose, getRevertMsg(responsePropose));\\n // Get the to automatically join as a member (by a regular proposal, they would have to manually accept, but this is no ordinary situation)\\n (bool successJoin, bytes memory responseJoin) = getContractAddress("rocketDAONodeTrustedActions").call(abi.encodeWithSignature("actionJoinRequired(address)", msg.sender));\\n // Was there an error?\\n require(successJoin, getRevertMsg(responseJoin));\\n}\\n```\\n\\nThis opens up a window during the bootstrapping phase where any Ethereum Address might be able to register as a node (RocketNodeManager.registerNode) if node registration is enabled (default=true) rushing into `RocketDAONodeTrusted.memberJoinRequired` adding themselves (up to 3 nodes) as trusted nodes to the DAO. The new DAO members can now take over the DAO by issuing proposals, waiting 2 blocks to vote/execute them (upgrade, change settings while Guardian is changing settings, etc.). The Guardian role can kick the new DAO members, however, they can invite themselves back into the DAO.\\n```\\nsetSettingBool("node.registration.enabled", true); \\n```\\n | Disable the DAO recovery mode during bootstrapping. Disable node registration by default and require the guardian to enable it. Ensure that `bootstrapDisable` (in both DAO contracts) performs sanity checks as to whether the DAO bootstrapping finished and permissions can effectively be revoked without putting the DAO at risk or in an irrecoverable state (enough members bootstrapped, vital configurations like registration and other settings are configured, …). | null | ```\\n/\\*\\*\\*\\* Recovery \\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*\\*/\\n \\n// In an explicable black swan scenario where the DAO loses more than the min membership required (3), this method can be used by a regular node operator to join the DAO\\n// Must have their ID, email, current RPL bond amount available and must be called by their current registered node account\\nfunction memberJoinRequired(string memory \\_id, string memory \\_email) override public onlyLowMemberMode onlyRegisteredNode(msg.sender) onlyLatestContract("rocketDAONodeTrusted", address(this)) {\\n // Ok good to go, lets add them\\n (bool successPropose, bytes memory responsePropose) = getContractAddress('rocketDAONodeTrustedProposals').call(abi.encodeWithSignature("proposalInvite(string,string,address)", \\_id, \\_email, msg.sender));\\n // Was there an error?\\n require(successPropose, getRevertMsg(responsePropose));\\n // Get the to automatically join as a member (by a regular proposal, they would have to manually accept, but this is no ordinary situation)\\n (bool successJoin, bytes memory responseJoin) = getContractAddress("rocketDAONodeTrustedActions").call(abi.encodeWithSignature("actionJoinRequired(address)", msg.sender));\\n // Was there an error?\\n require(successJoin, getRevertMsg(responseJoin));\\n}\\n```\\n |
RocketDaoNodeTrustedActions - Incomplete implementation of member challenge process | high | Any registered (even untrusted) node can challenge a trusted DAO node to respond. The challenge is initiated by calling `actionChallengeMake`. Trusted nodes can challenge for free, other nodes have to provide `members.challenge.cost` as a tribute to the Ethereum gods. The challenged node must call `actionChallengeDecide` before `challengeStartBlock + members.challenge.window` blocks are over (default approx 7 days). However, the Golang codebase does not actively monitor for the `ActionChallengeMade` event, nor does the node - regularly - check if it is being challenged. Means to respond to the challenge (calling `actionChallengeDecide` to stop the challenge) are not implemented.\\nNodes do not seem to monitor `ActionChallengeMade` events so that they could react to challenges\\nNodes do not implement `actionChallengeDecide` and, therefore, cannot successfully stop a challenge\\nFunds/Tribute sent along with the challenge will be locked forever in the `RocketDAONodeTrustedActions` contract. There's no means to recover the funds.\\nIt is questionable whether the incentives are aligned well enough for anyone to challenge stale nodes. The default of `1 eth` compared to the risk of the “malicious” or “stale” node exiting themselves is quite high. The challenger is not incentivized to challenge someone other than for taking over the DAO. If the tribute is too low, this might incentivize users to grief trusted nodes and force them to close a challenge.\\nRequiring that the challenge initiator is a different registered node than the challenge finalized is a weak protection since the system is open to anyone to register as a node (even without depositing any funds.)\\nblock time is subject to fluctuations. With the default of `43204` blocks, the challenge might expire at `5 days` (10 seconds block time), `6.5 days` (13 seconds Ethereum target median block time), `7 days` (14 seconds), or more with historic block times going up to `20 seconds` for shorter periods.\\nA minority of trusted nodes may use this functionality to boot other trusted node members off the DAO issuing challenges once a day until the DAO member number is low enough to allow them to reach quorum for their own proposals or until the member threshold allows them to add new nodes without having to go through the proposal process at all.\\n```\\nsetSettingUint('members.challenge.cooldown', 6172); // How long a member must wait before performing another challenge, approx. 1 day worth of blocks\\nsetSettingUint('members.challenge.window', 43204); // How long a member has to respond to a challenge. 7 days worth of blocks\\nsetSettingUint('members.challenge.cost', 1 ether); // How much it costs a non-member to challenge a members node. It's free for current members to challenge other members.\\n```\\n\\n```\\n// In the event that the majority/all of members go offline permanently and no more proposals could be passed, a current member or a regular node can 'challenge' a DAO members node to respond\\n// If it does not respond in the given window, it can be removed as a member. The one who removes the member after the challenge isn't met, must be another node other than the proposer to provide some oversight\\n// This should only be used in an emergency situation to recover the DAO. Members that need removing when consensus is still viable, should be done via the 'kick' method.\\n```\\n | Implement the challenge-response process before enabling users to challenge other nodes. Implement means to detect misuse of this feature for griefing e.g. when one trusted node member forces another trusted node to defeat challenges over and over again (technical controls, monitoring). | null | ```\\nsetSettingUint('members.challenge.cooldown', 6172); // How long a member must wait before performing another challenge, approx. 1 day worth of blocks\\nsetSettingUint('members.challenge.window', 43204); // How long a member has to respond to a challenge. 7 days worth of blocks\\nsetSettingUint('members.challenge.cost', 1 ether); // How much it costs a non-member to challenge a members node. It's free for current members to challenge other members.\\n```\\n |
RocketDAOProtocolSettings/RocketDAONodeTrustedSettings - anyone can set/overwrite settings until contract is declared “deployed” Acknowledged | high | The `onlyDAOProtocolProposal` modifier guards all state-changing methods in this contract. However, analog to https://github.com/ConsenSys/rocketpool-audit-2021-03/issues/7, the access control is disabled until the variable `settingsNameSpace.deployed` is set. If this contract is not deployed and configured in one transaction, anyone can update the contract while left unprotected on the blockchain.\\nSee issue 6.5 for a similar issue.\\n```\\nmodifier onlyDAOProtocolProposal() {\\n // If this contract has been initialised, only allow access from the proposals contract\\n if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress('rocketDAOProtocolProposals') == msg.sender, "Only DAO Protocol Proposals contract can update a setting");\\n \\_;\\n}\\n```\\n\\n```\\nmodifier onlyDAONodeTrustedProposal() {\\n // If this contract has been initialised, only allow access from the proposals contract\\n if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress('rocketDAONodeTrustedProposals') == msg.sender, "Only DAO Node Trusted Proposals contract can update a setting");\\n \\_;\\n}\\n```\\n\\nThere are at least 9 more occurrences of this pattern. | Restrict access to the methods to a temporary trusted account (e.g. guardian) until the system bootstrapping phase ends by setting `deployed` to `true.` | null | ```\\nmodifier onlyDAOProtocolProposal() {\\n // If this contract has been initialised, only allow access from the proposals contract\\n if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress('rocketDAOProtocolProposals') == msg.sender, "Only DAO Protocol Proposals contract can update a setting");\\n \\_;\\n}\\n```\\n |
RocketStorage - anyone can set/update values before the contract is initialized | high | According to the deployment script, the contract is deployed, and settings are configured in multiple transactions. This also means that for a period of time, the contract is left unprotected on the blockchain. Anyone can delete/set any value in the centralized data store. An attacker might monitor the mempool for new deployments of the `RocketStorage` contract and front-run calls to `contract.storage.initialised` setting arbitrary values in the system.\\n```\\nmodifier onlyLatestRocketNetworkContract() {\\n // The owner and other contracts are only allowed to set the storage upon deployment to register the initial contracts/settings, afterwards their direct access is disabled\\n if (boolStorage[keccak256(abi.encodePacked("contract.storage.initialised"))] == true) {\\n // Make sure the access is permitted to only contracts in our Dapp\\n require(boolStorage[keccak256(abi.encodePacked("contract.exists", msg.sender))], "Invalid or outdated network contract");\\n }\\n \\_;\\n}\\n```\\n | Restrict access to the methods to a temporary trusted account (e.g. guardian) until the system bootstrapping phase ends by setting `initialised` to `true.` | null | ```\\nmodifier onlyLatestRocketNetworkContract() {\\n // The owner and other contracts are only allowed to set the storage upon deployment to register the initial contracts/settings, afterwards their direct access is disabled\\n if (boolStorage[keccak256(abi.encodePacked("contract.storage.initialised"))] == true) {\\n // Make sure the access is permitted to only contracts in our Dapp\\n require(boolStorage[keccak256(abi.encodePacked("contract.exists", msg.sender))], "Invalid or outdated network contract");\\n }\\n \\_;\\n}\\n```\\n |
RocketDAOProposals - Unpredictable behavior due to short vote delay | high | A proposal can be voted and passed when it enters the `ACTIVE` state. Voting starts when the current `block.number` is greater than the `startBlock` configured in the proposal (up until the endBlock). The requirement for the `startBlock` is to be at least greater than `block.number` when the proposal is submitted.\\n```\\nrequire(\\_startBlock > block.number, "Proposal start block must be in the future");\\nrequire(\\_durationBlocks > 0, "Proposal cannot have a duration of 0 blocks");\\nrequire(\\_expiresBlocks > 0, "Proposal cannot have a execution expiration of 0 blocks");\\nrequire(\\_votesRequired > 0, "Proposal cannot have a 0 votes required to be successful");\\n```\\n\\nThe default vote delay configured in the system is `1` block.\\n```\\nsetSettingUint('proposal.vote.delay.blocks', 1); // How long before a proposal can be voted on after it is created. Approx. Next Block\\n```\\n\\nA vote is immediately passed when the required quorum is reached which allows it to be executed. This means that a group that is holding enough voting power can propose a change, wait for two blocks (block.number (of time of proposal creation) + configuredDelay (1) + 1 (for ACTIVE state), then vote and execute for the proposal to pass for it to take effect almost immediately after only 2 blocks (<30seconds).\\nSettings can be changed after 30 seconds which might be unpredictable for other DAO members and not give them enough time to oppose and leave the DAO. | The underlying issue is that users of the system can't be sure what the behavior of a function call will be, and this is because the behavior can change after two blocks. The only guarantee is that users can be sure the settings don't change for the next block if no proposal is active.\\nWe recommend giving the user advance notice of changes with a delay. For example, all upgrades should require two steps with a mandatory time window between them. The first step merely broadcasts to users that a particular change is coming, and the second step commits that change after a suitable waiting period. | null | ```\\nrequire(\\_startBlock > block.number, "Proposal start block must be in the future");\\nrequire(\\_durationBlocks > 0, "Proposal cannot have a duration of 0 blocks");\\nrequire(\\_expiresBlocks > 0, "Proposal cannot have a execution expiration of 0 blocks");\\nrequire(\\_votesRequired > 0, "Proposal cannot have a 0 votes required to be successful");\\n```\\n |
RocketNodeStaking - Node operators can reduce slashing impact by withdrawing excess staked RPL | high | Oracle nodes update the Minipools' balance and progress it to the withdrawable state when they observe the minipools stake to become withdrawable. If the observed stakingEndBalance is less than the user deposit for that pool, the node operator is punished for the difference.\\n```\\nrocketMinipoolManager.setMinipoolWithdrawalBalances(\\_minipoolAddress, \\_stakingEndBalance, nodeAmount);\\n// Apply node penalties by liquidating RPL stake\\nif (\\_stakingEndBalance < userDepositBalance) {\\n RocketNodeStakingInterface rocketNodeStaking = RocketNodeStakingInterface(getContractAddress("rocketNodeStaking"));\\n rocketNodeStaking.slashRPL(minipool.getNodeAddress(), userDepositBalance - \\_stakingEndBalance);\\n}\\n```\\n\\nThe amount slashed is at max `userDepositBalance - stakingEndBalance`. The `userDepositBalance` is at least `16 ETH` (minipool.half/.full) and at max `32 ETH` (minipool.empty). The maximum amount to be slashed is therefore `32 ETH` (endBalance = 0, minipool.empty).\\nThe slashing amount is denoted in `ETH`. The `RPL` price (in ETH) is updated regularly by oracle nodes (see related issue https://github.com/ConsenSys/rocketpool-audit-2021-03/issues/32; note that the `RPL` token is potentially affected by a similar issue as one can stake `RPL`, wait for the cooldown period & wait for the price to change, and withdraw stake at higher `RPL` price/ETH). The `ETH` amount to be slashed is converted to `RPL`, and the corresponding `RPL` stake is slashed.\\n```\\nuint256 rplSlashAmount = calcBase.mul(\\_ethSlashAmount).div(rocketNetworkPrices.getRPLPrice());\\n// Cap slashed amount to node's RPL stake\\nuint256 rplStake = getNodeRPLStake(\\_nodeAddress);\\nif (rplSlashAmount > rplStake) { rplSlashAmount = rplStake; }\\n// Transfer slashed amount to auction contract\\nrocketVault.transferToken("rocketAuctionManager", getContractAddress("rocketTokenRPL"), rplSlashAmount);\\n// Update RPL stake amounts\\ndecreaseTotalRPLStake(rplSlashAmount);\\ndecreaseNodeRPLStake(\\_nodeAddress, rplSlashAmount);\\n```\\n\\nIf the node does not have a sufficient `RPL` stake to cover the losses, the slashing amount is capped at whatever amount of `RPL` the node has left staked.\\nThe minimum amount of `RPL` a node needs to have staked if it operates minipools is calculated as follows:\\n```\\n // Calculate minimum RPL stake\\n return rocketDAOProtocolSettingsMinipool.getHalfDepositUserAmount()\\n .mul(rocketDAOProtocolSettingsNode.getMinimumPerMinipoolStake())\\n .mul(rocketMinipoolManager.getNodeMinipoolCount(\\_nodeAddress))\\n .div(rocketNetworkPrices.getRPLPrice());\\n}\\n```\\n\\nWith the current configuration, this would resolve in a minimum stake of `16 ETH * 0.1 (10% collateralization) * 1 (nr_minipools) * RPL_Price` for a node operating 1 minipool. This means a node operator basically only needs to have 10% of `16 ETH` staked to operate one minipool.\\nAn operator can withdraw their stake at any time, but they have to wait at least 14 days after the last time they staked (cooldown period). They can, at max, withdraw all but the minimum stake required to run the pools (nr_of_minipools * 16 ETH * 10%). This also means that after the cooldown period, they can reduce their stake to 10% of the half deposit amount (16ETH), then perform a voluntary exit on ETH2 so that the minipool becomes `withdrawable`. If they end up with less than the `userDepositBalance` in staking rewards, they would only get slashed the `1.6 ETH` at max (10% of 16ETH half deposit amount for 1 minipool) even though they incurred a loss that may be up to 32 ETH (empty Minipool empty amount).\\nFurthermore, if a node operator runs multiple minipools, let's say 5, then they would have to provide at least `5*16ETH*0.1 = 8ETH` as a security guarantee in the form of staked RPL. If the node operator incurs a loss with one of their minipools, their 8 ETH RPL stake will likely be slashed in full. Their other - still operating - minipools are not backed by any RPL anymore, and they effectively cannot be slashed anymore. This means that a malicious node operator can create multiple minipools, stake the minimum amount of RPL, get slashed for one minipool, and still operate the others without having the minimum RPL needed to run the minipools staked (getNodeMinipoolLimit).\\nThe RPL stake is donated to the RocketAuctionManager, where they can attempt to buy back RPL potentially at a discount.\\nNote: Staking more RPL (e.g., to add another Minipool) resets the cooldown period for the total RPL staked (not only for the newly added) | It is recommended to redesign the withdrawal process to prevent users from withdrawing their stake while slashable actions can still occur. A potential solution may be to add a locking period in the process. A node operator may schedule the withdrawal of funds, and after a certain time has passed, may withdraw them. This prevents the immediate withdrawal of funds that may need to be reduced while slashable events can still occur. E.g.:\\nA node operator requests to withdraw all but the minimum required stake to run their pools.\\nThe funds are scheduled for withdrawal and locked until a period of X days has passed.\\n(optional) In this period, a slashable event occurs. The funds for compensation are taken from the user's stake including the funds scheduled for withdrawal.\\nAfter the time has passed, the node operator may call a function to trigger the withdrawal and get paid out. | null | ```\\nrocketMinipoolManager.setMinipoolWithdrawalBalances(\\_minipoolAddress, \\_stakingEndBalance, nodeAmount);\\n// Apply node penalties by liquidating RPL stake\\nif (\\_stakingEndBalance < userDepositBalance) {\\n RocketNodeStakingInterface rocketNodeStaking = RocketNodeStakingInterface(getContractAddress("rocketNodeStaking"));\\n rocketNodeStaking.slashRPL(minipool.getNodeAddress(), userDepositBalance - \\_stakingEndBalance);\\n}\\n```\\n |
RocketTokenRPL - inaccurate inflation rate and potential for manipulation lowering the real APY | high | RocketTokenRPL allows users to swap their fixed-rate tokens to the inflationary RocketTokenRPL ERC20 token via a `swapToken` function. The DAO defines the inflation rate of this token and is initially set to be 5% APY. This APY is configured as a daily inflation rate (APD) with the corresponding `1 day in blocks` inflation interval in the `rocketDAOProtocolSettingsInflation` contract. The DAO members control the inflation settings.\\nAnyone can call `inflationMintTokens` to inflate the token, which mints tokens to the contracts RocketVault. Tokens are minted for discreet intervals since the last time `inflationMintTokens` was called (recorded as inflationCalcBlock). The inflation is then calculated for the passed intervals without taking the current not yet completed interval. However, the `inflationCalcBlock` is set to the current `block.number`, effectively skipping some “time”/blocks of the APY calculation.\\nThe more often `inflationMintTokens` is called, the higher the APY likelihood dropping below the configured 5%. In the worst case, one could manipulate the APY down to 2.45% (assuming that the APD for a 5% APY was configured) by calling `inflationMintTokens` close to the end of every second interval. This would essentially restart the APY interval at `block.number`, skipping blocks of the current interval that have not been accounted for.\\nThe following diagram illustrates the skipped blocks due to the incorrect recording of `inflationCalcBlock` as `block.number`. The example assumes that we are in interval 4 but have not completed it. `3` APD intervals have passed, and this is what the inflation rate is based on. However, the `inflationCalcBlock` is updated to the current `block.number`, skipping some time/blocks that are now unaccounted in the APY restarting the 4th interval at `block.number`.\\n\\nNote: updating the inflation rate will directly affect past inflation intervals that have not been minted! this might be undesirable, and it could be considered to force an inflation mint if the APY changes\\nNote: if the interval is small enough and there is a history of unaccounted intervals to be minted, and the Ethereum network is congested, gas fees may be high and block limits hit, the calculations in the for loop might be susceptible to DoS the inflation mechanism because of gas constraints.\\nNote: The inflation seems only to be triggered regularly on `RocketRewardsPool.claim` (or at any point by external actors). If the price establishes based on the total supply of tokens, then this may give attackers an opportunity to front-run other users trading large amounts of RPL that may previously have calculated their prices based on the un-inflated supply.\\nNote: that the discrete interval-based inflation (e.g., once a day) might create dynamics that put pressure on users to trade their RPL in windows instead of consecutively\\nthe inflation intervals passed is the number of completed intervals. The current interval that is started is not included.\\n```\\nfunction getInlfationIntervalsPassed() override public view returns(uint256) {\\n // The block that inflation was last calculated at\\n uint256 inflationLastCalculatedBlock = getInflationCalcBlock();\\n // Get the daily inflation in blocks\\n uint256 inflationInterval = getInflationIntervalBlocks();\\n // Calculate now if inflation has begun\\n if(inflationLastCalculatedBlock > 0) {\\n return (block.number).sub(inflationLastCalculatedBlock).div(inflationInterval);\\n }else{\\n return 0;\\n }\\n}\\n```\\n\\nthe inflation calculation calculates the to-be-minted tokens for the inflation rate at `newTokens = supply * rateAPD^intervals - supply`\\n```\\nfunction inflationCalculate() override public view returns (uint256) {\\n // The inflation amount\\n uint256 inflationTokenAmount = 0;\\n // Optimisation\\n uint256 inflationRate = getInflationIntervalRate();\\n // Compute the number of inflation intervals elapsed since the last time we minted infation tokens\\n uint256 intervalsSinceLastMint = getInlfationIntervalsPassed();\\n // Only update if last interval has passed and inflation rate is > 0\\n if(intervalsSinceLastMint > 0 && inflationRate > 0) {\\n // Our inflation rate\\n uint256 rate = inflationRate;\\n // Compute inflation for total inflation intervals elapsed\\n for (uint256 i = 1; i < intervalsSinceLastMint; i++) {\\n rate = rate.mul(inflationRate).div(10 \\*\\* 18);\\n }\\n // Get the total supply now\\n uint256 totalSupplyCurrent = totalSupply();\\n // Return inflation amount\\n inflationTokenAmount = totalSupplyCurrent.mul(rate).div(10 \\*\\* 18).sub(totalSupplyCurrent);\\n }\\n // Done\\n return inflationTokenAmount;\\n}\\n```\\n | Properly track `inflationCalcBlock` as the end of the previous interval, as this is up to where the inflation was calculated, instead of the block at which the method was invoked.\\nEnsure APY/APD and interval configuration match up. Ensure the interval is not too small (potential gas DoS blocking inflation mint and RocketRewardsPool.claim). | null | ```\\nfunction getInlfationIntervalsPassed() override public view returns(uint256) {\\n // The block that inflation was last calculated at\\n uint256 inflationLastCalculatedBlock = getInflationCalcBlock();\\n // Get the daily inflation in blocks\\n uint256 inflationInterval = getInflationIntervalBlocks();\\n // Calculate now if inflation has begun\\n if(inflationLastCalculatedBlock > 0) {\\n return (block.number).sub(inflationLastCalculatedBlock).div(inflationInterval);\\n }else{\\n return 0;\\n }\\n}\\n```\\n |
RocketDAONodeTrustedUpgrade - upgrade does not prevent the use of the same address multiple times creating an inconsistency where getContractAddress returns outdated information | high | When adding a new contract, it is checked whether the address is already in use. This check is missing when upgrading a named contract to a new implementation, potentially allowing someone to register one address to multiple names creating an inconsistent configuration.\\nThe crux of this is, that, `getContractAddress()` will now return a contract address that is not registered anymore (while `getContractName` may throw). `getContractAddress` can therefore not relied upon when checking ACL.\\nadd contract `name=test, address=0xfefe` ->\\n```\\n sets contract.exists.0xfefe=true\\n sets contract.name.0xfefe=test\\n sets contract.address.test=0xfefe\\n sets contract.abi.test=abi\\n```\\n\\nadd another contract `name=badcontract, address=0xbadbad` ->\\n```\\nsets contract.exists.0xbadbad=true\\nsets contract.name.0xbadbad=badcontract\\nsets contract.address.badcontract=0xbadbad\\nsets contract.abi.badcontract=abi\\n```\\n\\nupdate contract `name=test, address=0xbadbad` reusing badcontradcts address, the address is now bound to 2 names (test, badcontract)\\n```\\noverwrites contract.exists.0xbadbad=true` (even though its already true)\\nupdates contract.name.0xbadbad=test (overwrites the reference to badcontract; badcontracts config is now inconsistent)\\nupdates contract.address.test=0xbadbad (ok, expected)\\nupdates contract.abi.test=abi (ok, expected)\\nremoves contract.name.0xfefe (ok)\\nremoves contract.exists.0xfefe (ok)\\n```\\n\\nupdate contract `name=test, address=0xc0c0`\\n```\\nsets contract.exists.0xc0c0=true\\nsets contract.name.0xc0c0=test (ok, expected)\\nupdates contract.address.test=0xc0c0 (ok, expected)\\nupdates contract.abi.test=abi (ok, expected)\\nremoves contract.name.0xbadbad (the contract is still registered as badcontract, but is indirectly removed now)\\nremoves contract.exists.0xbadbad (the contract is still registered as badcontract, but is indirectly removed now)\\n```\\n\\nAfter this, `badcontract` is partially cleared, `getContractName(0xbadbad)` throws while `getContractAddress(badcontract)` returns `0xbadbad` which is already unregistered (contract.exists.0xbadbad=false)\\n```\\n(removed) contract.exists.0xbadbad\\n(removed) contract.name.0xbadbad=badcontract\\nsets contract.address.badcontract=0xbadbad\\nsets contract.abi.badcontract=abi\\n```\\n\\ncheck in `_addContract``\\n```\\nrequire(\\_contractAddress != address(0x0), "Invalid contract address");\\n```\\n\\nno checks in `upgrade.`\\n```\\nrequire(\\_contractAddress != address(0x0), "Invalid contract address");\\nrequire(\\_contractAddress != oldContractAddress, "The contract address cannot be set to its current address");\\n// Register new contract\\nsetBool(keccak256(abi.encodePacked("contract.exists", \\_contractAddress)), true);\\nsetString(keccak256(abi.encodePacked("contract.name", \\_contractAddress)), \\_name);\\nsetAddress(keccak256(abi.encodePacked("contract.address", \\_name)), \\_contractAddress);\\nsetString(keccak256(abi.encodePacked("contract.abi", \\_name)), \\_contractAbi);\\n```\\n | Resolution\\nA check has been introduced to make sure that the new contract address is not already in use by checking against the corresponding `contract.exists` storage key.\\nCheck that the address being upgraded to is not yet registered and properly clean up `contract.address.<name|abi>`. | null | ```\\n sets contract.exists.0xfefe=true\\n sets contract.name.0xfefe=test\\n sets contract.address.test=0xfefe\\n sets contract.abi.test=abi\\n```\\n |
RocketStorage - Risk concentration by giving all registered contracts permissions to change any settings in RocketStorage Acknowledged | high | The ACL for changing settings in the centralized `RocketStorage` allows any registered contract (listed under contract.exists) to change settings that belong to other parts of the system.\\nThe concern is that if someone finds a way to add their malicious contract to the registered contact list, they will override any setting in the system. The storage is authoritative when checking certain ACLs. Being able to set any value might allow an attacker to gain control of the complete system. Allowing any contract to overwrite other contracts' settings dramatically increases the attack surface.\\n```\\nmodifier onlyLatestRocketNetworkContract() {\\n // The owner and other contracts are only allowed to set the storage upon deployment to register the initial contracts/settings, afterwards their direct access is disabled\\n if (boolStorage[keccak256(abi.encodePacked("contract.storage.initialised"))] == true) {\\n // Make sure the access is permitted to only contracts in our Dapp\\n require(boolStorage[keccak256(abi.encodePacked("contract.exists", msg.sender))], "Invalid or outdated network contract");\\n }\\n \\_;\\n}\\n```\\n\\n```\\nfunction setAddress(bytes32 \\_key, address \\_value) onlyLatestRocketNetworkContract override external {\\n addressStorage[\\_key] = \\_value;\\n}\\n\\n/// @param \\_key The key for the record\\nfunction setUint(bytes32 \\_key, uint \\_value) onlyLatestRocketNetworkContract override external {\\n uIntStorage[\\_key] = \\_value;\\n}\\n```\\n | Resolution\\nThe client provided the following statement:\\nWe've looked at adding access control contracts using namespaces, but the increase in gas usage would be significant and could hinder upgrades.\\nAllow contracts to only change settings related to their namespace. | null | ```\\nmodifier onlyLatestRocketNetworkContract() {\\n // The owner and other contracts are only allowed to set the storage upon deployment to register the initial contracts/settings, afterwards their direct access is disabled\\n if (boolStorage[keccak256(abi.encodePacked("contract.storage.initialised"))] == true) {\\n // Make sure the access is permitted to only contracts in our Dapp\\n require(boolStorage[keccak256(abi.encodePacked("contract.exists", msg.sender))], "Invalid or outdated network contract");\\n }\\n \\_;\\n}\\n```\\n |
RocketDAOProposals - require a minimum participation quorum for DAO proposals | medium | If the DAO falls below the minimum viable membership threshold, voting for proposals still continues as DAO proposals do not require a minimum participation quorum. In the worst case, this would allow the last standing DAO member to create a proposal that would be passable with only one vote even if new members would be immediately ready to join via the recovery mode (which has its own risks) as the minimum votes requirement for proposals is set as `>0`.\\n```\\nrequire(\\_votesRequired > 0, "Proposal cannot have a 0 votes required to be successful");\\n```\\n\\n```\\nfunction propose(string memory \\_proposalMessage, bytes memory \\_payload) override public onlyTrustedNode(msg.sender) onlyLatestContract("rocketDAONodeTrustedProposals", address(this)) returns (uint256) {\\n // Load contracts\\n RocketDAOProposalInterface daoProposal = RocketDAOProposalInterface(getContractAddress('rocketDAOProposal'));\\n RocketDAONodeTrustedInterface daoNodeTrusted = RocketDAONodeTrustedInterface(getContractAddress('rocketDAONodeTrusted'));\\n RocketDAONodeTrustedSettingsProposalsInterface rocketDAONodeTrustedSettingsProposals = RocketDAONodeTrustedSettingsProposalsInterface(getContractAddress("rocketDAONodeTrustedSettingsProposals"));\\n // Check this user can make a proposal now\\n require(daoNodeTrusted.getMemberLastProposalBlock(msg.sender).add(rocketDAONodeTrustedSettingsProposals.getCooldown()) <= block.number, "Member has not waited long enough to make another proposal");\\n // Record the last time this user made a proposal\\n setUint(keccak256(abi.encodePacked(daoNameSpace, "member.proposal.lastblock", msg.sender)), block.number);\\n // Create the proposal\\n return daoProposal.add(msg.sender, 'rocketDAONodeTrustedProposals', \\_proposalMessage, block.number.add(rocketDAONodeTrustedSettingsProposals.getVoteDelayBlocks()), rocketDAONodeTrustedSettingsProposals.getVoteBlocks(), rocketDAONodeTrustedSettingsProposals.getExecuteBlocks(), daoNodeTrusted.getMemberQuorumVotesRequired(), \\_payload);\\n}\\n```\\n\\nSidenote: Since a proposals acceptance quorum is recorded on proposal creation, this may lead to another scenario where proposals acceptance quorum may never be reached if members leave the DAO. This would require a re-submission of the proposal. | Do not accept proposals if the member count falls below the minimum DAO membercount threshold. | null | ```\\nrequire(\\_votesRequired > 0, "Proposal cannot have a 0 votes required to be successful");\\n```\\n |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.