Munchables
Game Contracts

Munchables is an on-chain game where players earn points by feeding, petting and hatching their Munchables. We reviewed the game contracts, including the migration of NFTs from the previous version.
report id
0236
category
Token & RWA
language
Solidity
final report
May 30, 2024
lines of code
4756
Content

Download audit report

1

Executive Summary

This document outlines the security review conducted by Nethermind for the Munchables protocol implementation. Munchables is a GameFi protocol where users aim to accumulate as many points as they can though a variety of actions such as feeding, petting, hatching primordials and managing their Snuggery. This Munchables implementation supports migrating NFTs from a previous version of the game, allowing existing users to keep their original Munchable NFTs.

The audit was performed using (a) manual analysis of the codebase, (b) automated analysis tools, (c) simulation of the smart contract, and (d) creation of test cases. Along with this document, we report 37 points of attention, where 1 is classified as Critical, 7 are classified as High, 6 are classified as Medium, 6 are classified as Low, 10 are classified as Info and 7 are classified as Best Practices.

Audit assessment
Audit TypeSecurity Review
Initial ReportMay 27, 2024
Response from ClientMay 28, 2024
Final ReportMay 30, 2024
Repositorymunchablesorg/munchables-common-core
Commit (Audit)5f3087a78e
Commit (Final)2056e1c58d
Documentation AssessmentHigh
Test Suite AssessmentHigh
Total findings
37
Fixed
30
Acknowledged
7
Mitigated
0
Unresolved
0

Findings by severity

  • Critical1
  • High7
  • Medium6
  • Low6
  • Informational10
  • Best Practices7

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1src/proxy/ProxyFactory.sol9111.1%212
2src/config/BaseConfigStorage.sol7311.4%1488
3src/config/ConfigStorage.sol295196.4%48362
4src/config/BaseConfigStorageUpgradeable.sol1815.6%423
5src/managers/BaseBlastManager.sol8367.2%15104
6src/managers/LockManager.sol3824211.0%66490
7src/managers/ClaimManager.sol20452.5%35244
8src/managers/SnuggeryManager.sol267228.2%55344
9src/managers/MigrationManager.sol33130.9%44378
10src/managers/BonusManager.sol22773.1%26260
11src/managers/RewardsManager.sol17042.4%26200
12src/managers/MunchadexManager.sol11510.9%15131
13src/managers/AccountManager.sol312196.1%46377
14src/managers/BaseBlastManagerUpgradeable.sol2214.5%326
15src/managers/PrimordialManager.sol12586.4%33166
16src/managers/NFTAttributeManagerV1.sol16353.1%29197
17src/distributors/FundTreasuryDistributor.sol3912.6%848
18src/libraries/MunchablesCommonLib.sol14732.0%23173
19src/overlords/NFTOverlord.sol373318.3%71475
20src/tokens/OldMunchNFT.sol1698147.9%31281
21src/tokens/MunchToken.sol25416.0%534
22src/tokens/MunchNFT.sol11821.7%15135
23src/tokens/TestERC20Token.sol24416.7%634
24src/rng/RNGProxySelfHosted.sol1417.1%318
25src/rng/BaseRNGProxy.sol4012.5%1455
26src/rng/RNGProxyAPI3.sol4836.2%859
27src/interfaces/IBlast.sol971111.3%11119
28src/interfaces/ILockManager.sol117125106.8%57299
29src/interfaces/IMunchNFT.sol68133.3%317
30src/interfaces/IMigrationManager.sol805771.2%25162
31src/interfaces/INFTAttributesManager.sol523465.4%17103
32src/interfaces/IConfigStorage.sol16974.1%34210
33src/interfaces/IHoldsGovernorship.sol4375.0%18
34src/interfaces/IClaimManager.sol922527.2%12129
35src/interfaces/ISnuggeryManager.sol6171116.4%28160
36src/interfaces/IConfigNotifiable.sol5120.0%28
37src/interfaces/IMunchadexManager.sol28828.6%339
38src/interfaces/IPrimordialManager.sol271659.3%1558
39src/interfaces/IBaseBlastManager.sol4125.0%16
40src/interfaces/IRNGProxy.sol20525.0%328
41src/interfaces/IMunchToken.sol4250.0%17
42src/interfaces/IBonusManager.sol16318.8%524
43src/interfaces/IDistributor.sol9333.3%315
44src/interfaces/INFTOverlord.sol746587.8%26165
45src/interfaces/IAccountManager.sol8393112.0%36212
46src/interfaces/IRNGProxySelfHosted.sol4125.0%16
47src/interfaces/IRewardsManager.sol1119.1%517
Total475681617.2%9346506

3

Summary of Issues

#FindingSeverityUpdate
1Malicious caller can migrate other player’s NFTs to their addressCriticalFixed
2Account registration can be blocked by adding future user as sub-accountHighFixed
3Downcast can reduce number of unrevealed NFTs to be mintedHighFixed
4Function _calculateLevelBonus(...) reverts with a Snuggery length more than 10HighFixed
5Loss of precision in _claimPointsHighFixed
6Players cannot spend pointsHighFixed
7USDPrice cannot be updated in the lockManagerHighFixed
8User cannot export non-zero-chonk Munchables from their SnuggeryHighFixed
9A max reveal queue greater than one will overwrite existing reveal dataMediumFixed
10Player can pet their own MunchablesMediumFixed
11Player lock durations can be less than the default minimumMediumFixed
12Players can mint multiple munchables for the same primordialMediumFixed
13Players can reduce their asset unlock timeMediumFixed
14The function getSnuggery reverts with the index out of bounds errorMediumFixed
15Any user can access the full migration bonusLowFixed
16Function getFullPlayerData may not return accurate Snuggery dataLowFixed
17MunchNFT contract’s pause mechanism is unreachableLowFixed
18The last entry in a user’s sub-account array cannot be removedLowFixed
19Thresholds can be updated while a proposal is in progressLowFixed
20User can set their own address as a referrerLowFixed
21A price proposal can be both approved and disapprovedInfoFixed
22Double approval account check when approving USD priceInfoAcknowledged
23Duplicate notifiable addresses and handled differently in add/removalInfoAcknowledged
24Non configured but active tokens result in division by zeroInfoFixed
25Primordials can be fed after hatchingInfoFixed
26Redundant loop in function addSubAccountInfoAcknowledged
27The same spray proposal can be executed multiple timesInfoFixed
28Unnecessary storage write when player chonks haven’t changedInfoAcknowledged
29Wrong error message in burnUnrevealedForPoints(...)InfoFixed
30tokenLocked can be overwritten during migration snapshot loadingInfoAcknowledged
31Common storage does not have provision for additional features in futureBest PracticesAcknowledged
32Lock pragmas to specific compiler versionBest PracticesFixed
33Migration data token ID should not be zeroBest PracticesFixed
34Missing _disableInitializers(...) function in upgradeable contractsBest PracticesFixed
35Redundant inheritanceBest PracticesFixed
36Unused importsBest PracticesAcknowledged
37Use of legacy call to transfer native tokensBest PracticesFixed

4

System Overview

This section presents basic concepts on the game Munchables and a system overview of the audited contracts.

4.1 Munchables

The game involves earning MUNCH points by owning and managing Munchables (NFTs). Players feed their own and pet others’ Munchables and refer more players to earn points. Each Munchable is a different creature and has multiple distinct attributes that impact the balance of the game. Players can obtain a Munchable by migrating from season 1, locking up funds, buying one on the open market, or minting and leveling up a primordial to hatch a new Munchable. Players use their Snuggery, a customizable home, to manage up to 6 Munchables, but they can convert points to increase the number of slots. Players import their Munchables in their Snuggery to feed them Schnibbles. The allocated number of Schnibbles is based on how much a player has locked and if the player has a migration bonus. The impact of Schnibbles varies when fed to Munchables, converting into Chonks (XP). As Munchables reach new Chonk thresholds, they level up, enhancing their stats and evolving into new forms.

4.2 High Level Visual Overview of Munchables

The component diagram in Fig. 2 presents the structural design of the protocol. This diagram shows the relationship between the different components of the system. A component diagram allows developers to group contracts based on a common purpose so that others can examine a software project at a high level. This audit consists of 22 smart contracts and 1 (one) library. The package config relies on the contracts responsible for storing all information throughout the Munchables protocol.

1 Package config - this package relies on the contracts responsible for managing central functionalities throughout the Munchables protocol.

a . ConfigStorage: The central storage location for the Munchables protocol. All other contracts inherit an abstract contract that allows them to interact with the config storage contract to query protocol data such as important addresses, RNG data for attribute generation, point multipliers and much more. Storage data can be modified on the config storage contract, and the changes will be reflected across the protocol.

