Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

QA Report #236

Open
code423n4 opened this issue Jun 24, 2022 · 2 comments
Open

QA Report #236

code423n4 opened this issue Jun 24, 2022 · 2 comments
Labels
bug Something isn't working QA (Quality Assurance) Assets are not at risk. State handling, function incorrect as to spec, issues with clarity, syntax sponsor disputed Sponsor cannot duplicate the issue, or otherwise disagrees this is an issue

Comments

@code423n4
Copy link
Contributor

Overview

Risk Rating Number of issues
Low Risk 21
Non-Critical Risk 5

Table of Contents

Low Risk Issues

1. whenNotPaused is not used on createBasket

While whenNotPaused is used on createVault:

File: NibblVaultFactory.sol
38:     function createVault(
...
47:         ) external payable override whenNotPaused returns(address payable _proxyVault) {

This seems to have been forgotten on createBasket:

File: NibblVaultFactory.sol
80:     function createBasket(address _curator, string memory _mix) public override returns(address)  {
...
86:     }

2. createBasket uses basketImplementation for salt, but createVault doesn't use vaultImplementation for salt

File: NibblVaultFactory.sol
80:     function createBasket(address _curator, string memory _mix) public override returns(address)  {
81:         address payable _basketAddress = payable(new ProxyBasket{salt: keccak256(abi.encodePacked(_curator, _mix))}(basketImplementation));
...
86:     }
File: NibblVaultFactory.sol
38:     function createVault(
...
47:         ) external payable override whenNotPaused returns(address payable _proxyVault) {
...
50:         _proxyVault = payable(new ProxyVault{salt: keccak256(abi.encodePacked(_curator, _assetAddress, _assetTokenID, _initialSupply, _initialTokenPrice))}(payable(address(this))));

3. Add constructor initializers

As per OpenZeppelin’s (OZ) recommendation, “The guidelines are now to make it impossible for anyone to run initialize on an implementation contract, by adding an empty constructor with the initializer modifier. So the implementation contract gets initialized automatically upon deployment.”

Note that this behaviour is also incorporated the OZ Wizard since the UUPS vulnerability discovery: “Additionally, we modified the code generated by the Wizard 19 to include a constructor that automatically initializes the implementation when deployed.”

Furthermore, this thwarts any attempts to frontrun the initialization tx of these contracts:

contracts/Basket.sol:
  23:     function initialise(address _curator) external override initializer {

contracts/NibblVault.sol:
  182:     ) external override initializer payable {

4. DDOS on nibbledTokens array

The minimum price to create a vault is pretty trivial, 1 gwei:

File: NibblVaultFactory.sol
19:     uint256 private constant MIN_INITIAL_RESERVE_BALANCE = 1e9;

An attacker could spam and bloat the size of the nibbledTokens array to the point getVaults() becomes unusable

contracts/NibblVaultFactory.sol:
  22:     ProxyVault[] public nibbledTokens;
  54:         nibbledTokens.push(ProxyVault(_proxyVault));
  77:         return nibbledTokens;

5. Check Effects Interactions pattern not respected

To avoid unexpected behavior in the future (be it for the solution or for a fork), it's recommended to always follow the CEI pattern.

Consider always moving the state-changes before the external calls.

Affected code:

NibblVaultFactory.sol:53:        IERC721(_assetAddress).safeTransferFrom(msg.sender, address(_vault), _assetTokenID);

6. AccessControlMechanism.sol: propose/accept pattern is redundant since grantRole can be used to push a role

  • File: @openzeppelin/contracts/access/AccessControl.sol
217:     function _grantRole(bytes32 role, address account) internal virtual {
218:         if (!hasRole(role, account)) {
219:             _roles[role].members[account] = true;
220:             emit RoleGranted(role, account, _msgSender());
221:         }
222:     }
  • File: AccessControlMechanism.sol
40:     function proposeGrantRole(bytes32 _role, address _to) external override onlyRole(getRoleAdmin(_role)) {
41:         pendingRoles[_role][_to] = true;
42:     }
43: 
44:     /// @notice proposed user needs to claim the role
45:     /// @dev can only be called by the proposed user
46:     /// @param _role role to be claimed
47:     function claimRole(bytes32 _role) external override {
48:         require(pendingRoles[_role][msg.sender], "AccessControl: Role not pending");
49:         _grantRole(_role, msg.sender);
50:         delete pendingRoles[_role][msg.sender];
51:     }

7. TWAV is only over four blocks

Someone does not have to maintain price variation for long to reject a buyout. This can result in blocking of buyouts.

File: Twav.sol
12:     uint8 private constant TWAV_BLOCK_NUMBERS = 4; //TWAV of last 4 Blocks 

8. Unsafe casting may overflow

SafeMath and Solidity 0.8.* handles overflows for basic math operations but not for casting.
Consider using OpenZeppelin's SafeCast library to prevent unexpected overflows when casting from uint256 here:

NibblVault.sol:183:        uint32 _secondaryReserveRatio = uint32((msg.value * SCALE * 1e18) / (_initialTokenSupply * _initialTokenPrice));
NibblVault.sol:226:        secondaryReserveRatio = uint32((secondaryReserveBalance * SCALE * 1e18) / (initialTokenSupply * initialTokenPrice)); //secondaryReserveRatio is updated on every trade 
NibblVault.sol:303:            uint32 _blockTimestamp = uint32(block.timestamp % 2**32);
NibblVault.sol:365:            uint32 _blockTimestamp = uint32(block.timestamp % 2**32);
NibblVault.sol:413:        _updateTWAV(_currentValuation, uint32(block.timestamp % 2**32));
NibblVault.sol:445:        uint32 _blockTimestamp = uint32(block.timestamp % 2**32);

9. Basic ecrecover is used

Basic ecrecover is used, leading to being able to approve transfers from the zero address. Any tokens sent to 0 address can be recovered by another user.

563:         address signer = ecrecover(toTypedMessageHash(structHash), v, r, s);

Consider using OpenZeppelin’s ECDSA library

10. Missing address(0) checks

(Output from Slither) Consider adding an address(0) check here:

  - _to.transfer(address(this).balance) (contracts/Basket.sol#80)
  - assetAddress = _assetAddress (contracts/NibblVault.sol#191)
  - curator = _curator (contracts/NibblVault.sol#193)
  - curator = _newCurator (contracts/NibblVault.sol#487)
  - vaultImplementation = _vaultImplementation (contracts/NibblVaultFactory.sol#24)
  - feeTo = _feeTo (contracts/NibblVaultFactory.sol#25)
  - basketImplementation = _basketImplementation (contracts/NibblVaultFactory.sol#26)
  - pendingBasketImplementation = _newBasketImplementation (contracts/NibblVaultFactory.sol#100)
  - pendingFeeTo = _newFeeAddress (contracts/NibblVaultFactory.sol#124)
  - pendingVaultImplementation = _newVaultImplementation (contracts/NibblVaultFactory.sol#159)
  - implementation = address(_implementation) (contracts/Proxy/ProxyBasket.sol#20)
  - factory = address(_factory) (contracts/Proxy/ProxyVault.sol#20)

11. Unsafe use of transfer()/transferFrom() with IERC20

Some tokens do not implement the ERC20 standard properly but are still accepted by most code that accepts ERC20 tokens. For example Tether (USDT)'s transfer() and transferFrom() functions do not return booleans as the specification requires, and instead have no return value. When these sorts of tokens are cast to IERC20, their function signatures do not match and therefore the calls made, revert. Use OpenZeppelin’s SafeERC20's safeTransfer()/safeTransferFrom() instead

Bad:

IERC20(token).transferFrom(msg.sender, address(this), amount);

Good (using OpenZeppelin's SafeERC20):

import {SafeERC20} from "openzeppelin/token/utils/SafeERC20.sol";

// ...

IERC20(token).safeTransferFrom(msg.sender, address(this), amount);

Consider using safeTransfer/safeTransferFrom here:

Basket.sol:87:        IERC20(_token).transfer(msg.sender, IERC20(_token).balanceOf(address(this)));
Basket.sol:94:            IERC20(_tokens[i]).transfer(msg.sender, IERC20(_tokens[i]).balanceOf(address(this)));
NibblVault.sol:517:        IERC20(_asset).transfer(_to, IERC20(_asset).balanceOf(address(this)));
NibblVault.sol:526:            IERC20(_assets[i]).transfer(_to, IERC20(_assets[i]).balanceOf(address(this)));

12. Return values of transfer()/transferFrom() not checked

Not all IERC20 implementations revert() when there's a failure in transfer()/transferFrom(). The function signature has a boolean return value and they indicate errors that way instead. By not checking the return value, operations that should have marked as failed, may potentially go through without actually making a payment.

Bad:

IERC20(token).transferFrom(msg.sender, address(this), amount);

Good (using require):

bool success = IERC20(token).transferFrom(msg.sender, address(this), amount);
require(success, "ERC20 transfer failed");

Consider wrapping transfers in require() statements consistently here:

Basket.sol:87:        IERC20(_token).transfer(msg.sender, IERC20(_token).balanceOf(address(this)));
Basket.sol:94:            IERC20(_tokens[i]).transfer(msg.sender, IERC20(_tokens[i]).balanceOf(address(this)));
NibblVault.sol:517:        IERC20(_asset).transfer(_to, IERC20(_asset).balanceOf(address(this)));
NibblVault.sol:526:            IERC20(_assets[i]).transfer(_to, IERC20(_assets[i]).balanceOf(address(this)));

Alternatively, SafeERC20 could be used here, as stated before

13. Unused/empty receive() function

If the intention is for the Ether to be used, the function should call another function, otherwise it should revert

Proxy/ProxyBasket.sol:56:    receive() external payable {    }
Proxy/ProxyVault.sol:56:    receive() external payable {    }
Basket.sol:114:    receive() external payable {}
NibblVault.sol:585:    receive() external payable {}
NibblVaultFactory.sol:183:    receive() payable external {    }

14. Lack of event emission after critical initialize() functions

Similar issue in the past: here

To record the init parameters for off-chain monitoring and transparency reasons, please consider emitting an event after the initialize() functions:

Basket.sol:23:    function initialise(address _curator) external override initializer {

15. Prevent accidentally burning tokens

Transferring tokens to the zero address is usually prohibited to accidentally avoid "burning" tokens by sending them to an unrecoverable zero address.

Consider adding a check to prevent accidentally burning tokens here:

Basket.sol:37:        IERC721(_token).safeTransferFrom(address(this), _to, _tokenId);
Basket.sol:44:            IERC721(_tokens[i]).safeTransferFrom(address(this), _to, _tokenId[i]);
Basket.sol:54:        IERC721(_token).transferFrom(address(this), _to, _tokenId);
Basket.sol:64:        IERC1155(_token).safeTransferFrom(address(this), _to, _tokenId, _balance, "0");
Basket.sol:72:            IERC1155(_tokens[i]).safeTransferFrom(address(this), _to, _tokenIds[i], _balance, "0");
NibblVault.sol:389:        safeTransferETH(_to, _saleReturn); //send _saleReturn to _to
NibblVault.sol:458:        safeTransferETH(_to, _amount);
NibblVault.sol:468:        safeTransferETH(_to, _amtOut);
NibblVault.sol:478:        safeTransferETH(_to, _feeAccruedCurator);
NibblVault.sol:497:        IERC721(_assetAddress).safeTransferFrom(address(this), _to, _assetID);
NibblVault.sol:507:            IERC721(_assetAddresses[i]).safeTransferFrom(address(this), _to, _assetIDs[i]);
NibblVault.sol:517:        IERC20(_asset).transfer(_to, IERC20(_asset).balanceOf(address(this)));
NibblVault.sol:526:            IERC20(_assets[i]).transfer(_to, IERC20(_assets[i]).balanceOf(address(this)));
NibblVault.sol:538:        IERC1155(_asset).safeTransferFrom(address(this), _to, _assetID, balance, "0");
NibblVault.sol:549:            IERC1155(_assets[i]).safeTransferFrom(address(this), _to, _assetIDs[i], balance, "0");

16. _safeMint() should be used rather than _mint() wherever possible

_mint() is discouraged in favor of _safeMint() which ensures that the recipient is either an EOA or implements IERC721Receiver. Both open OpenZeppelin and solmate have versions of this function so that NFTs aren't lost if they're minted to contracts that cannot transfer them back out.

Basket.sol:6:import { ERC721, IERC721 } from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
Basket.sol:24:        _mint(_curator, 0);

17. abi.encodePacked() should not be used with dynamic types when passing the result to a hash function such as keccak256()

Similar issue in the past: here

Use abi.encode() instead which will pad items to 32 bytes, which will prevent hash collisions (e.g. abi.encodePacked(0x123,0x456) => 0x123456 => abi.encodePacked(0x1,0x23456), but abi.encode(0x123,0x456) => 0x0...1230...456). If there is only one argument to abi.encodePacked() it can often be cast to bytes() or bytes32() instead.

Utilities/EIP712Base.sol:47:                abi.encodePacked("\x19\x01", domainSeperator, messageHash)
NibblVaultFactory.sol:50:        _proxyVault = payable(new ProxyVault{salt: keccak256(abi.encodePacked(_curator, _assetAddress, _assetTokenID, _initialSupply, _initialTokenPrice))}(payable(address(this))));
NibblVaultFactory.sol:70:        bytes32 newsalt = keccak256(abi.encodePacked(_curator, _assetAddress, _assetTokenID,  _initialSupply, _initialTokenPrice));
NibblVaultFactory.sol:72:        bytes32 _hash = keccak256(abi.encodePacked(bytes1(0xff), address(this), newsalt, keccak256(code)));
NibblVaultFactory.sol:81:        address payable _basketAddress = payable(new ProxyBasket{salt: keccak256(abi.encodePacked(_curator, _mix))}(basketImplementation));
NibblVaultFactory.sol:89:        bytes32 newsalt = keccak256(abi.encodePacked(_curator, _mix));
NibblVaultFactory.sol:90:        bytes memory code = abi.encodePacked(type(ProxyBasket).creationCode, uint256(uint160(basketImplementation)));
NibblVaultFactory.sol:91:        bytes32 hash = keccak256(abi.encodePacked(bytes1(0xff), address(this), newsalt, keccak256(code)));

18. Upgradeable contract is missing a __gap[50] storage variable to allow for new storage variables in later versions

See this link for a description of this storage variable. While some contracts may not currently be sub-classed, adding the variable now protects against forgetting to add it in the future.

NibblVault.sol:20:contract NibblVault is INibblVault, BancorFormula, ERC20Upgradeable, Twav, EIP712Base {

19. All initialize() functions are front-runnable in the solution

Consider adding some access control to them or deploying atomically or using constructor initializer:

Basket.sol:23:    function initialise(address _curator) external override initializer {
NibblVault.sol:173:    function initialize(

20. Use a constant instead of duplicating the same string

Basket.sol:36:        require(_isApprovedOrOwner(msg.sender, 0), "withdraw:not allowed");
Basket.sol:42:        require(_isApprovedOrOwner(msg.sender, 0), "withdraw:not allowed");
Basket.sol:53:        require(_isApprovedOrOwner(msg.sender, 0), "withdraw:not allowed");
Basket.sol:62:        require(_isApprovedOrOwner(msg.sender, 0), "withdraw:not allowed");
Basket.sol:69:        require(_isApprovedOrOwner(msg.sender, 0), "withdraw:not allowed");
Basket.sol:79:        require(_isApprovedOrOwner(msg.sender, 0), "withdraw:not allowed");
Basket.sol:86:        require(_isApprovedOrOwner(msg.sender, 0), "withdraw:not allowed");
Basket.sol:92:        require(_isApprovedOrOwner(msg.sender, 0), "withdraw:not allowed");
NibblVault.sol:475:        require(msg.sender == curator,"NibblVault: Only Curator");
NibblVault.sol:486:        require(msg.sender == curator,"NibblVault: Only Curator");
NibblVault.sol:496:        require(msg.sender == bidder,"NibblVault: Only winner");
NibblVault.sol:505:        require(msg.sender == bidder,"NibblVault: Only winner");
NibblVault.sol:516:        require(msg.sender == bidder, "NibblVault: Only winner");
NibblVault.sol:524:        require(msg.sender == bidder, "NibblVault: Only winner");
NibblVault.sol:536:        require(msg.sender == bidder, "NibblVault: Only winner");
NibblVault.sol:546:        require(msg.sender == bidder, "NibblVault: Only winner");

21. Calculation doesn't match with comment

405:         // buyoutValuationDeposit = _currentValuation - ((primaryReserveBalance - fictitiousPrimaryReserveBalance) + secondaryReserveBalance); 
406:         buyoutValuationDeposit = msg.value - (_buyoutBid - _currentValuation);

Non-Critical Issues

1. Typos

  • function initialise (vs initialize)
Basket.sol:23:    function initialise(address _curator) external override initializer {
  • internall
Proxy/ProxyBasket.sol:26:     * This function does not return to its internall call site, it will return directly to the external caller.
Proxy/ProxyVault.sol:26:     * This function does not return to its internall call site, it will return directly to the external caller.
  • reenterancy
NibblVault.sol:125:    ///@notice reenterancy guard
  • pausablity
NibblVault.sol:152:    /// @dev pausablity implemented in factory
  • primaryReseveRatio
NibblVault.sol:200:        //curator fee is proportional to the secondary reserve ratio/primaryReseveRatio i.e. initial liquidity added by curator
NibblVault.sol:201:        curatorFee = (((_secondaryReserveRatio - MIN_SECONDARY_RESERVE_RATIO) * MIN_CURATOR_FEE) / (primaryReserveRatio - MIN_SECONDARY_RESERVE_RATIO)) + MIN_CURATOR_FEE; //curator fee is proportional to the secondary reserve ratio/primaryReseveRatio i.e. initial liquidity added by curator
  • seconday
NibblVault.sol:263:    /// @dev Valuation = If current supply is on seconday curve we use secondaryReserveBalance and secondaryReserveRatio to calculate valuation else we use primary reserve ratio and balance
  • Continous
NibblVault.sol:250:    /// @dev The max continous tokens on SecondaryCurve is equal to initialTokenSupply
NibblVault.sol:270:    /// @param _amount amount of reserve tokens to buy continous tokens
NibblVault.sol:282:    /// @param _amount amount of reserve tokens to buy continous tokens
NibblVault.sol:359:    /// @param _amtIn Continous Tokens to be sold
  • recieve
NibblVault.sol:361:    /// @param _to Address to recieve the reserve token to
  • airdops
NibblVault.sol:512:    /// @notice ERC20s can be accumulated by the underlying ERC721 in the vault as royalty or airdops 
NibblVault.sol:531:    /// @notice ERC1155s can be accumulated by the underlying ERC721 in the vault as royalty or airdops 

2. Deprecated library used for Solidity >= 0.8 : SafeMath

NibblVaultFactory.sol:3:pragma solidity 0.8.10;
NibblVaultFactory.sol:9:import { SafeMath } from  "@openzeppelin/contracts/utils/math/SafeMath.sol";"

3. Commented code

File: NibblVault.sol
321:                 // _purchaseReturn = _buySecondaryCurve(_to, _lowerCurveDiff);
322:                 _purchaseReturn += _buyPrimaryCurve(msg.value - _lowerCurveDiff, _totalSupply + _purchaseReturn);
File: NibblVault.sol
382:                 // _saleReturn = _sellPrimaryCurve(_tokensPrimaryCurve);
383:                 _saleReturn += _sellSecondaryCurve(_amtIn - _tokensPrimaryCurve, _initialTokenSupply);

4. Missing friendly revert strings

NibblVaultFactory.sol:114:        require(_success);

5. Use a more recent version of solidity

From solidity version of at least 0.8.4 , you can use bytes.concat() instead of abi.encodePacked(<bytes>,<bytes>)
Use a solidity version of at least 0.8.12 to get string.concat() instead of abi.encodePacked(<str>,<str>)

Utilities/EIP712Base.sol:3:pragma solidity 0.8.10;
Utilities/EIP712Base.sol:47:                abi.encodePacked("\x19\x01", domainSeperator, messageHash)
NibblVaultFactory.sol:3:pragma solidity 0.8.10;
NibblVaultFactory.sol:50:        _proxyVault = payable(new ProxyVault{salt: keccak256(abi.encodePacked(_curator, _assetAddress, _assetTokenID, _initialSupply, _initialTokenPrice))}(payable(address(this))));
NibblVaultFactory.sol:70:        bytes32 newsalt = keccak256(abi.encodePacked(_curator, _assetAddress, _assetTokenID,  _initialSupply, _initialTokenPrice));
NibblVaultFactory.sol:71:        bytes memory code = abi.encodePacked(type(ProxyVault).creationCode, uint256(uint160(address(this))));
NibblVaultFactory.sol:72:        bytes32 _hash = keccak256(abi.encodePacked(bytes1(0xff), address(this), newsalt, keccak256(code)));
NibblVaultFactory.sol:81:        address payable _basketAddress = payable(new ProxyBasket{salt: keccak256(abi.encodePacked(_curator, _mix))}(basketImplementation));
NibblVaultFactory.sol:89:        bytes32 newsalt = keccak256(abi.encodePacked(_curator, _mix));
NibblVaultFactory.sol:90:        bytes memory code = abi.encodePacked(type(ProxyBasket).creationCode, uint256(uint160(basketImplementation)));
NibblVaultFactory.sol:91:        bytes32 hash = keccak256(abi.encodePacked(bytes1(0xff), address(this), newsalt, keccak256(code)));
@code423n4 code423n4 added bug Something isn't working QA (Quality Assurance) Assets are not at risk. State handling, function incorrect as to spec, issues with clarity, syntax labels Jun 24, 2022
code423n4 added a commit that referenced this issue Jun 24, 2022
@mundhrakeshav mundhrakeshav added sponsor acknowledged Technically the issue is correct, but we're not going to resolve it for XYZ reasons sponsor disputed Sponsor cannot duplicate the issue, or otherwise disagrees this is an issue and removed sponsor acknowledged Technically the issue is correct, but we're not going to resolve it for XYZ reasons labels Jun 26, 2022
@HardlyDifficult
Copy link
Collaborator

Merging with #127

@HardlyDifficult
Copy link
Collaborator

Lots of good & relevant feedback here. Good report format.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working QA (Quality Assurance) Assets are not at risk. State handling, function incorrect as to spec, issues with clarity, syntax sponsor disputed Sponsor cannot duplicate the issue, or otherwise disagrees this is an issue
Projects
None yet
Development

No branches or pull requests

3 participants