b . BaseConfigStorage: Every other contract in the system inherits this contract that handles the initialization and connection to the ConfigStorage.

2 Package managers - this package contains most of the system’s contracts. These contracts depend on the config package since they inherit BaseConfigStorage. Particularly, provide the game functionalities that interface with external-facing actions, such as locking up funds, importing Munchables into the Snuggery, feeding Munchables, etc. The contracts are presented below:

a . AccountManager: Handles new player registration for both main-accounts and sub-accounts. Other contracts within the Munchables protocol query the account manager to get the main account associated with a given caller address. The schnibble spray proposal and execute mechanism is also implemented in this contract.

b . BonusManager: Contains all functions necessary for bonus calculations, including feed bonuses, harvest bonuses and pet bonuses. These bonuses can be affected by migrations, lock duration, Munchable levels, referrals and the Munchadex.

c . ClaimManager: Handles all logic related to claiming points, as well changing to the next period. Points can be manually claimed or force claimed when other interactions in the protocol are done. Points can be converted into munch tokens.

d . LockManager: Users lock their funds on this contract in exchange for Munchable NFTs. Three different assets are accepted: WETH, USDB, and native Ether. The USD price proposal system is managed on this contract as well, using a voting system controlled by privileged addresses.

e . MigrationManager: Logic for supporting the migration of Season 1 Munchables over to the new implementation. The admin will upload a snapshot containing all previous player data, and users can migrate their NFTs over, burning their old and minting a new replacement in the process.

f . MunchadexManager: Tracks the circulation on Munchables based on attributes and stats such as by realm and rarity, also tracking the unique counts.

g . NFTAttributesManagerV1: Stores the attributes associated with each unique Munchable. Keeping the attributes logic separate from the actual Munchable ERC721 contract was a design choice by the Munchables team to allow for modularity, in case changes need to be made in the future.

h . PrimordialManager: Handles the claiming, feeding, levelling and hatching of Primordials, an alternative pathway to a Munchable without having to lock assets.

i . RewardsManager: Handles blast yield claiming and gas fee claiming.

j . SnuggeryManager: Logic for placing Munchables in the Snuggery including importing, exporting, feeding, petting and increasing the snuggery size.

3 Package tokens - consists of contracts that implement ERC-20 and ERC-721.

a . MunchNFT: The Munchable NFT contract, an ERC-721 implementation with token IDs that increment starting at ID of 1.

4 Package overlords - this contract contains a single contract described below:

a . NFTOverlord: Used for creating and revealing Munchables both through assets locks and primordials. Will use RNG data to generate attributes which are passed and stored on the NFT attributes manager contract.

5 Package rng - contains two smart contracts to request random numbers:

a . RNGProxyAPI3: The primary RNG contract, where the source of the randomness is API3. This is the default RNG contract, with a backup RNG source in case the randomness source needs to be changed.

b . RNGProxySelfHosted: Exists as a backup RNG source, in case the API3 RNG source stops behaving correctly. This source of randomness is centralized, but can be used in emergency situations.

4.3 Centralization risks

This section of the report will highlight centralization risks that are present within the protocol. It should be noted that the Munchables team has indicated that they will be using a multisig wallet to ensure that privileged access is controlled and used correctly to mitigate risks.

The USD price of the lockable assets are set by privileged roles: The price of lockable assets which are used to mint Munchables are set by addresses with the PriceFeed role instead of using a more common asset pricing mechanism such as an oracle. The PriceFeed addresses will submit a price proposal which can be voted on. Once the threshold of "for" votes is met, the new price will be accepted, or in the case of "against" votes, the proposal will be discarded. Although a voting process exists, the pricing mechanism for assets is more centralized than relying on an oracle. The admin can also directly overwrite the price using the configureToken function, bypassing any proposals. Additionally, the price updates will be less common, so during the time windows between price updates, the USD price of assets may be stale and when users are locking assets, meaning the users may not be paying the correct amount.

All protocol storage is tracked in one contract: The Munchables protocol consists of many contracts, but they all refer to a single contract ConfigStorage to query storage. This contract uses enum inputs as keys to store fixed size types and dynamic types like arrays. All storage can be written or overwritten directly by the admin affecting the protocol as a whole. In traditional protocol structures where storage is managed on the same contract, allowing for input validation when setting parameters, it is not possible to add input validation using the central storage approach in ConfigStorage. This allows the admin to place the protocol in invalid states by setting storage data such that depending contracts may fail once data has been queried. For example setting an important address to zero, causing contract calls to fail.

Infinite Schnibbles spraying: Schnibbles can be sent to any address through a proposal and execute mechanism, requiring the role "Social" to propose and "SocialApproval" to execute. There are no limits on the amount of Schnibbles that can be sprayed, nor the frequency at which the proposals are executed. The addresses assigned to the "Social" and "SocialApproval" roles are able to create and distribute Schnibbles to any address.

RNG oracle can fallback to self hosted with manual inputs: By default the RNG source will be an API3 RNG oracle, which is a decentralized source of randomness. As a backup feature, the Munchables protocol has a self hosted RNG oracle where a privileged role "NFTOracle" can set the random output to be any fixed value. There is potential for preferential treatment or ensuring specific outputs to lead to certain attributes in a minted Munchable.

5

Risk Rating Methodology

The risk rating methodology used by Nethermind Security follows the principles established by the OWASP Foundation. The severity of each finding is determined by two factors: Likelihood and Impact.

Likelihood measures how likely the finding is to be uncovered and exploited by an attacker. This factor will be one of the following values:

  1. High: the issue is trivial to exploit and has no specific conditions that need to be met;
  2. Medium: the issue is moderately complex and may have some conditions that need to be met;
  3. Low: the issue is very complex and requires very specific conditions to be met.

When defining the likelihood of a finding, other factors are also considered. These can include but are not limited to motive, opportunity, exploit accessibility, ease of discovery, and ease of exploit.

Impact is a measure of the damage that may be caused if an attacker exploits the finding. This factor will be one of the following values:

  1. High: the issue can cause significant damage, such as loss of funds or the protocol entering an unrecoverable state;
  2. Medium: the issue can cause moderate damage, such as impacts that only affect a small group of users or only a particular part of the protocol;
  3. Low: the issue can cause little to no damage, such as bugs that are easily recoverable or cause unexpected interactions that cause minor inconveniences.

When defining the impact of a finding, other factors are also considered. These can include but are not limited to data and state integrity, loss of availability, financial loss, and reputation damage. After defining the likelihood and impact of an issue, the severity is determined according to the table below.

Impact / LikelihoodLowMediumHigh
HighMediumHighCritical
MediumLowMediumHigh
LowInfo / Best PracticesLowMedium
UndeterminedUndeterminedUndeterminedUndetermined

To address issues that do not fit a High, Medium or Low severity, Nethermind Security also uses three more finding severities: Informational, Best Practices, and Undetermined.

  1. Informational findings do not pose any risk to the application, but they carry some information that the audit team intends to pass to the client formally;
  2. Best Practice findings are used when some piece of code does not conform with smart contract development best practices;
  3. Undetermined findings are used when we cannot predict the impact or likelihood of the issue.

6

Issues

6.1 Malicious caller can migrate other player’s NFTs to their address

FileFix commitTypeStatus
src/managers/MigrationManager.sol—CriticalFixed

When users want to migrate all their locked NFTs, they call the function migrateAllNFTs. This will migrate a user’s NFTs in batches of five per call, and importantly, this function can be called by anyone. A snippet from the function is shown below:

function migrateAllNFTs(address _user, uint32 _skip) external override {
if (_userLockedAction[_user] != UserLockedChoice.LOCKED_FULL_MIGRATION)
// ...
_migrateNFTs(_user, _userLockedAmounts[_user].tokenLocked, tokenIds);
}

When migrateAllNFTs is called, the internal function _migrateNFTs will be invoked, which loops through the array of tokenIds to verify migration snapshot data, and mint the new token. As shown below, the mint is done through NFTOverlord.mintForMigration, with the msg.sender passed as the owner of the new token.

function _migrateNFTs(...) internal {
// ...
for (; i < tokenIds.length; i++) {
// Snapshot validations done here
// ...

// @audit Caller will be owner, callable by anyone
// Caller isn't guaranteed to be original owner
newTokenIds[i] = _nftOverlord.mintForMigration(
msg.sender,
snapshot.attributes,
snapshot.immutableAttributes,
snapshot.gameAttributes
);

migratedTokenIds[i] = snapshot.tokenId;
_oldNFTContract.burn(tokenId);
}
// ....
}

Since msg.sender is used as the argument for the new owner, and the function is callable by anyone, it is possible to steal migration tokens from other users.

Recommendation

Consider changing the input in mintForMigration from msg.sender to the _user argument to prevent migration tokens from being stolen by other users.

Resolution

Fix in pull request #179, commit hash cd1f4b0.

6.2 Account registration can be blocked by adding future user as sub-account

FileFix commitTypeStatus
AccountManager.sol—HighFixed

The function register is used to add a new main-account to the protocol and initialize necessary storage such as registration date, unfed Schnibbles and referrer. There is a check which will revert execution if the caller is already a sub-account, to prevent an address from being both a sub-account and main-account at the same time. This check is shown below:

function register(...) external /* ... */ {
if (mainAccounts[msg.sender] != address(0))
revert SubAccountCannotRegisterError();
// ...
}

When adding a new sub-account, there are no guarantees that the caller has any control over the sub-account they are assigning to their main-account. A malicious user can add victim addresses as a sub-account before the victim is able to call register themselves, and they will no longer be able to register or interact with the protocol. The addSubAccount function is shown below:

function addSubAccount(address _subAccount) external /* ... */ {
if (mainAccounts[_subAccount] != address(0))
revert SubAccountAlreadyRegisteredError();

// @audit The `_subAccount` address may not belong to the caller
// and could be any arbitrary address, including future users

mainAccounts[_subAccount] = msg.sender;

for (uint256 i; i < subAccounts[msg.sender].length; i++) {
if (subAccounts[msg.sender][i] == _subAccount)
revert SubAccountAlreadyRegisteredError();
}

subAccounts[msg.sender].push(_subAccount);
// ...
}

Given that these contracts will be deployed on the Blast Network which is based on the OP Stack, there is no public mempool to watch for registration activity to frontrun. However, historical interactions with the previous Munchables implementation can be analyzed to find all existing users. This data can then be used to prevent registration from all original Munchables users.

Recommendation

Consider implementing a mechanism to ensure that a given address permits being assigned as a sub-account to some main-account address. This will prevent arbitrary addresses from being added as a sub-account without permission.

Resolution

PR #179, commit hash 5694d94. In this hash, I basically made it so that when you are registering, if you are a subaccount of another main account, it automatically removes you as a subaccount and allows you to continue forward with registering. Don’t think it’s necessary to have an additional signing tx as long as there is nothing else that is limiting the actions of a user.

6.3 Downcast can reduce number of unrevealed NFTs to be minted

FileFix commitTypeStatus
LockManager.sol—HighFixed

When a user locks their assets, they receive some number of unrevealed NFTs based on the nftCost for the given asset. While locking assets, the internal function _lock is called, which calculates the unrevealed NFT count and makes a call to NFTOverlord.addReveal to update the unrevealed NFT count for the user. A snippet from the _lock function is shown below:

function _lock(...) private {
// ...
if (...) {
// ...
remainder = quantity % configuredToken.nftCost;
numberNFTs = (quantity - remainder) / configuredToken.nftCost;

// @audit The `numberNFTs` is downcast to uint8
// This downcast can lead to information loss
nftOverlord.addReveal(_lockRecipient, uint8(numberNFTs));
}
// ...
}

If a user locks enough assets such that the numberNFTs is calculated to be greater than 255, when it is downcast to a uint8 for the call to addReveal some bits may be truncated, causing the user to receive less unrevealed NFTs than they have paid for. An example is shown below:

// 255 is  11111111
// 256 is 100000000, when downcast to uint8 is 00000000
uint8(uint256(255)) == 255
uint8(uint256(256)) == 0

Recommendation

Consider changing the argument type for _quantity in addReveal to be a uint16, and add input validation in _lock to ensure that no value will be lost when downcasting from uint256 to uint16.

Resolution

PR #179 commit hash 22d1c1f. Used recommendation.

6.4 Function _calculateLevelBonus(...) reverts with a Snuggery length more than 10

FileFix commitTypeStatus
BonusManager.sol—HighFixed

The function _calculateLevelBonus(...) calculates level bonus in two scenarios:

1. Everytime the player wants to calculate Schnibbles to distribute and credit to unfed Schnibbles and; 2. When a user adds to their lock to force claim at the previous locked value;

function _calculateLevelBonus(address _caller) internal view
returns (uint256 _levelBonus) {
(
,
MunchablesCommonLib.Player memory player,
MunchablesCommonLib.SnuggeryNFT[] memory _snuggery,
uint256 _snuggerySize
) = _accountManager.getFullPlayerData(_caller);
if (_snuggerySize > 0) {
uint i;
// @audit _snuggerySize can be greater than _snuggery length
for (; i < _snuggerySize; i++) {
_levelBonus += _nftAttributesManager
.getAttributes(_snuggery[i].tokenId)
.level;
}
// ...
}
}

The function invokes _accountManager.getFullPlayerData(...) to get the first 10 munchables in the snuggery and the length of the player snuggery to calculate level bonus. Then, _calculateLevelBonus(...) loops _snuggery to sum the level of each munchable. However, the variable _snuggerySize value can be greater than the _snuggery length, causing an index out of bounds error.

Recommendation

Set the upper limit in the loop to the _snuggery length.

Resolution

We removed pagination all together and set a global maximum for snuggery size in these two commits: 63906fc8366dd48bf17bcdff151059cf32c53594, 1e6d63c67e967ab000036aaf4b7151299158b2fe.

6.5 Loss of precision in _claimPoints

FileFix commitTypeStatus
ClaimManager.sol—HighFixed

The internal function _claimPoints is used to calculate and update the number of points that a player should receive. The claimAmount is calculated by dividing the player’s total chonk count by the global total chonk, and then multiplying by the available points, as shown below:

uint256 claimAmount = (snuggeryManager.getTotalChonk(_player) /
currentPeriod.globalTotalChonk) * availablePoints;

Dividing and then multiplying values can lead to loss of precision. In this case since the player chonk count will always be less than the global chonk count, this will always result in a claimAmount of zero, meaning users will never be able to claim points. Consider the example below:

totalPlayerChonk = 200
totalGlobalChonk = 300
availablePoints = 456
// Results in...
(200 / 300) * 456 == 0
// Expected result was 304

Recommendation

Multiply the player total chonk count by the available points before division.

uint256 claimAmount = (snuggeryManager.getTotalChonk(_player) *
availablePoints) / currentPeriod.globalTotalChonk;

Resolution

Resolved here.

6.6 Players cannot spend points

FileFix commitTypeStatus
SnuggeryManager.sol—HighFixed

Players can call the function increaseSnuggerySize to exachange their points towards buying additional snuggery space. This function will invoke ClaimManager.spendPoints to verify and adjust their points balance before the snuggery size is increased. The function is shown below:

function increaseSnuggerySize(uint8 _quantity) external notPaused {
// ...

uint16 previousSize = _player.maxSnuggerySize;
uint256 pointsCost = NEW_SLOT_COST * uint256(_quantity);

// @audit The function spendPoints(...) can be called only by ClaimManager
claimManager.spendPoints(_caller, pointsCost);

_player.maxSnuggerySize += uint16(_quantity);

// ...
}

The function ClaimManager.spendPoints has a modifier which only allows it to be called by the ClaimManager contract, which itself. As a result, the function increaseSnuggerySize will always revert and users are not able to spend their points. The function is presented below:

function spendPoints(
address _player,
uint256 _spendPoints
) external override onlyConfiguredContract(StorageKey.ClaimManager) {
// @audit The modifier will not allow call from SnuggeryManager
if (_points[_player] < _spendPoints) revert NotEnoughPointsError();
_points[_player] -= _spendPoints;
emit PointsSpent(_player, _spendPoints);
}

Recommendation

Consider changing the modifier to allow a call from the SnuggeryManager contract.

Resolution

Resolved here.

6.7 USDPrice cannot be updated in the lockManager

FileFix commitTypeStatus
LockManager.sol—HighFixed

The USD price is maintained in the LockManager manually through a proposal and approval framework. The "pricefeed" roles have entitlements to propose a revised USD Price which will then be approved by other with similar role. The USD price update is submitted as a proposal using the structure below. Note the mapping for approvals and disapprovals:

struct USDUpdateProposal {
uint32 proposedDate;
address proposer;
address[] contracts;
uint256 proposedPrice;
mapping(address => bool) approvals;
mapping(address => bool) disapprovals;
uint8 approvalsCount;
uint8 disapprovalsCount;
}

When a struct contains a storage mapping, deleting the struct does not delete the entries inside the mapping. So, if the structure is again reused, there is a risk of stale data being used in subsequent interactions. When the USD price proposal is submitted by address 0x1234, the approvals mapping for 0x1234 is flagged as true.

usdUpdateProposal.approvals[msg.sender] = true;

Assuming that the proposal hits the threshold to update the USD price and is executed, post execution, the proposal is deleted as below in _execUSDPriceUpdate. The delete will not be able to clear the mapping entries and hence, 0x1234 will remain in the approvals mapping.

function _execUSDPriceUpdate() internal {
if (
usdUpdateProposal.approvalsCount >= APPROVE_THRESHOLD &&
usdUpdateProposal.disapprovalsCount < DISAPPROVE_THRESHOLD
) {
// ...
delete usdUpdateProposal;
}
}

As the next USD price proposal is submitted, 0x1234 will not be able to approve it because of the following condition in approveUSDPrice since the delete did not clear the mapping entry and hence, it will be accounted as already approved.

if (usdUpdateProposal.approvals[msg.sender])
revert ProposalAlreadyApprovedError();

This means that once a given address approved or disapproved a proposal, any interactions on following proposals will revert, effectively preventing the USD price updates.

Recommendation

Consider using an array to track votes, or change to a nested mapping in the struct to include the proposal round. This will ensure that previous votes won’t remain on a new proposal.

Resolution

Fixed in commit 8b3891d155d4c66e82818eb0381218c495542ea3.

6.8 User cannot export non-zero-chonk Munchables from their Snuggery

FileFix commitTypeStatus
SnuggeryManager.sol—HighFixed

The modifier chonkUpdated is used to update the player and global chonk count whenever the functions feed, importMunchable, or exportMunchable are called. After the main function logic has executed, the modifier will invoke the internal function _recalculateChonks to determine how the player’s chonk count has changed, and reflect that difference on the global chonk count, as shown below:

function _recalculateChonks(address _player) internal {
uint256 previousChonks = playerChonks[_player];
uint256 _playerChonks;
for (uint256 i; i < snuggeries[_player].length; i++) {
_playerChonks += nftAttributesManager
.getAttributes(snuggeries[_player][i].tokenId)
.chonks;
}
playerChonks[_player] = _playerChonks;

if (previousChonks != _playerChonks) {
// @audit When Munchable exported the previousChonks is greater than _playerChonks
// This will lead to an overflow error, transaction will revert
totalGlobalChonk += (_playerChonks - previousChonks);
}
}

When a Munchable is exported using exportMunchable, the chonk count of the player’s snuggery will decrease (assuming the exported Munchable has a non-zero chonk count). The global chonk count is increased by the difference in player chonks: _playerChonks previousChonks. On a call to exportMunchable the _playerChonks will be less than the previousChonks, causing an overflow and reverting the transaction. This prevents any Munchable with a non-zero chonk count from being exported.

Recommendation

Consider changing the global chonk count calculation to handle cases where the player’s new chonk count is less than their previous count:

if (previousChonks != _playerChonks) {
totalGlobalChonk = (totalGlobalChonk + _playerChonks) - previousChonks;
}

Resolution

Fix at commit hash: 738fc47

6.9 A max reveal queue greater than one will overwrite existing reveal data

FileFix commitTypeStatus
BaseRNGProxy.sol—MediumFixed

The process of revealing a new Munchable is done in two stages, the startReveal which is initiated by the user, and then the reveal which is initiated by the API3 RNGProxy. There is a storage variable MAX_REVEAL_QUEUE which limits the number of unrevealed NFTs that can be in the reveal queue. This is set to a default of 1, with plans to be increased post-deployment. All the logic inside of the NFTOverlord contract behaves correctly with any value of MAX_REVEAL_QUEUE however, the tracked RNG requests in the BaseRNGProxy implementation are not able to track unique requests from the same main-account.

function requestRandom(
address _contract,
bytes4 _selector,
uint256 _index
) public virtual onlyConfiguredContract(StorageKey.NFTOverlord) {
// @audit The `_index` key is the user address, not unique on multiple requests
// Each new request will overwrite the last, and the associated NFT will be lost
requests[_index] = RequestData({
targetContract: _contract,
selector: _selector
});
emit RandomRequested(_contract, _selector, _index);
}

As shown above, the _index argument is calculated as uint256(uint160(useraddress)) which means multiple requests from the same user will have the same value. This will lead to the same mapping storage slot being written to, overwriting previous request data. Once a pending request has been overwritten, the NFT associated with that request will be permanently lost, due to the following check in the _callback function:

function _callback(uint256 _index, bytes calldata _rand) internal {
RequestData storage data = requests[_index];
// @audit Only the latest non-overwritten reveal will work, then that slot is deleted
if (data.targetContract == address(0)) revert NoRequestError();
// ...
delete requests[_index];
}

Recommendation

Consider calculating _index as the hash of the address and another unique field that will allow for unique keys for reveals that came from the same address. For the API3 RNGProxy this could be the requestID. Alternatively to ensure compatibility with the self-hosted RNGProxy a nonce system could be implemented in the base RNG implementation instead.

Resolution

PR #179, commit hash 5d918ff. We prepend a nonce. The index for rng (self hosted and api3) is a uint256 but we only need 160 bits for the address so nonce is prepended when converting address to uint256 and then silently discarded when it is converted back to a uint160.

6.10 Player can pet their own Munchables

FileFix commitTypeStatus
SnuggeryManager.sol—MediumFixed

Players can call the function pet in order to pet another player’s Munchable, giving both them and the recipient Schnibbles in the process. The function will recover the main account of the caller, and check the owner of the munchable to be pet to ensure that the caller is not the owner of the Munchable. This is done to prevent petting your own Munchable, however the check done is owner == msg.sender instead of owner == _mainAccount. As a result, it is possible to pet your own Munchables through a sub-account.

function pet(uint256 _tokenId) external notPaused {
(
address _mainAccount,
MunchablesCommonLib.Player memory _player
) = _getMainAccountRequireRegistered(msg.sender);

// @audit owner is the main account of the NFT's owner
address owner = IERC721(munchNFT).ownerOf(_tokenId);

(
address _owner,
MunchablesCommonLib.Player memory _ownerPlayer
) = _getMainAccountRequireRegistered(owner);

// ...

// @audit Should check that owner == _mainAccount
// Caller could be subaccount and will pass check
if (owner == msg.sender) revert CannotPetOwnError();
// ...
}

Recommendation

Consider changing the check to msg.sender == _mainAccount to prevent player’s from petting their own Munchables via a subaccount.

Resolution

Fixed in commit 2ece43e5144a6028873ff0d816d99bae77a1acea.

6.11 Player lock durations can be less than the default minimum

FileFix commitTypeStatus
LockManager.sol—MediumFixed

The function setLockDuration(...) allows players to set the lock duration and updates existing locks. However, it does not check whether the new duration is at least the minimum period defined in lockdrop.minLockDuration. The function is presented below:

function setLockDuration(uint256 _duration) external notPaused {
if (_duration > configStorage.getUint(StorageKey.MaxLockDuration))
revert MaximumLockDurationError();

// @audit Missing check if new duration is less than lockdrop.minLockDuration
playerSettings[msg.sender].lockDuration = uint32(_duration);
uint256 configuredTokensLength = configuredTokenContracts.length;
// ...
}

The function _lock(...) uses the lockDuration defined by the player when players directly lock tokens or migrate. If the player did not set the lock duration, the minimum lock duration (lockdrop.minLockDuration) is used instead. Since the function setLockDuration doesn’t prevent a player’s custom duration from being less than the minimum, a player can use their own duration to unlock before the minimum time period.

function _lock(...) private {
// ...

// @audit User can have their own lock duration non-zero but less than minimum
uint32 _lockDuration = playerSettings[_lockRecipient].lockDuration;
if (_lockDuration == 0) {
_lockDuration = lockdrop.minLockDuration;
}

// ...
}

Recommendation

Consider adding a check to setLockDuration to prevent a duration less than drop.minLockDuration.

Resolution

Fix in PR #179 commit hash 39e31d6. I did not use the suggested fix because let’s say someone locked their tokens for 45 days but wanted to increase it to 60 and the min lock duration was 30... Then it would break. Instead, I modified the if statement here such that the migrationManager check happens after the lock duration check.

6.12 Players can mint multiple munchables for the same primordial

FileFix commitTypeStatus
src/manager/PrimordialManager.sol—MediumFixed

Players call hatchPrimordialToMunchable(...) once their primordials reach level 0 to swap for an NFT. The function checks whether the primordials exist and are ready to hatch.

function hatchPrimordialToMunchable() external notPaused {
(address _caller, ) = _getMainAccountRequireRegistered(msg.sender);
// @audit The function does not check if the primordial has already hatched
if (primordials[_caller].createdDate == 0)
revert PrimordialDoesntExistError();
if (primordials[_caller].level < 0) revert PrimordialNotReadyError();

primordials[_caller].hatched = true;

nftOverlord.mintFromPrimordial(_caller);

emit PrimordialHatched(_caller);
}

The function does not check whether the primordial has already hatched. As a result, the user can create multiple NFTs from the same primordial.

Recommendation

Ensure the primal isn’t hatched before creating a new NFT and marking the hatched = true attribute.

Resolution

Fixed in commit 487479d50c8685949485996bbd2873416b5704df.

6.13 Players can reduce their asset unlock time

FileFix commitTypeStatus
LockManager.sol—MediumFixed

The function setLockDuration(...) allows players to set their asset lock duration. The function ensures that block.timestamp + _duration is less than unlockTime, ensuring players are not setting the lock duration shorter than the current unlockTime.

function setLockDuration(uint256 _duration) external notPaused {
// ...
for (uint256 i; i < configuredTokensLength; i++) {
address tokenContract = configuredTokenContracts[i];
if (lockedTokens[msg.sender][tokenContract].quantity > 0) {
// Check they are not setting lock time before current unlocktime
// @audit Check with block.timestamp, but the update is lastLockTime + _duration
if (
uint32(block.timestamp) + uint32(_duration) <
lockedTokens[msg.sender][tokenContract].unlockTime
) {
revert LockDurationReducedError();
}
uint32 lastLockTime = lockedTokens[msg.sender][tokenContract]
.lastLockTime;
lockedTokens[msg.sender][tokenContract].unlockTime =
lastLockTime +
uint32(_duration);
}
}
// ...
}

The update to unlockTime is calculated by adding the lastLockTime with the duration instead of the current block timestamp. This allows a user to reduce their unlockTime to be shorter than before, since lastLockTime < block.timestamp < unlockTime. Users may be able to call this function multiple times to shorten their lock duration a significant amount. Consider the example below:

Let be new _duration = 70 days:

block.timestamp = 1716410961 // current timestamp
lastLockTime = uint32(block.timestamp) - uint32(20 days); // 20 days ago
unlockTime = lastLockTime + uint32(90 days); // Current unlocktime. This current lock period is 90 days

Considering the current timestamp in this example, the last lock time was 20 days ago for a locking period of 90 days; we have:

lastLockTime = 1714682961
unlockTime = 1722458961

The checking below will pass:

uint32(block.timestamp) + uint32(_duration) <
lockedTokens[msg.sender][tokenContract].unlockTime
uint32(block.timestamp) + uint32(_duration) = 1722458961

The function updates unlockTime to:

unlockTime = 1720730961

The player could reduce in 20 days their locking period.

Recommendation

Ensure the new lock duration will not lead to the unlock time being reduced, by changing the check to rely on lastLockTime instead of block.timestamp.

Resolution

Resolved in PR #1 of munchable-common-core-latest hash 0b12df2.

6.14 The function getSnuggery reverts with the index out of bounds error

FileFix commitTypeStatus
SnuggeryManager.sol—MediumFixed

The function getSnuggery(...) returns token ids and their respective imported dates for a given range defined by the parameter _start and the local variable maxSize. The function can return 10 tokenIds at most.

function getSnuggery( address _account, uint256 _start)
external view returns (
MunchablesCommonLib.SnuggeryNFT[] memory _snuggery,
uint256 _snuggerySize
)
{
// ...
_snuggerySize = snuggeries[_player].length;
uint256 maxSize = _snuggerySize;
if (maxSize > 10) {
maxSize = 10;
}
// ..
}

The issue arises when _start is greater than five and the maximum length for the array _snuggery is 10. The variable i reaches values out of bounds of the _snuggery when the variable _snuggerySize > 10.

    // @audit the maximum length for _snuggery is 10
_snuggery = new MunchablesCommonLib.SnuggeryNFT[](maxSize);
for (uint256 i = _start; i < maxSize + _start; i++) {
if (i >= _snuggerySize) break;

MunchablesCommonLib.SnuggeryNFT memory snuggeryNFT = snuggeries[
_player
][I];
// @audit if i greater than 10, we have index out of bounds error
_snuggery[i].tokenId = snuggeryNFT.tokenId;
_snuggery[i].importedDate = snuggeryNFT.importedDate;
}
}

Recommendation

Start adding munchables information from index zero in the array _snuggery.

Resolution

Resolved here to remove pagination: 63906fc8366dd48bf17bcdff151059cf32c53594, 1e6d63c67e967ab000036aaf4b7151299158b2fe.

6.15 Any user can access the full migration bonus

FileFix commitTypeStatus
MigrationManager.sol—LowFixed

Users can selectively migrate their purchased Munchable NFTs using the function migratePurchasedNFTs, passing an array of token IDs which they would like to migrate. After migration is complete the user is eligible for a migration bonus, which increases the amount of Schnibbles that the user earns on a daily basis. It is possible for a user who is not included in the migration snapshot to still access the migration bonus, by calling the migratePurchasedNFTs function with an empty tokenIds array. The for loop containing input validation is skipped since the array is empty, and the internal function _migrateNFTs is called.

function migratePurchasedNFTs(
uint256[] memory tokenIds
) external payable override nonReentrant {
MigrationSnapshotData memory snapshot;
uint256 quantity;
// @audit This loop and its validations are skipped entirely
for (uint256 i = 0; i < tokenIds.length; i++) {
// ...
}
_migrateNFTs(msg.sender, address(0), tokenIds);
if (msg.value != (quantity * discountFactor) / 10e12)
revert InvalidMigrationAmountError();
}

Inside the _migrateNFTs function, the mapping _userClaimedOnce[msg.sender] is set to true, then more token validation logic nested inside a loop is skipped. It will calculate the amount of assets to be locked in the LockManager as zero, so a lock with zero assets will be completed. In a later transaction when the user attempts to harvest, BonusManager.getHarvestBonus will be called which includes a migration bonus. Since the _userClaimedOnce mapping now points to true for the user, they will receive a migration bonus. A snippet from the migration bonus calculations are shown below:

function _calculateMigrationBonus(
address _caller,
uint256 weightedValue
) internal view returns (uint256 _migrationBonus) {
(
bool didMigrate, // This will be true
IMigrationManager.MigrationTotals memory totals
) = _migrationManager.getUserMigrationCompletedData(_caller);
ILockManager.ConfiguredToken memory configuredToken = _lockManager
.getConfiguredToken(totals.tokenLocked);
if (didMigrate) {
uint256 usdPrice = configuredToken.usdPrice;
// `totals.totalLockedAmount` is zero, so `migrateHighestAmount` is zero
uint256 migrateHighestAmount = (2 * totals.totalLockedAmount * usdPrice);
uint256 halfAmount = (totals.totalLockedAmount * usdPrice) / 2;
// `migrateHighestAmount` is now always zero, this if statement is a tautology
// Will always enter this if statement, giving a full bonus
if (weightedValue >= migrateHighestAmount) {
// Full bonus
_migrationBonus = migrationBonus;
} else if (weightedValue >= halfAmount) {
// ...
}
}
}

Since didMigrate is true but no tokens were actually migrated, the returned totals data is still empty so the totals.totalLockedAmount will be zero, leading to migrateHighestAmount always being zero. The first if statement will always be entered, granting a full bonus to users even if they did not hold any previous Munchables and were not included in the migration snapshot.

Recommendation

Consider adding a check in BonusManager._calculateMigrationBonus to set the migration bonus to zero if totals.totalLockedAmount is zero. Also consider preventing an array length of zero in the function MigrationManager.migratePurchasedNFTs, and as an extra precaution prevent any user from locking zero assets in LockManager.

Resolution

People are only eligible for the migration bonus when they transfer over locked NFTs, not purchased ones. Because of this, we moved the _userClaimedOnce check to the lockFundsForAllMigration at commit hash 0ececce.

6.16 Function getFullPlayerData may not return accurate Snuggery data

FileFix commitTypeStatus
AccountManager.sol—LowFixed

The function BonusManager._calculateLevelBonus is used to calculate the additional harvest bonus a player should receive based on the total level of the Munchables in their Snuggery. To calculate the total, the function AccountManager.getFullPlayerData is called which in turn calls Snuggery.getSnuggery to get the number of Munchables currently in the Snuggery and the token ID of each.

function _calculateLevelBonus(...) internal view returns (...) {
(
,
MunchablesCommonLib.Player memory player,
MunchablesCommonLib.SnuggeryNFT[] memory _snuggery,
uint256 _snuggerySize
) = _accountManager.getFullPlayerData(_caller);

if (_snuggerySize > 0) {
uint i;
for (; i < _snuggerySize; i++) {
_levelBonus += _nftAttributesManager.getAttributes(_snuggery[i].tokenId).level;
}
// ...
}
}

The function Snuggery.getSnuggery is limited to return a maximum of 10 Munchables per call, as it is intended to be called multiple times with an incrementing _start input in order to collect data on all Munchables in the Snuggery. When used by AccountManager.getFullPlayerData it only calls the function once and does not consider that there may be more than 10 Munchables. For bonus calculations, this means that users with more than 10 Munchables in their Snuggery will not receive the full rewards they would expect.

Recommendation

Consider applying one of the recommendations below:

1 - Consider refactoring the function Snuggery.getSnuggery. This refactoring would consist of extracting a private function C where Snuggery.getSnuggery would call it. This function C would loop the player’s snuggery according to parameters start and end, which could represent a pagination or the whole snuggery. Then, AccountManager.getFullPlayerData would call function C to get the entire player’s snuggery.

2 - Consider changing AccountManager.getFullPlayerData to call Snuggery.getSnuggery with increasing _start inputs until all Munchables have been retrieved.

Resolution

Resolved here to remove pagination: 63906fc8366dd48bf17bcdff151059cf32c53594, 1e6d63c67e967ab000036aaf4b7151299158b2fe.

6.17 MunchNFT contract’s pause mechanism is unreachable

FileFix commitTypeStatus
MunchNFT.sol—LowFixed

The MunchNFT contract derives from ERC721Pausable implementation but does not expose the internal _pause and _unpause functions. This means it is not possible to access the pausable features of the token.

Recommendation

Add an external function allowing a permissioned user to pause and unpause the contract. Also, consider adding the whenNotPaused modifier to the mint function to ensure that when the contract is paused, minting is also prevented.

Resolution

Fix in PR request #11 (we use the ConfigStorage Pause): PR #11

6.18 The last entry in a user’s sub-account array cannot be removed

FileFix commitTypeStatus
AccountManager.sol—LowFixed

When removing a sub-account in the function removeSubAccount, an array of all sub-accounts are iterated through until the matching address is found. Once found, all following elements in the array are shuffled to overwrite the address to be removed. The function is shown below:

function removeSubAccount(
address _subAccount
) external notPaused onlyRegistered(msg.sender) {
delete mainAccounts[_subAccount];
uint256 subAccountLength = subAccounts[msg.sender].length;
bool found = false;
for (uint256 i = 0; i < subAccountLength - 1; i++) {
if (subAccounts[msg.sender][i] == _subAccount || found) {
subAccounts[msg.sender][i] = subAccounts[msg.sender][i + 1];
found = true;
}
}
if (!found) revert SubAccountNotRegisteredError();
subAccounts[msg.sender].pop();
// ...
}

The for loop in removeSubAccount will execute until the second last index of the array, after which it will stop. This means the last element in the array will never be "found", and the function will revert. Consider an example with an array size of 3, the loop will terminate at i < arr.len - 1 which would be i < 2. In this case the loop would only execute twice with i=0,1, the third element won’t be checked.

Recommendation

Provided that sub-account array ordering does not matter, every element in the array can be checked, and once found a swap-then-pop approach can be used instead of shuffling each element.

function removeSubAccount(...) external /* ... */ {
// ...
bool found = false;
// @audit Replace the _subAccount to be removed by the one in the last position
for (uint256 i = 0; i < subAccountLength; i++) {
if (subAccounts[msg.sender][i] == _subAccount) {
subAccounts[msg.sender][i] = subAccounts[msg.sender][subAccountLength-1];
found = true;
subAccounts[msg.sender].pop();
break;
}
}
if (!found) revert SubAccountNotRegisteredError();

emit SubAccountRemoved(msg.sender, _subAccount);
}

Resolution

PR #179 commit hash 215bcee. Implemented recommendation.

6.19 Thresholds can be updated while a proposal is in progress

FileFix commitTypeStatus
LockManager.sol—LowFixed

The admin invokes the function setUSDThresholds(...) to update the thresholds APPROVE_THRESHOLD and DISAPPROVE_THRESHOLD.

function setUSDThresholds(
uint8 _approve,
uint8 _disapprove
) external onlyAdmin {
// @audit it should check if there not proposal in progress
APPROVE_THRESHOLD = _approve;
DISAPPROVE_THRESHOLD = _disapprove;

emit USDThresholdUpdated(_approve, _disapprove);
}

However, if the admin by mistake calls this function to update the thresholds while a proposal is in progress, this would directly impact the number of approvals and disapprovals to update the USD price.

Recommendation

Add the following check below in the function setUSDThresholds(...):

+if (usdUpdateProposal.proposer != address(0))
+revert ProposalInProgressError();

Resolution

Fixed in commit hash d88305b

6.20 User can set their own address as a referrer

FileFix commitTypeStatus
AccountManager.sol—LowFixed

When calling the register function as a new user, you can specify a referral address which will receive some additional points whenever the ClaimManager._claimPoints is called. It is possible for a user to do a "self referral" by passing their own address into this function to receive extra points.

function register(
MunchablesCommonLib.Realm _snuggeryRealm,
address _referrer
) external onlyUnregistered(msg.sender) {
// @audit User can pass their own address as the referral
// This will grant them additional undeserved points

if (mainAccounts[msg.sender] != address(0))
revert SubAccountCannotRegisterError();
if (_snuggeryRealm >= MunchablesCommonLib.Realm.Invalid)
revert InvalidRealmError();

// ...
}

Recommendation

Consider adding a check to prevent players from using their own address as a referral.

Resolution

Fix in PR #179 at commit hash 9aaff75.

6.21 A price proposal can be both approved and disapproved

FileFix commitTypeStatus
LockManager.sol—InfoFixed

The function approveUSDPrice allows an authorized address to voter for or against a price proposal. A series of validations are done before the vote is counted, including a check to ensure that the caller hasn’t already voted for the proposal before. However, it fails to validate that the voter has not voted against the proposal before.

function approveUSDPrice(uint256 _price) external onlyOneOfRoles(...)
{
/// ...
/// @audit Check that the voter has not voted in favor of the proposal before
if (usdUpdateProposal.approvals[msg.sender]) revert ProposalAlreadyApprovedError();

/// ...

/// @audit Counts the vote as valid
usdUpdateProposal.approvals[msg.sender] = true;
usdUpdateProposal.approvalsCount++;
/// ...
}

This would allow a voter to call the function disapproveUSDPrice to vote against a proposal, and then call approveUSDPrice to vote again, but this time in favour of the proposal.

Recommendation

Consider adding a check to ensure the proposal has not been previously voted against, similar to what is done in disapproveUSDPrice.

Resolution

Fixed in commit hash 06caf27.

6.22 Double approval account check when approving USD price

FileFix commitTypeStatus
LockManager.sol—InfoAcknowledged

The function approveUSDPrice increments the approvals count with each valid approval, and checks if the approval count meets or exceeds the APPROVAL_THRESHOLD. If the approval count is met then the price is updated by calling _execUSDPriceUpdate. Then, a duplicate approvals count check is done inside _execUSDPRiceUpdate, as shown below:

function approveUSDPrice(uint256 _price) external onlyOneOfRoles(...) {
//...
// @audit Approval count is checked
if (usdUpdateProposal.approvalsCount >= APPROVE_THRESHOLD) {
_execUSDPriceUpdate();
}
//...
}

// @audit This can only be called if approvalsCount >= APPROVE_THRESHOLD
function _execUSDPriceUpdate() internal {
if (
// @audit Approval count is checked again
usdUpdateProposal.approvalsCount >= APPROVE_THRESHOLD
&& usdUpdateProposal.disapprovalsCount < DISAPPROVE_THRESHOLD
) {
// ...
}
}

Recommendation

Consider removing one of these checks, so the approval count is only checked once.

Resolution

Acknowledged.

6.23 Duplicate notifiable addresses and handled differently in add/removal

FileFix commitTypeStatus
ConfigStorage.sol—InfoAcknowledged

The ConfigStorage contract has a notifiableAddresses storage array containing a list of addresses that will be notified for a configuration update upon storage changes. The functions addNotifiableAddress, addNotifiableAddresses, and removeNotifiableAddress are responsible for managing the addresses in this array.

The behaviour of these functions differs slightly however, when adding addresses it is possible to include duplicate entries that already exist. When removing addresses, handling of duplicates is not supported and the function will exit upon removal of the first entry, even if there are duplicate addresses in the array. Consequently, a contract may remain susceptible to updates via configUpdated, leading to unexpected behavior.

Recommendation

Consider changing removeNotifiableAddresses to not exit early on the first removal. This will improve consistency between the add and remove functions, where duplicates are supported for both.

Resolution

Acknowledged

6.24 Non configured but active tokens result in division by zero

FileFix commitTypeStatus
LockManager.solPR #164InfoFixed

The functions lockOnBehalf and lock allow users to lock their tokens. They use the modifier onlyActiveToken to ensure that the given token is active before it can be locked. However, these functions do not check that the given token is configured. If a token is active but not configured, a division by zero error can occur, causing asset lock attempts to revert. Relevant function snippets are shown below:

// @audit This function accepts unconfigured tokens
function lockOnBehalf(...) external payable notPaused onlyActiveToken(_tokenContract) nonReentrant {
// ...

_lock(
_tokenContract,
_quantity,
tokenOwner,
lockRecipient,
_lockDuration
);
}

// @audit This function accepts unconfigured tokens
function lock(...) external payable notPaused onlyActiveToken(_tokenContract) nonReentrant {
_lock(_tokenContract, _quantity, msg.sender, msg.sender, _lockDuration);
}

function _lock(...) private {
// ...

// @audit Division by zero if nftCost == 0, i.e., non configured token
remainder = quantity % configuredToken.nftCost;
numberNFTs = (quantity - remainder) / configuredToken.nftCost;

// ...
}

Recommendation

Consider adding the modifier onlyConfiguredToken to the functions lock and lockOnBehalf.

Resolution

Used your suggestion in this PR: https://github.com/munchablesorg/munchables-common-core/pull/164.

6.25 Primordials can be fed after hatching

FileFix commitTypeStatus
src/managers/PrimordialManager.sol—InfoFixed

A player invokes feedPrimordial to feed their primordials to increase their chonks. When the primordial reaches level 0, it can be swapped for a Munchable. It is possible to call feedPrimordial multiple times after the primordial has already hatched, and the players schnibbles will be consumed, increasing it’s chonks without further increasing the level.

function feedPrimordial(
uint256 _schnibbles
) external notPaused onlyPrimordialsEnabled {
(
address _mainAccount,
MunchablesCommonLib.Player memory _player
) = _getMainAccountRequireRegistered(msg.sender);

if (_player.unfedSchnibbles < _schnibbles)
revert InsufficientSchnibblesError(_player.unfedSchnibbles);

if (primordials[_mainAccount].createdDate == 0)
revert PrimordialDoesntExistError();
// @audit No check if primordial already hatched
// Can feed already hatched primordial, and schnibbles will be spent
primordials[_mainAccount].chonks += _schnibbles;
// ...
}

Recommendation

Consider adding a check to prevent feeding if the player’s primordial has already hatched.

Resolution

Fixed in commit f001ee9fa6c8f090093290e6f752e1d314226114.

6.26 Redundant loop in function addSubAccount

FileFix commitTypeStatus
AccountManager.sol—InfoAcknowledged

In the function addSubAccount a loop is used to check that the sub-account address to be added is not already a sub account for the caller. This loop is not necessary, as a previous check makes sure that the given _subAccount doesn’t have an associated main account, as shown below:

function addSubAccount(
address _subAccount
) ... {
// @audit This check makes sure the sub account doesn't have a main account
if (mainAccounts[_subAccount] != address(0))
revert SubAccountAlreadyRegisteredError();
mainAccounts[_subAccount] = msg.sender;

// @audit Sub account already doesn't have a main account
// This check is unnecessary
for (uint256 i; i < subAccounts[msg.sender].length; i++) {
if (subAccounts[msg.sender][i] == _subAccount)
revert SubAccountAlreadyRegisteredError();
}
// ...
}

Recommendation

Consider removing the unnecessary loop.

Resolution

Acknowledged

6.27 The same spray proposal can be executed multiple times

FileFix commitTypeStatus
AccountManager.sol—InfoFixed

The function execSprayProposal allows accounts with the "Social Approval" role to execute proposals that will distribute Schnibbles to users. Once a proposal has been executed however, the proposal data is not cleared, allowing the same proposal to be executed multiple times. A snippet from the function is shown below:

function execSprayProposal(address _proposer) external onlyOneOfRoles([...]) {
uint256 numberEntries = sprayProposals[_proposer].squirts.length;
for (uint256 i; i < numberEntries; i++) {
/// ...

if (players[player].registrationDate != 0) {
players[player].unfedSchnibbles += schnibbles;
} else {
unclaimedSchnibbles[player] += schnibbles;
}
}
/// @audit Upon completion, the proposal not deleted
}

Recommendation

Consider deleting proposal data after the proposal has been executed in execSprayProposal.

Resolution

Resolved here

6.28 Unnecessary storage write when player chonks haven’t changed

FileFix commitTypeStatus
managers/SnuggeryManager.sol—InfoAcknowledged

The function _recalculateChonks recalculates the player chonks and will update the totalGlobalChonk if a difference has been observed. As shown below, the playerChonks mapping entry is updated every time, even when previousChonks is equal to _playerChonks:

function _recalculateChonks(address _player) internal {
uint256 previousChonks = playerChonks[_player];
uint256 _playerChonks;
for (uint256 i; i < snuggeries[_player].length; i++) {
_playerChonks += nftAttributesManager
.getAttributes(snuggeries[_player][i].tokenId)
.chonks;
}

//@audit This update can be moved into the if branch below to save gas
playerChonks[_player] = _playerChonks;

if (previousChonks != _playerChonks) {
totalGlobalChonk += (_playerChonks - previousChonks);
}
}

Recommendation

Consider updating the code to change playerChonks only if previousChonks!= _playerChonks, since if there is no difference the storage write will be unnecessary.

Resolution

Acknowledged

6.29 Wrong error message in burnUnrevealedForPoints(...)

FileFix commitTypeStatus
MigrationManager.sol—InfoFixed

The function burnUnrevealedForPoints can only be called when the migration data is sealed, and will revert otherwise. However, revert error used is MigrationDataSealedError, where MigrationDataNotSealedError should be used instead, as shown below:

function burnUnrevealedForPoints() external {
// @audit Error should be MigrationDataNotSealedError
if (!seal) revert MigrationDataSealedError();
// ...
}

Recommendation

Consider replacing the MigrationDataSealedError(...) error with MigrationDataNotSealedError(...).

Resolution

Fixed at commit hash d88305b.

6.30 tokenLocked can be overwritten during migration snapshot loading

FileFix commitTypeStatus
MigrationManager.sol—InfoAcknowledged

The function loadMigrationSnapshot is called by the admin to load migration snapshots for multiple users. The function is presented below:

function loadMigrationSnapshot(
address[] calldata users,
MigrationSnapshotData[] calldata data
) external override onlyUniversalRole(Role.Admin) {
// ...
if (data[i].lockAmount != 0) {
_userLockedAmounts[_user].totalLockedAmount += data[I]
.lockAmount;
// @audit tokenLocked can be overwritten if users contains
// more than one occurrence of the same user address
// and different token (USDB or WETH)
_userLockedAmounts[_user].tokenLocked = data[i].token;
} else {
// ...
}

The function validates if the tokens in the struct data are USDB, WETH, or zero address for ETH. it also validates if the migration snapshot for a particular user and tokenId is not loaded yet. However, the loadMigrationSnapshot(...) does not check if tokenLocked is equal to data[i].token (in case the tokenLocked is already set) when data[i].lockAmount != 0. A particular user may occur multiple times in the array users or can be passed to the function in different invokes. In these both scenarios, if _userLockedAmounts is already set for a particular user, then the tokenLocked will be overwritten with a different token address and the totalLockedAmount will be incremented for different tokens.

Recommendation

Ensure _userLockedAmounts[_user].tokenLocked is equal to data[I].token when it is already set.

Resolution

Considered, but all data coming in will be one token type per user so this can be ignored.

6.31 Common storage does not have provision for additional features in future

FileFix commitTypeStatus
BaseConfigStorage.sol—Best PracticesAcknowledged

BaseConfigStorage is a storage location for generic functionality of the protocol. As of now, only pause and reference to interface for business specific storage is stored. As the protocol grows, there may be a need to add more state variable for generic functionality of the protocol. Currently, there is no gap provisioned in BaseConfigStorage contract for any additional state variables needed to support new generic/common functionality for the protocol in future.

Recommendation

Consider adding a storage gap to create reserve space in the storage layout for future functionality: uint256[20] __gap. The gap size only serves as a suggestion.

Resolution

Acknowledged

6.32 Lock pragmas to specific compiler version

FileFix commitTypeStatus
src/*—Best PracticesFixed

The smart contracts in this project use different pragma versions. Contracts should be deployed with the same fixed compiler version to ensure consistency between testing and production environments. The following is a list of the varying pragma versions throughout the codebase:

pragma solidity 0.8.25;
pragma solidity ^0.8.0;
pragma solidity ^0.8.25;

Recommendation

Consider using the same version for all contracts in the codebase.

Resolution

Fixed at commit hash 9674508.

6.33 Migration data token ID should not be zero

FileFix commitTypeStatus
MigrationManager.sol—Best PracticesFixed

The function loadMigrationData is called by the admin to set migration data which will be used to lock and convert previous Munchables over to the new implementation. The token ID of a Munchable available to be migrated is part of the migration data, and can be set to any value by the admin, including zero. However, in other functions such as _migrateNFTs a token ID of zero is treated differently, causing the function to exit early or revert in some cases, as shown below:

// Function burnNFTs
if (snapshot.tokenId == 0) revert NoMigrationExistsError();
// Function burnRemainingPurchasedNFTs
if (snapshot.tokenId == 0) revert NoMigrationExistsError();
// Function _migrateNFTs
if (tokenId == 0) continue;
if (snapshot.tokenId == 0) revert NoMigrationExistsError();

As a general best practice it should not be possible to set valid data to the same value that is reserved for "empty", in this case, a token ID of zero as it may lead to unexpected behavior such as locked migration funds.

Recommendation

Consider adding a check to loadMigrationData to prevent the MigrationSnapshotData.tokenId fields from being zero.

Resolution

Fixed in PR #179 at commit hash 7cd19ec.

6.34 Missing _disableInitializers(...) function in upgradeable contracts

FileFix commitTypeStatus
src/*—Best PracticesFixed

The contracts AccountManager and ClaimManager are designed to be upgradeable, inheriting from the OpenZeppelin Initializable abstract contract implementation. A security recommendation issued by OpenZeppelin is to lock the initialization of the implementation contracts after deployment. This will any users from being able to execute the initialize function and potentially take control of the implementation contract.

Recommendation

Consider following OpenZeppelin’s best practices by invoking the _disableInitializers function in the contract’s constructor. This action will automatically lock the contract upon deployment, thereby preventing the implementation contract from being controlled.

Resolution

Fix in PR #18: PR #18

6.35 Redundant inheritance

FileFix commitTypeStatus
BonusManager.sol—Best PracticesFixed

The BonusManager contract has an explicit inheritance, which is already implicitly included in a parent contract. Consider the example shown below:

// BonusManager inherits BaseConfigStorage
// However BaseConfigStorage is already inherited via BaseBlastManager

contract BonusManager is BaseConfigStorage, BaseBlastManager {...}
abstract contract BaseBlastManager is BaseConfigStorage {...}

Recommendation

Consider evaluating the redundant inheritance from BonusManager.

Resolution

Fixed at d302fda.

6.36 Unused imports

FileFix commitTypeStatus
RewardsManager.sol
RewardsManager.sol
—Best PracticesAcknowledged

The codebase contains some unused code, affecting overall readability and code quality. A list of files and their unused declarations are shown below:

Contract RewardsManager.sol

import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/IDistributor.sol";
import "../interfaces/IClaimManager.sol";
import "../interfaces/IConfigStorage.sol";
import "../interfaces/IBlast.sol";
import "../interfaces/IConfigNotifiable.sol";

Contract LockManager.sol

import "../interfaces/IConfigStorage.sol";

Recommendation

To keep the code clean and readable, consider evaluating if the unused functionality should be used and, if not, remove it from the codebase.

Resolution

Acknowledged

6.37 Use of legacy call to transfer native tokens

FileFix commitTypeStatus
FundTreasuryDistributor.sol—Best PracticesFixed

The function receiveTokens is using transfer() to move native assets to the treasury account. The transfer function operates with a 2300 gas limit. As gas costs are subject to change, it is not recommended to rely on a fixed gas cost native asset transfer mechanism.

Recommendation

Consider using the low level call() function to transfer native assets instead of transfer().

Resolution

Fixed at commit hash 9c8e121.

7

Documentation Evaluation

Software documentation refers to the written or visual information that describes the functionality, architecture, design, and implementation of software. It provides a comprehensive overview of the software system and helps users, developers, and stakeholders understand how the software works, how to use it, and how to maintain it. Software documentation can take different forms, such as user manuals, system manuals, technical specifications, requirements documents, design documents, and code comments. Software documentation is critical in software development, enabling effective communication between developers, testers, users, and other stakeholders. It helps to ensure that everyone involved in the development process has a shared understanding of the software system and its functionality. Moreover, software documentation can improve software maintenance by providing a clear and complete understanding of the software system, making it easier for developers to maintain, modify, and update the software over time. Smart contracts can use various types of software documentation. Some of the most common types include:

  • Technical whitepaper: A technical whitepaper is a comprehensive document describing the smart contract’s design and technical details. It includes information about the purpose of the contract, its architecture, its components, and how they interact with each other;
  • User manual: A user manual is a document that provides information about how to use the smart contract. It includes step-by-step instructions on how to perform various tasks and explains the different features and functionalities of the contract;
  • Code documentation: Code documentation is a document that provides details about the code of the smart contract. It includes information about the functions, variables, and classes used in the code, as well as explanations of how they work;
  • API documentation: API documentation is a document that provides information about the API (Application Programming Interface) of the smart contract. It includes details about the methods, parameters, and responses that can be used to interact with the contract;
  • Testing documentation: Testing documentation is a document that provides information about how the smart contract was tested. It includes details about the test cases that were used, the results of the tests, and any issues that were identified during testing;
  • Audit documentation: Audit documentation includes reports, notes, and other materials related to the security audit of the smart contract. This type of documentation is critical in ensuring that the smart contract is secure and free from vulnerabilities.

These types of documentation are essential for smart contract development and maintenance. They help ensure that the contract is properly designed, implemented, and tested, and they provide a reference for developers who need to modify or maintain the contract in the future.

8

Remarks & Test Suite

The documentation for Munchables is contained in the project’s Github directory guides. It consists of five files with:

  • Explanation of how the game works.
  • General overview of the system.
  • Description of the features.
  • Logic and structural flow. The information in the documentation is concise and technical, with well-written explanations. Code comments are also of high quality, with descriptions for every function explaining the context and situations where the function is called. There are comments in other parts of the code where extra information is needed, allowing readers to comprehend the code faster. During the audit, the Munchables Team had effective communication. They were available for meetings to answer questions, explain further, and discuss the detected issues. In addition, they were consistently accessible, ensuring that our team could seek and receive timely clarifications and support as needed.
Test suite
2Tests passed0Failed

The complete test output is in the full report.

As auditors, we recommend that any changes or updates made to the audited codebase undergo a re-audit or security review to address potential vulnerabilities or risks introduced by the modifications. By conducting a re-audit or security review of the modified codebase, you can significantly enhance the overall security of your system and reduce the likelihood of exploitation. However, we do not possess the authority or right to impose obligations or restrictions on our clients regarding codebase updates, modifications, or subsequent audits. Accordingly, the decision to seek a re-audit or security review lies solely with you.

This report is based on the scope of materials and documentation provided by you to Nethermind in order that Nethermind could conduct the security review outlined in 1. Executive Summary and 2. Audited Files. The results set out in this report may not be complete nor inclusive of all vulnerabilities. Nethermind has provided the review and this report on an as-is, where-is, and as-available basis. You agree that your access and/or use, including but not limited to any associated services, products, protocols, platforms, content, and materials, will be at your sole risk. Blockchain technology remains under development and is subject to unknown risks and flaws. The review does not extend to the compiler layer, or any other areas beyond the programming language, or other programming aspects that could present security risks. This report does not indicate the endorsement of any particular project or team, nor guarantee its security. No third party should rely on this report in any way, including for the purpose of making any decisions to buy or sell a product, service or any other asset. To the fullest extent permitted by law, Nethermind disclaims any liability in connection with this report, its content, and any related services and products and your use thereof, including, without limitation, the implied warranties of merchantability, fitness for a particular purpose, and non-infringement. Nethermind does not warrant, endorse, guarantee, or assume responsibility for any product or service advertised or offered by a third party through the product, any open source or third-party software, code, libraries, materials, or information linked to, called by, referenced by or accessible through the report, its content, and the related services and products, any hyperlinked websites, any websites or mobile applications appearing on any advertising, and Nethermind will not be a party to or in any way be responsible for monitoring any transaction between you and any third-party providers of products or services. As with the purchase or use of a product or service through any medium or in any environment, you should use your best judgment and exercise caution where appropriate. FOR AVOIDANCE OF DOUBT, THE REPORT, ITS CONTENT, ACCESS, AND/OR USAGE THEREOF, INCLUDING ANY ASSOCIATED SERVICES OR MATERIALS, SHALL NOT BE CONSIDERED OR RELIED UPON AS ANY FORM OF FINANCIAL, INVESTMENT, TAX, LEGAL, REGULATORY, OR OTHER ADVICE.