Download audit report
This document presents the security review performed by Nethermind in the eCredits code. This protocol allows users to freeze funds for a period of 12 months for earning interests. Standard users receive an annual interest rate of 2%. Users with Gold subscription receive an annual interest rate of 3%, while users having a Platinum subscription receive 6%, Any user can freeze several times, and freezes are only accepted when there is enough budget for rewarding the users.
The source code consists of 318 lines of Solidity with code coverage of 89%. The audit was performed with manual analysis of the codebase, use of automated tools, followed by the deployment and operation of the contracts. The audit team has not received a formal documentation suite, but a set of use cases for conducting the audit. The client was responsive and guided us through the audit.
The most important issues are related to the way rewards are computed, the possibility of bypassing the main contract and funding old campaigns (which can be solved by improving the access control), missing validation for some input parameters, payable functions not checking msg.value for being greater than zero, storage access inside loops, costly loops, and the lack of a formal use case for closing the campaign, preventing new funds to be added to a closed campaign.
During the audit, we point out 31 points of attention. The client has fixed 26 points of attention, while 5 points of attention were acknowledged. The acknowledged points do not bring any risk to the protocol and they are just minor optimizations in the code.
| Audit assessment | |
| Audit Type | Security Review |
| Initial Report | Jan. 3, 2023 |
| Response from Client | Jan. 10, 2023 |
| Final Report | Jan. 22, 2023 |
| Methods | Manual Review, Automated Analysis |
| Repository | eCredits by Cryptix |
| Commit Hash (Initial Audit) | 00271bf3a0 |
| Commit Hash (Final Audit) | 7107cc5ad9 |
| Documentation | Low |
| Documentation Assessment | Low |
| Test Suite Assessment | Medium |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | contracts/EVaultCampaignBudget.sol | 24 | 9 | 37.5% | 9 | 42 |
| 2 | contracts/EVaultCampaigns.sol | 83 | 45 | 54.2% | 24 | 152 |
| 3 | contracts/EVaultCampaign.sol | 211 | 52 | 24.6% | 56 | 319 |
| Total | 318 | 106 | 33.3% | 89 | 513 |
The protocol is composed of four contracts summarized in Fig. 2. The contract SubscriptionNFT is responsible for storing the category of subscription. Users having a Gold or Platinum subscription will have an ERC1155 token stored in this contract. This is a simple and straightforward contract that is out of the scope of this audit. The contract EVaultCampaigns works like a factory, managing the active campaign, instantiating a new one when necessary, and also providing the entry point and interface for external interactions. As we show along the report, some functions provided by this contract can be bypassed, which can be easily solved by adding access control to the underlying contracts.
The contract EVaultCampaign is owned by the factory contract and receives in its constructor the address of the SubscriptionNFT contract, the freezingThresholdLimit and the maxFreezableAmountPerAddress. The freezingThresholdLimit is a reserve of funds used to guarantee the existence of funds for paying all the rewards after 12 months, while the maxFreezableAmountPerAddress imposes a limit on the amount that each address can freeze for earning interests. This contract holds the investments made by users.
ERC1155Upgradeable
AccessControl
AccessControlUpgradeable
__constr__
initializemintGold
mintPlatinum
burnGold
burnPlatinum
extendExpirationclaim
Ownable Ownable__constr__
reserve
claim
claimForSenderHowever, the reward funds are stored in a separate contract named EVaultCampaignBudget. This contract is instantiated during the construction of the contract EVaultCampaign. Each campaign is associated with one single budget contract, and each budget contract is also associated with just one campaign contract. The budget contract stores the funds that are available for paying rewards. When any user freezes a given amount in the contract EVaultCampaigns, that operation propagates to the active campaign. The active campaign checks the availability of funds in the budget contract. In case funds are available, the budget contract reserves the amount required for paying the reward to the user and updates the available balance. New investments (freezes) are only accepted when the budget contract has sufficient available funds for paying the rewards. The contracts are described below in accordance with the structural diagram presented in Fig. 3.
EVaultCampaignsThis contract is a wrapper for the wallet orchestrating calls to all existent campaigns and also responsible for adding new campaigns. Campaigns don’t have a particular end date, meaning as long as funds are available they can be used for freezing. When a campaign is getting closer to its end, it means that funds have been drained close to total budget. Then, the owner decides whether they send additional funds to the budget or let the campaign end (with the last available freezing) and create a new one.
EVaultCampaignThe contracts EVaultCampaign and EVaultCampaignBudget consist of the logic for storing assets and computing rewards based on amounts that users freeze and claim. EVaultCampaign is a contract that users and owner use to get several information, such as compute the freezable amount for a particular claimer, all freezings of a particular claimer within the campaign, and get total reward withdrawn by a claimer. Only the owner can call freeze() and claimForSender() functions. The freezings are locked in the campaign contract and they apply two strategies to know if all funds have been transferred from the campaign contract to users: a) campaign contract balance which should decrease down to 0 over time; b) by parsing the emitted events.
EVaultCampaignBudgetThe EVaultCampaignBudget contract holds the budget funds and acts as the source for the rewards given by a campaign. The budget contract only transfers funds upon user claim. This is computed proportionally to the freezing period held by the user. However, there are situations where some funds can remain available in the contract after the 12 months: a) the users do not claim their accumulated rewards, which means they are marked as reserved but are finally not withdrawn; b) if nobody wants to freeze anymore, which essentially means that the budget will not be reduced (in terms of reserved amount) and therefore the available funds still remain there.
The DEFAULT_ADMIN_ROLE is the address who has deployed the contract EVaultCampaigns. The role can:
The CAMPAIGN_CREATOR_ROLE is set by the DEFAULT_ADMIN_ROLE during the deployment of the contract EVaultCampaigns. The role can:
EVaultCampaigns.addCampaign(...);The CAMPAIGN_OWNER is the contract EVaultCampaigns. The role can:
EVaultCampaign.freeze(address sender);EVaultCampaign.claimForSender(address claimer).The BUDGET_OWNER is the contract EVaultCampaign. The role can:
EVaultCampaignBudget.reserve(uint256 amount);EVaultCampaignBudget.claimRewards(address payable claimer, uint256 amount).The protocol provides the following public functionalities.
EVaultCampaigns.freeze()EVaultCampaigns.claim()EVaultCampaigns.fund()EVaultCampaign.fund()EVaultCampaign.claim()EVaultCampaignBudget.fund()In addition to these features, the contract also provides getters which are not listed above.
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:
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:
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 / Likelihood | Low | Medium | High |
| High | Medium | High | Critical |
| Medium | Low | Medium | High |
| Low | Info / Best Practices | Low | Medium |
| Undetermined | Undetermined | Undetermined | Undetermined |
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.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.solcontracts/EVaultCampaign.solcontracts/EVaultCampaignBudget.sol | 7107cc5 | High | Fixed |
Let’s assume Bob is a regular user who will receive an interest rate of 2%. Bob makes the following freezes in sequential blocks into a single campaign:
Bob freezes 40 Wei in Block 1;
Bob freezes 40 Wei in Block 2;
Bob freezes 40 Wei in Block 3;
...
Bob freezes 40 Wei in Block 10;Along the same day, Bob has deposited 400 Wei using 10 different transactions. Then, Bob waits for the period of 12 months for claiming the rewards. Since Bob has freezed 400 Wei, he expects to receive 8 Wei as rewards. However, since interests are computed using individual deposits, and there is a truncation, Bob will receive 0 Wei as a total reward for his 400 Wei freezed during 12 months, as presented below.
Bob's Rewards for Block 1 = 2% of 40 Wei = 0.8, which will be rounded down to 0 Wei;
Bob's Rewards for Block 2 = 2% of 40 Wei = 0.8, which will be rounded down to 0 Wei;
Bob's Rewards for Block 3 = 2% of 40 Wei = 0.8, which will be rounded down to 0 Wei;
...
Bob's Rewards for Block 10 = 2% of 40 Wei = 0.8, which will be rounded down to 0 Wei.A better technical solution would be to compute the interests considering the whole amount freezed up to this moment, which would allow Bob to receive the proper reward for his freezed investment. Although we are presenting an extreme example, this situation can happen even when users freeze amounts that are not multiples of 50 when considering the interest rate of 2%. Another example is presented below. Alice freezes two values:
Alice freezes 170 Wei in Block 1;
Alice freezes 230 Wei in Block 2;Since Alices has also freezed 400 Wei, she expects to receive 8 Wei as rewards. However, what happens is described below:
Alice's Rewards for Block 1 = 2% of 170 Wei = 3.4, which will be rounded down to 3 Wei;
Alice's Rewards for Block 2 = 2% of 230 Wei = 4.6, which will be rounded down to 4 Wei.Instead of 8 Wei, Alice will get only 7 Wei as rewards. However, if she delays 20 Wei from Block 1 to Block 2, she would freeze as follows:
Alice freezes 150 Wei in Block 1;
Alice freezes 250 Wei in Block 2.In this setup, Alice would get 8 Wei of rewards, as show below:
Alice's Rewards for Block 1 = 2% of 150 Wei = 3, which won't be rounded;
Alice's Rewards for Block 2 = 2% of 250 Wei = 5, which won't be rounded.Recommendation
Compute the interests considering the whole amount freezed up to each moment, and not using the individual amounts freezed at each block. Modifying this functionality will also require reviewing the reserve value stored in the budget contract. Another approach is to ensure the amounts to be multiples of 100.
Resolution
Fixed by accepting only amounts which are multiple of 100 Wei in the freeze() function. Wallet UI validation will be updated in order to reflect this. Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.solcontracts/EVaultCampaign.solcontracts/EVaultCampaignBudget.sol | 7107cc5 | High | Fixed |
According to the specification, by default users are rewarded with 2% in ECS. Users with Gold subscription are rewarded with 3% in ECS. Users with Platinum subscription are rewarded with 6% in ECS (interest rates considering 12 months of investment). Let’s consider the scenario where users are rewarded with 2% in ECS. If the user invests 50 ECS, after 12 months he/she will be rewarded with 1 ECS. This is the same value obtained by another user who invested 99 ECS. The values are the same due to rounding errors.
In the scenario of 2% of reward, every 50 units provide 1 unit of interest. Users with a Gold subscription are rewarded 3%. So, every 33.33333...3 units lead to an interest of 1. Platinum users are rewarded with 6%. So, every 16.66...6 units lead to an interest of 1 unit. A straightforward way of addressing this issue is requiring every investment to be a multiple of 100. By doing so, all the three interest rates can be properly computed.
Recommendation
The smart contract must assist the users when depositing. If depositing more does not change the rewards, the users must be alerted. One straightforward solution is to require deposited amounts to be multiple of 100. Other approaches can be proposed as well. Also update the user facing documentation.
Resolution
Fixed by accepting only amounts which are multiple of 100 Wei in the freeze() function. Wallet UI validation will be updated in order to reflect this. Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.sol | 7107cc5 | Medium | Fixed |
The new campaign may be added only if the current active campaign has less than 1 ether of funds for rewards. Since anyone can fund a campaign, the possibility of finishing the campaign and creating a new one is not ensured by the protocol. This may lead to an infinite run of one active campaign.
Recommendation
Consider adding a mechanism that would safely allow the owner to start a new campaign.
Resolution
Fixed by adding the function addCampaignWithForce().
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
freezingThresholdLimit and maxFreezableAmountPerAddress must be validated| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.solcontracts/EVaultCampaign.sol | 7107cc5 | Medium | Fixed |
The EVaultCampaign.constructor(...) is called by EVaultCampaigns.addCampaign(...), which is a protected function only callable by the CAMPAIGN_CREATOR_ROLE. Since the protocol is ultimately managed by humans, writing a defensive code is useful to promptly identify human errors. By inspecting the code, we notice that EVaultCampaign.constructor(...) does not perform any validation on the input parameters _freezingThresholdLimit and _maxFreezableAmount. For instance, the _freezingThresholdLimit and _maxFreezableAmount can be checked for a validity range. The code with audit comments is reproduced below.
constructor(address _subscriptionNftAddress, uint256 _freezingThresholdLimit, uint256 _maxFreezableAmount) {
//////////////////////////////////////////////////////////////////////////////////
// @audit "_freezingThresholdLimit" not validated
// @audit "_maxFreezableAmount" not validated.
//////////////////////////////////////////////////////////////////////////////////
subscriptionNFT = SubscriptionNFT(_subscriptionNftAddress);
freezingThresholdLimit = _freezingThresholdLimit;
maxFreezableAmountPerAddress = _maxFreezableAmount;
budget = new EVaultCampaignBudget();
}These parameters play a key role in the application, and the protocol can be useless if wrong values are accepted for these parameters. The function EVaultCampaigns.addCampaign(...) uses the input parameters maxFreezableAmount and freezingThresholdLimit to create a campaign, as reproduced below.
function addCampaign(uint256 freezingThresholdLimit, uint256 maxFreezableAmount) external {
...
address campaignAddress = createCampaign(freezingThresholdLimit, maxFreezableAmount);
...
}Once the campaign is created by instantiating the contract EVaultCampaign, maxFreezableAmount and freezingThresholdLimit can not be changed, since those variables are declared as immutable in EVaultCampaign.sol, as reproduced below.
uint256 private immutable freezingThresholdLimit;
uint256 private immutable maxFreezableAmountPerAddress;When maxFreezableAmountPerAddress is zero and the campaign is funded, the functions freeze(...) and getFreezableAmount(...) will revert due to overflow, as presented in the code snippets below:
function freeze(address sender) public payable onlyOwner {
///////////////////////////////////////////////////////////
// @audit The operation "maxFreezableAmountPerAddress - getTotalFrozenAmount(sender)"
// overflows if "maxFreezableAmountPerAddress" is zero.
///////////////////////////////////////////////////////////
require (maxFreezableAmountPerAddress - getTotalFrozenAmount(sender) >= msg.value, 'freeze: msg.value of sender,! above max freezable amount');
...
}
function getFreezableAmount(address claimer) public view returns (uint256) {
///////////////////////////////////////////////////////////
// @audit The operation "maxFreezableAmountPerAddress - getTotalFrozenAmount(claimer)"
// overflows if "maxFreezableAmountPerAddress" is zero.
///////////////////////////////////////////////////////////
uint256 claimerFreezable = maxFreezableAmountPerAddress - getTotalFrozenAmount(claimer);
...
return claimerFreezable - freezingThresholdLimit;
}As the users can never freeze, the budget.claimRewards(...) call will never be executed and assets in EVaultCampaignBudget will be locked permanently. Furthermore, the function getAvailableFreezingBudget(...) will always return the notReserved amount when freezingThresholdLimit is zero. This threshold is used to ensure that all users can receive the reward at the end of the campaign. The code snippet is reproduced below.
function getAvailableFreezingBudget() public view returns (uint256) {
uint256 notReserved = budget.getAvailableAmount();
if (notReserved < freezingThresholdLimit)
return 0;
///////////////////////////////////////////////////////////
// @audit If "freezingThresholdLimit" is zero, the function
// always returns "notReserved".
///////////////////////////////////////////////////////////
return notReserved - freezingThresholdLimit;
}Recommendation
Ensure that maxFreezableAmount and freezingThresholdLimit are within reasonable intervals and they are greater than zero.
Resolution
Fixed by adding basic validation. Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | — | Low | Acknowledged |
To claim rewards, user can call two functions: EVaultCampaigns.claim(...) which iterates over all FrozenAmount objects in all existing campaigns, or EVaultCampaign.claim(...) which computes reward due from one campaign. If there are sufficient campaigns and FrozenAmount objects, the cost of claiming funds in function EVaultCampaigns.claim(...) can be high. In such a situation, the user would have to call claim(...) on each campaign. This is not ideal, since the wallet works only with the active campaign, and calling previous campaigns requires interacting with the smart contract outside of the user interface.
Recommendation
To optimize the process of claiming rewards, consider allowing the user to easily claim rewards from previous campaigns through the user interface, so it would not require technical knowledge on the user side. You can also consider adding a pagination scheme in case the user has too many entries in the FrozenAmount structure.
Resolution
That’s a valid and known issue. For the sake of simplicity it was decided to offer one "claim-for-everything" approach with potentially increased gas costs. The required changes would be too big to implement in tine. Additionally as the expected count of campaigns is rather low and the gas costs in the network are cheap it is a tradeoff we accept.
| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | 7107cc5 | Low | Fixed |
The function freeze(...) computes the value that must be reserved in the budget contract (EVaultCampaignBudget). When msg.value is small, the function calculateBudgetToReserve(...) will return zero due to truncation. Then, the code checks if toReserve is smaller than or equal to the balance of the budget contract in the line reproduced below.
require(toReserve <= budget.getAvailableAmount(), 'freeze: no budget left anymore');Since toReserve and budget.getAvailableAmount() have the same value (zero), the require(...) will pass, and the user will be able to freeze an amount without having any reserves in the budget contract. The whole function is reproduced below.
function freeze(address sender) public payable onlyOwner {
require (maxFreezableAmountPerAddress - getTotalFrozenAmount(sender) >= msg.value, 'freeze: msg.value of sender,! above max freezable amount');
uint256 rate; uint256 subscription;
(rate, subscription) = determineRate(sender);
/////////////////////////////////////////////////////////////////////////////////////////////////
// @audit When "msg.value" is small, "toReserve" receives zero.
/////////////////////////////////////////////////////////////////////////////////////////////////
uint256 toReserve = calculateBudgetToReserve(msg.value, rate);
/////////////////////////////////////////////////////////////////////////////////////////////////
// @audit When "toReserve" is zero and the budget contract has zero balance,
// the "require" clause is evaluated as "true".
/////////////////////////////////////////////////////////////////////////////////////////////////
require(toReserve <= budget.getAvailableAmount(), 'freeze: no budget left anymore');
budget.reserve(toReserve);
FrozenAmount[] storage frozenSenderAmounts = frozenAmounts[sender];
if (frozenSenderAmounts.length > 0) {
require(frozenSenderAmounts[frozenSenderAmounts.length - 1].blockNumber != getBlockNumber(), 'freeze: sender,! already did a freezing in same block');
}
FrozenAmount memory fa = FrozenAmount(msg.value, getBlockNumber(), getBlockTimestamp(), rate, 0, false);
frozenSenderAmounts.push(fa);
emit VaultLock(fa.blockNumber, msg.value, rate, subscription);
}Recommendation
There are some options. a) if toReserve is zero, revert the operation; b) set a minimal amount for freezes; c) change the require(...) clause to check if toReserve is smaller than budget.getAvailableAmount(). This option is not the best one, since at least 1 wei will be locked forever.
Resolution
Fixed with option (a). Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
calculateFreezableAmountForBudgetLeft(...) performs division before multiplication| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | 7107cc5 | Low | Fixed |
The function getFreezableAmount(...) performs division before the multiplication. Solidity integer division might truncate. As a result, performing multiplication before division can sometimes avoid loss of precision. The function with audit comments is reproduced below.
function calculateFreezableAmountForBudgetLeft(uint256 budgetLeft, uint256 rate) private pure returns (uint256) {
/////////////////////////////////////////////////////////////
// @audit Performing multiplication on the result of a division.
/////////////////////////////////////////////////////////////
uint256 amount = budgetLeft * 100 * WEI_PRECISION / ONE_PERCENT_ATTO_WEI_REWARD_PER_SECOND / SECONDS_PER_YEAR / rate;
return amount * 1 ether;
}Recommendation
Perform multiplication before division.
Resolution
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
getFreezableAmount(...) reverts due to overflow| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | 7107cc5 | Low | Fixed |
The function getFreezableAmount(...) returns the amount that can be freezed by the user. However, whenever the user has claimerFreezable less than freezingThresholdLimit the function reverts. The reversion is due to an overflow in the last line of the function (reproduced below).
function getFreezableAmount(address claimer) public view returns (uint256) {
///////////////////////////////////////////////////////////////////////
// @audit Function can have external visibility
///////////////////////////////////////////////////////////////////////
uint256 claimerFreezable = maxFreezableAmountPerAddress - getTotalFrozenAmount(claimer);
uint256 budgetLeft = getAvailableFreezingBudget();
if (budgetLeft == 0)
return 0;
(uint256 rate, ) = determineRate(claimer);
uint256 toReserve = calculateBudgetToReserve(claimerFreezable, rate);
if (toReserve > budgetLeft) {
// we cannot reserve the full claimable amount -> lets inverse calculate with the rest
claimerFreezable = calculateFreezableAmountForBudgetLeft(budgetLeft, rate);
return claimerFreezable; // freezingThresholdLimit already considered in budgetLeft, no need to subtract!
}
///////////////////////////////////////////////////////////////////////
// @audit Function reverts due to overflow when user has freezed the
// whole amount. Remember that Solidity 0.8.* uses SafeMath.
///////////////////////////////////////////////////////////////////////
return claimerFreezable - freezingThresholdLimit;
}Whenever claimerFreezable is between 0 and freezingThresholdLimit-1, the subtraction claimerFreezable - freezingThresholdLimit will overflow and the function will revert.
Recommendation
Mitigate the underflow error by validating that claimerFreezable is greater than or equal to freezingThresholdLimit. Otherwise return 0.
Resolution
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.solcontracts/EVaultCampaign.solcontracts/EVaultCampaignBudget.sol | — | Low | Acknowledged |
Users may freeze only in the active campaign. A new campaign may be created when the current active campaign has less than 1 ether. If a new campaign is created when the current active campaign still has freezable funds (< 1 ether), those funds would be locked in the campaign forever.
After some clarification from the client, there is no withdrawal function in the budget contract on purpose in order to guarantee that nobody has access to the budget funds except the users freezing funds. The only way for the protocol to get the funds out again is to freeze on our own funds for the remaining budget and claim it one year later (or earlier for partial access).
Recommendation
We are okay with the clarification provided by the client. In order to contribute, we present some comments below that maybe can help the application. When creating a new campaign, the first step could be accumulating the balance of all users into a new vault contract (invested amount plus rewards). Once these funds are transferred to the vault contract, remaining funds in the active campaign can be transferred to a new campaign that is about to be created. By doing so, users will withdraw the funds from all finished campaigns in one single transaction from the vault contract. The simplified flow for creating a campaign is presented below.
if the current campaign has budget < 1 ether then
create and activate the new campaign;
end ifIn summary, the decision of creating a new campaign is made based on the available balance of the current campaign, and the code does not engage in special actions for the campaign that is being terminated. Below we present another possible flow.
if the current campaign has budget < 1 ether then
transfer the rewards of each user from the current campaign to the balance of the user in the Vault contract;
transfer the freezed values from each user from the current campaign to the balance of the user in the Vault contract;
create the new campaign;
transfer the remaining budget in EVaultCampaignBudget from the current campaign to the new campaign;
finish the current campaign avoiding new values to be freezed or funded into this campaign;
formally activate the new campaign;
end ifResolution
Valid point and the suggestion is really appreciated. Having this issue in mind we have also created a halfshaped prototype version to replace tracking of FrozenAmount objects with a contract deployment per freezing() and just store list of contract addresses per freezer/campaign in order to get rid of homebrew bookkeeping logic and let EVM track the state of the funds. Due to the project timeline we have to postpone such an improved version to V2 of the protocol.
| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | 7107cc5 | Low | Fixed |
The functions claim(...) and claimForSender(...) call calculateRewardDueAndUpdateStorage(...) to calculate the reward claimable for all frozen amounts and pay the unlocked amounts from the campaign. This function calls transfer(...) within a loop. There are different reasons why sending assets to another address may fail. One reason for failure is running out of gas, e.g., many transfers made within a single function call. Another example that results in failure is if the receiver is not able to receive funds via transfer. So, every new attempt to transfer toUnlock amount to the claimer will result in an exception, thus, making it impossible to pay unlocked amounts from the campaign. To minimize the damage caused by these failures, it would be a better choice to isolate external calls into its own transaction, initiated by the claimer. If possible, avoid combining multiple transfers in a single transaction. The code is reproduced below.
function calculateRewardDueAndUpdateStorage(address claimer) private returns (uint256) {
...
for (uint i; i < frozenSenderAmounts.length; i++) {
FrozenAmount storage fa = frozenSenderAmounts[i];
(uint256 rewardWei, uint256 toUnlock) = calculateRewardWei(fa);
totalDue += rewardWei;
if (toUnlock > 0) {
fa.returned = true;
////////////////////////////////////////////
// @audit Multiple transfers
////////////////////////////////////////////
payable(claimer).transfer(toUnlock);
emit VaultReturn(fa.blockNumber, toUnlock);
}
...
}
...
}Recommendation
There are some options to address this issue: a) all the values can be transferred to the user in a single transaction; b) let the claimer "pull" the amounts, instead of "pushing" the values into the claimer. The protocol can store the value able to be claimed from all campaigns into a single storage variable for each user. For more information on the attack discussed here, please check this reference.
Resolution
As the receiver is always the same single address (the claimer who can only claim his very own funds to his same address) the risk of having single transfers failing is neglectable (only a matter of gas, which is anyway pre-estimated by wallet via eth_estimateGas call). Nevertheless it is valid that multiple transfers in a loop result in increased gas consumption which will be fixed by doing only one single transfer call with summed up total amount after the loop while still emitting multiple VaultReturn events to track individual returns. Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | 7107cc5 | Low | Fixed |
The calculateRewardDueAndUpdateStorage(...) and freeze(...) functions are not following the checks-effects-interactions pattern. This pattern indicates that the function must perform all the checks in the first place. After checking, the function must do all state updates. Only after the updates, the function must interact with external contracts.
We can notice that the function calculateRewardDueAndUpdateStorage(...) applies state changes after the function transfer(...). The code is reproduced below.
function calculateRewardDueAndUpdateStorage(address claimer) private returns (uint256) {
FrozenAmount[] storage frozenSenderAmounts = frozenAmounts[claimer];
...
for (uint i; i < frozenSenderAmounts.length; i++) {
...
if (toUnlock > 0) {
fa.returned = true;
//////////////////////////////////////////////////////
// @audit Interacting with external contracts
// and making state updates after.
//////////////////////////////////////////////////////
payable(claimer).transfer(toUnlock);
emit VaultReturn(fa.blockNumber, toUnlock);
}
uint256 rewardNew = rewardWei - fa.withdrawn;
totalWithdrawnByClaimer[claimer] += rewardNew;
fa.withdrawn = rewardWei;
emit VaultReward(fa.blockNumber, rewardNew);
}
return totalDue - claimerWithdrawn;
}Similarly, the function freeze(...) applies state changes after calling the external functions getAvailableAmount() and reserve(...). The code is reproduced below.
function freeze(address sender) public payable onlyOwner {
...
uint256 toReserve = calculateBudgetToReserve(msg.value, rate);
require(toReserve <= budget.getAvailableAmount(), 'freeze: no budget left anymore');
budget.reserve(toReserve);
FrozenAmount[] storage frozenSenderAmounts = frozenAmounts[sender];
if (frozenSenderAmounts.length > 0) {
require(frozenSenderAmounts[frozenSenderAmounts.length - 1].blockNumber != getBlockNumber(), 'freeze: sender,! already did a freezing in same block');
}
FrozenAmount memory fa = FrozenAmount(msg.value, getBlockNumber(), getBlockTimestamp(), rate, 0, false);
frozenSenderAmounts.push(fa);
emit VaultLock(fa.blockNumber, msg.value, rate, subscription);
}Since the contract is using transfer(...), the contract will be safe by adopting the checks-effects-interactions pattern. However, if you change transfer(...) to call(...), the contract becomes highly vulnerable to reentrancy attacks.
Recommendation
Always apply the checks-effects-interactions pattern when writing smart contracts. Keep using transfer(...). Discuss the possibility of adding the nonReentrant modifier.
Resolution
calculateRewardDueAndUpdateStorage() fixed by changes from the issue Multiple transfers can be avoided (risk of out-of-gas failures). Function freeze() is fixed by moving contract calls to the end of function.
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
msg.value can grow storage unlimitedly| File | Fix commit | Type | Status |
contracts/EVaultCampaign.solcontracts/EVaultCampaigns.sol | 7107cc5 | Low | Fixed |
The payable functions below do not validate msg.value for being greater than zero.
EVaultCampaign.freeze(...);
EVaultCampaigns.freeze(...);
EVaultCampaign.fund();
EVaultCampaigns.fund();The lack of validation in the function EVaultCampaigns.freeze(...) is not desired, since new entries will be created in the storage structure EVaultCampaign.frozenAmounts that can grow indefinitely. The code of EVaultCampaigns.freeze() is presented below.
function EVaultCampaigns.freeze() public payable {
EVaultCampaign activeCampaign = getActiveCampaign();
return activeCampaign.freeze{value: msg.value}(msg.sender);
}As we can notice, the function EVaultCampaigns.freeze() calls EVaultCampaign.freeze(), whose code is reproduced below and we can note the command frozenSenderAmounts.push(fa).
function freeze(address sender) public payable onlyOwner {
require (maxFreezableAmountPerAddress - getTotalFrozenAmount(sender) >= msg.value, 'freeze: msg.value of sender,! above max freezable amount');
uint256 rate; uint256 subscription;
(rate, subscription) = determineRate(sender);
uint256 toReserve = calculateBudgetToReserve(msg.value, rate);
require(toReserve <= budget.getAvailableAmount(), 'freeze: no budget left anymore');
budget.reserve(toReserve);
FrozenAmount[] storage frozenSenderAmounts = frozenAmounts[sender];
if (frozenSenderAmounts.length > 0) {
require(frozenSenderAmounts[frozenSenderAmounts.length - 1].blockNumber != getBlockNumber(), 'freeze: sender,! already did a freezing in same block');
}
FrozenAmount memory fa = FrozenAmount(msg.value, getBlockNumber(), getBlockTimestamp(), rate, 0, false);
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// @audit New items are added to the storage without validating "msg.value" for being greater than zero.
///////////////////////////////////////////////////////////////////////////////////////////////////////////
frozenSenderAmounts.push(fa);
emit VaultLock(fa.blockNumber, msg.value, rate, subscription);
}Recommendation
In payable functions, always check if msg.value is greater than zero. Revert otherwise.
Resolution
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
EVaultCampaigns.fund()| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.solcontracts/EVaultCampaign.solcontracts/EVaultCampaignBudget.sol | 7107cc5 | Low | Fixed |
The fund functionality is not respecting the specification, which defines that funding must occur only through the function EVaultCampaigns.fund(). The paragraph 1.1.4 of the specification is reproduced below.
1.1.4 Anybody is allowed to extend Allocated Budget of the Campaign. Additional funding always goes to the latest,! created campaign even if it has not started yet (to fulfill 1.1.3 and prevent extension of the old campaign after,! the new one is already created/scheduled).
However, the contracts EVaultCampaign and EVaultCampaignBudget have a public function fund(), and the user can bypass the contract EVaultCampaigns. The functions EVaultCampaign.fund() and EVaultCampaignBudget.fund() are reproduced below.
// EVaultCampaign
function EVaultCampaign.fund() public payable {
budget.fund{value: msg.value}();
}
function EVaultCampaignBudget.fund() public payable {
emit CampaignFunded(msg.value);
}Recommendation
Add access control to functions EVaultCampaign.fund() and EVaultCampaignBudget.fund().
Resolution
Fixed by adding onlyOwner modifier to EVaultCampaign.fund() and EVaultCampaignBudget.fund(). Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
maxFreezableAmountPerAddress| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.sol | — | Info | Acknowledged |
The check for available amount to freeze for each address is done by subtracting the value of getTotalFrozenAmount(claimer) from the maxFreezableAmountPerAddress. However, the function getTotalFrozenAmount(...) sums frozen amounts that have not been claimed yet. Thus, any address can freeze the maximum amount, claim it, and then freeze again exceeding maxFreezableAmountPerAddress.
Recommendation
This is a business decision. In case one address cannot freeze amounts above maxFreezableAmountPerAddress, keep track of all the deposits. On the other hand, to circumvent this restriction, the user can create another address.
Resolution
Known limitation of the current max freezing amount protection logic. As stated it could be circumvented anyway if someone does not use our mobile wallet but instead interacts with the contract directly with another address.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.solcontracts/EVaultCampaign.solcontracts/EVaultCampaignBudget.sol | — | Info | Fixed |
The contracts are not keeping track of the funders, being impossible to return funds when the campaign is over. Also notice that the three contracts have a public function fund(), which does not add clarity on how the functionality should be used.
Recommendation
Clearly specify the use case related to funders. If necessary, keep track of funders. Also enforce funding to be made using the function EVaultCampaigns.fund(), and restrict the access to EVaultCampaign.fund() and EVaultCampaignBudget.fund() to onlyOwner.
Resolution
Funders are tracked off-chain by processing and parsing all transactions to the contracts from the backend. In case funds are not claimed theoretically we can notify the users as we have firebase push Ids. Funding should be available for everybody.
Update from Nethermind Security
We agree and we consider this point of attention as fixed.
| File | Fix commit | Type | Status |
contracts/EVaultCampaign.solcontracts/EVaultCampaigns.sol | — | Info | Fixed |
Index event parameters for logged events allow you to search them more quickly by using the indexed fields as filters. Up to three fields can receive the attribute indexed. It’s possible to filter for particular values of indexed fields in the user interface. However, it’s important to remember that each index parameter costs extra gas during emission.
Recommendation
Consider using indexed fields to make them accessible quicker to tools that parse events.
Resolution
Indexed fields omitted to save gas as those events are only parsed by backend.
Update from Nethermind Security
We agree. Since this decision does not impose any risk to the protocol, we consider this point of attention as resolved (fixed).
calculateRewardsForSeconds(...) can be slightly optimized| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | — | Info | Fixed |
The function calculateRewardsForSeconds(...) can be optimized by joining all divisions into one single operation. The current code is reproduced below, and it requires 23,757 gas units.
function calculateRewardsForSeconds(uint256 amount, uint256 rate, uint256 sec) private pure returns (uint256) {
uint256 rewardDueAttoWei = amount * ONE_PERCENT_ATTO_WEI_REWARD_PER_SECOND * sec * rate / 100 / WEI_PRECISION;
return rewardDueAttoWei / 1 ether;
}The proposed version is presented below, and it consumes 23,425 gas units (saving 332 gas units).
function opt_calculateRewardsForSeconds(uint256 amount, uint256 rate, uint256 sec) private pure returns (uint256) {
return (amount * ONE_PERCENT_ATTO_WEI_REWARD_PER_SECOND * sec * rate ) / 1e24;
}Recommendation
Evaluate the possibility of adopting the optimized function.
Resolution
Gas is not critical here. Keeping the old version in favor of readability.
Update from Nethermind Security
We agree and we consider this point of attention as resolved (fixed).
subscriptionNftAddress for address(0x0)| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.sol | 7107cc5 | Info | Fixed |
The immutable storage variable EVaultCampaigns.subscriptionNftAddress is not checked for address(0x0) in the constructor of EVaultCampaigns. The code is reproduced below.
address internal immutable subscriptionNftAddress;
constructor (address _subscriptionNftAddress) {
subscriptionNftAddress = _subscriptionNftAddress;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setRoleAdmin(CAMPAIGN_CREATOR_ROLE, DEFAULT_ADMIN_ROLE);
}Recommendation
Ensure that _subscriptionNftAddress is different from address(0x0). An interesting approach is to change the type of the variable subscriptionNftAddress from address to SubscriptionNFT as presented below.
- address internal immutable subscriptionNftAddress;
+ SubscriptionNFT internal immutable subscriptionNftAddress;Resolution
Address validation added. Address type still used as the address is just passed through to EVaultCampaign() contract constructor. Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.solcontracts/EVaultCampaign.solcontracts/EVaultCampaignBudget.sol | 7107cc5 | Info | Fixed |
The new campaign may be added only if the current active campaign has balance smaller than 1 ether. However, anyone can fund old campaigns by calling the functions EVaultCampaignBudget.fund(), EVaultCampaign.fund(), EVaultCampaign.fund(). Funding old campaigns is not expected by the protocol. The functions are reproduced below.
function EVaultCampaigns.fund() public payable {
EVaultCampaign activeCampaign = getActiveCampaign();
activeCampaign.fund{value: msg.value}();
}
function EVaultCampaign.fund() public payable {
budget.fund{value: msg.value}();
}
function EVaultCampaignBudget.fund() public payable {
emit CampaignFunded(msg.value);
}Recommendation
Ensure that only the newest campaign can be funded.
Resolution
This is known behavior. If anyone is generous enough it’s up to him to fund old campaigns (whose funds will never be used as EVaultCampaigns redirects all calls to current active campaign contract only). The only problem could be that someone might keep the campaign alive by constantly funding it so the EVaultCampaigns.addCampaign() will not allow the creation of a new campaign as there are still funds on the old one (fixed as part of the next issue). Fixed by adding onlyOwner modifier to EVaultCampaign.fund() and EVaultCampaignBudget.fund() essentially allowing only EVaultCampaigns to fund the latest campaign. Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | 7107cc5 | Info | Fixed |
The functions getTotalFrozenAmount(...), calculateRewardDue(...) and getFreezeInfo(...) access the struct FrozenAmount in a loop directly from the storage. Accessing storage variables in loops is expensive. Instead, we can access the storage variable from the memory. Note that those are view functions. The functions are reproduced below.
function getTotalFrozenAmount(address claimer) public view returns (uint256 totalFrozen) {
FrozenAmount[] storage freezingsByClaimer = frozenAmounts[claimer];
for (uint i; i < freezingsByClaimer.length; i++) {
if (!freezingsByClaimer[i].returned) {
totalFrozen += freezingsByClaimer[i].amount;
}
}
}
function calculateRewardDue(address claimer) public view returns (uint256) {
FrozenAmount[] storage frozenSenderAmounts = frozenAmounts[claimer];
uint256 claimerWithdrawn = totalWithdrawnByClaimer[claimer];
uint256 totalDue = 0;
for (uint i; i < frozenSenderAmounts.length; i++) {
FrozenAmount storage fa = frozenSenderAmounts[i];
(uint256 rewardWei, uint256 toUnlock) = calculateRewardWei(fa);
totalDue += rewardWei + toUnlock; // here we add both rewards and unlocked amount to indicate gross amount to,! wallet
}
return totalDue - claimerWithdrawn;
}
function getFreezeInfo(address claimer, uint256 blockNumber)
external view returns (uint256 rate, uint256 rewardDue, uint256 withdrawn) {
FrozenAmount[] storage frozenSenderAmounts = frozenAmounts[claimer];
for (uint i; i < frozenSenderAmounts.length; i++) {
FrozenAmount storage fa = frozenSenderAmounts[i];
if (fa.blockNumber == blockNumber) {
(rewardDue, ) = calculateRewardWei(fa);
withdrawn = fa.withdrawn;
rate = fa.rate;
break;
}
}
}Recommendation
Replace the identifier storage per memory as shown below.
function getTotalFrozenAmount(...)
- FrozenAmount[] storage freezingsByClaimer = frozenAmounts[claimer];
+ FrozenAmount[] memory freezingsByClaimer = frozenAmounts[claimer];
function calculateRewardDue(...)
- FrozenAmount[] storage frozenSenderAmounts = frozenAmounts[claimer];
+ FrozenAmount[] memory frozenSenderAmounts = frozenAmounts[claimer];
function getFreezeInfo(...)
- FrozenAmount[] storage frozenSenderAmounts = frozenAmounts[claimer];
+ FrozenAmount[] memory frozenSenderAmounts = frozenAmounts[claimer];Resolution
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.solcontracts/EVaultCampaign.solcontracts/EVaultCampaignBudget.sol | 7107cc5 | Info | Fixed |
The contracts use unlocked pragma ˆ0.8.2. A better approach is to stick to a single Solidity version. solc frequently releases new compiler versions. Using an old version prevents access to new Solidity security checks. Also notice that some versions are more stable than others.
Recommendation
Lock the pragma to version 0.8.16 and use this version for deploying the contracts. For more information, please check this reference.
Resolution
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
campaigns in EVaultCampaigns| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.sol | 7107cc5 | Info | Fixed |
The contract EVaultCampaigns uses a mapping for storing the campaigns. Mappings are hash tables that use hash functions to generate new values according to a mathematical hashing algorithm, and they are widely used when we need to reduce the search time from a) O(n) when the elements are unsorted or b) O(log(n)) when the elements are sorted down to O(1). However, the campaigns are indexed by integers in a sequential way, and there’s no need to have the extra overhead imposed by mappings/hash tables. Instead of using a mapping, you can rely on an array of campaigns. The code snippet is reproduced below.
//////////////////////////////////////////////////////////////////////////////////////////////
// @audit Declaring the “campaigns” as a mapping.
// You can use an array.
//////////////////////////////////////////////////////////////////////////////////////////////
mapping(uint => address) private campaigns;
function addCampaign(...) external onlyRole(CAMPAIGN_CREATOR_ROLE) {
////////////////////////////////////////////////////
// @audit "campaigns" is accessed as an array.
////////////////////////////////////////////////////
address activeCampaignAddress = campaigns[activeCampaignId];
...
address campaignAddress = createCampaign(freezingThresholdLimit, maxFreezableAmount);
////////////////////////////////////////////////////
// @audit "campaigns" is accessed as an array.
////////////////////////////////////////////////////
uint256 campaignId = activaCampaignAddress == address(0) ? 0 : activeCampaignId + 1; // first campaign already,! created?
////////////////////////////////////////////////////
// @audit Here is where you would "push" a new
// campaign into the array.
////////////////////////////////////////////////////
campaigns[campaignId] = campaignAddress;
activeCampaignId = campaignId;
...
}Recommendation
Instead of using a mapping for campaigns, consider adopting an array.
Resolution
Refactored using array. Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
EVaultCampaign.sol imports itself| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | 7107cc5 | Info | Fixed |
The contract EVaultCampaign.sol imports itself, as reproduced in the code snippet below.
pragma solidity ^0.8.2;
import '@openzeppelin/contracts/access/Ownable.sol';
////////////////////////////////////////////////////////////
// @audit "EVaultCampaign.sol" is importing itself
////////////////////////////////////////////////////////////
import './EVaultCampaign.sol';
import './EVaultCampaignBudget.sol';
import './SubscriptionNFT.sol';Recommendation
Do not import EVaultCampaign.sol inside EVaultCampaign.sol.
Resolution
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.solcontracts/EVaultCampaign.solcontracts/EVaultCampaignBudget.sol | 7107cc5 | Best Practices | Fixed |
All the contracts in scope don’t follow the NatSpec standard.
Recommendation
It is recommended that Solidity contracts are fully annotated using NatSpec.
Resolution
Fixed. Comments added to all contracts and external functions.
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.sol | 7107cc5 | Best Practices | Fixed |
The require(...) string "addCampaign: there is another campaign still active" has a length of 51 bytes.
Recommendation
Consider reducing the length of this string up to 32 bytes.
Resolution
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
claimer / sender| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | — | Best Practices | Acknowledged |
Emitting events is a good practice and helps to improve protocol monitoring. Events related to the vault are linked to a smart contract (the active campaign) but they don’t mention the sender or claimer of funds.
Recommendation
Modify the events below to add the concerned sender/claimer of funds.
/* event fired on successful claiming per frozen amount rewarded by the claim */
event VaultReward(
address user
uint256 frozenAmountId,
uint256 amount,
uint256 rate,
uint256 subscription
);
/* event fired on successful claiming for each frozen amount older than one year (and returned by claim) */
event VaultReturn(
address user
uint256 frozenAmountId,
uint256 amount
);
/* event fired on successful freezing */
event VaultLock(
address user
uint256 frozenAmountId,
uint256 amount,
uint256 rate,
uint256 subscription
);Resolution
Claimer is always the sender of the transaction so not needed for implementation. Actually We had it there in the beginning, but then we removed it to shrink event data. If it’s considered best practice we will add it to new events next time - changing event signatures now would mean a bunch of changes in front-end and backend-end which we would like to avoid.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.sol | 7107cc5 | Best Practices | Fixed |
The functions getClaimableAmount(...), claim(...), getFreezeInfo(...) can use a local variable to hold the value of activeCampaignId when performing loops for saving gas. The code snippets of these functions are reproduced below.
function getClaimableAmount(...) ... {
///////////////////////////////////////////////////////
// @audit Avoid using storage variables inside loops.
///////////////////////////////////////////////////////
for (uint i; i <= activeCampaignId; i++) {
...
}
}
function claim() external {
///////////////////////////////////////////////////////
// @audit Avoid using storage variables inside loops.
///////////////////////////////////////////////////////
for (uint i; i <= activeCampaignId; i++) {
...
}
}
function getFreezeInfo(...) ... returns (uint256 rate, uint256 rewardDue, uint256 withdrawn) {
///////////////////////////////////////////////////////
// @audit Avoid using storage variables inside loops.
///////////////////////////////////////////////////////
for (uint i; i <= activeCampaignId; i++) {
...
}
}Recommendation
Create a local variable to store the contents of the storage variable activeCampaignId. Use the local variable inside the loops as shown below.
- for (uint i; i <= activeCampaignId; i++)
+ uint256 local = activeCampaignId;
+ for (uint i; i <= local; i++)Resolution
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.solcontracts/EVaultCampaign.solcontracts/EVaultCampaignBudget.sol | 7107cc5 | Best Practices | Fixed |
The functions below can have external visibility since they are called outside of the contract. This can also result in gas savings.
- EVaultCampaign.getFreezableAmount(address)
- EVaultCampaign.freeze(address)
- EVaultCampaign.getTotalRewardWithdrawn(address)
- EVaultCampaign.calculateRewardDue(address)
- EVaultCampaign.fund()
- EVaultCampaign.claim()
- EVaultCampaign.claimForSender(address)
- EVaultCampaignBudget.fund()
- EVaultCampaigns.freeze()
- EVaultCampaigns.fund()Recommendation
Make these functions external.
Resolution
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | 7107cc5 | Best Practices | Fixed |
The contract EVaultCampaign.sol uses functionalities implemented in the contract SubscriptionNFT.sol by importing the whole file. The recommended approach is to define interfaces that should be imported when modules interact.
Recommendation
Create an interface for the contract SubscriptionNFT.sol and make all access considering the interface.
Resolution
Fixed using @openzeppelin/contracts/token/ERC1155/IERC1155.sol.
Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
activeCampaignAddress instead accessing the storage twice| File | Fix commit | Type | Status |
contracts/EVaultCampaigns.sol | 7107cc5 | Best Practices | Fixed |
The function addCampaign(...) reads the value of the storage variable campaigns[activeCampaignId] twice. The function can be optimized by using the memory variable activeCampaignAddress directly. The code snippet with audit comments is reproduced below.
function addCampaign(...) external onlyRole(CAMPAIGN_CREATOR_ROLE) {
address activeCampaignAddress = campaigns[activeCampaignId];
if (activeCampaignAddress != address(0)) {
/////////////////////////////////////////////////////////////
// @audit No need to read the storage again.
// The content is already saved in "activeCampaignAddress".
/////////////////////////////////////////////////////////////
EVaultCampaign activeCampaign = EVaultCampaign(campaigns[activeCampaignId]);
...
}
...
}Recommendation
Use the activeCampaignAddress instead of making a second access to the storage as reproduced below.
- EVaultCampaign activeCampaign = EVaultCampaign(campaigns[activeCampaignId]);
+ EVaultCampaign activeCampaign = EVaultCampaign(activeCampaignAddress);Resolution
activeCampaignAddress not needed anymore due to fix of Unnecessary use of a mapping for storing the campaigns in EVaultCampaigns. Fixed in commit hash 7107cc5ad957d5491bdb862820653b84cb051b39.
bool in storage is more expensive than uint256| File | Fix commit | Type | Status |
contracts/EVaultCampaign.sol | — | Best Practices | Acknowledged |
Booleans in storage are more expensive than uint256, since an extra SLOAD operation is required to read the slot content, replace the bit taken up by the boolean, and then write it back. More information can be found here. We reproduce the struct FrozenAmount below.
struct FrozenAmount {
uint256 amount;
uint256 blockNumber;
uint256 timestamp;
uint256 rate;
uint256 withdrawn;
bool returned;
}Recommendation
Use uint256 instead of bool for the field returned as shown below.
- bool returned;
+ uint256 returned;Resolution
Omitted in favor of readability.
Update from Nethermind Security
We agree in favoring readability.
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:
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.
The client has provided the high level description of the system and the most important use cases, as reproduced below.
1. Consumers and Businesses are allowed to freeze funds on eVault. The amount specified by the user (Frozen amount) is,! sent to the smart contract where it is locked for the next 12 months.
1.1. Amounts are frozen in scope of Campaign (not related to marketing campaigns in the wallet). Campaign has Start Time,! and Allocated Budget.
1.1.1. Campaign is configured via Backoffice and later created on blockchain.
1.1.2. Campaign cannot be cancelled as it is created on blockchain.
1.1.3. There can't be two Campaigns running in parallel.
1.1.4. Anybody is allowed to extend Allocated Budget of the Campaign. Additional funding always goes to the latest,! created campaign even if it hasn't started yet. (to fulfil 1.1.3 and prevent extension of the old campaign after the,! new one is already created/scheduled).
1.2. Users are allowed to freeze ECS from their reference addresses as long as the smart contract allows it as many,! times as they wish.
1.2.1. By default users are rewarded with 2% in ECS. Users with Gold subscription are rewarded with 3% in ECS. Users,! with Platinum subscription are rewarded with 6% in ECS.
1.2.2. Purchasing of Gold or Platinum subscription does not change the reward of the existing Frozen Amounts.
1.2.3. Users with Gold subscription are allowed to vault 1 hour before Campaign start. Users with Platinum - 2 hours,! before Campaign starts.
1.2.4. Upon each Frozen Amount the Total Reward is calculated according to the current subscription of the user (if,! there is Golden or Platinum NFT on the freezing address). Smart contract controls if the Total Reward exceeds the,! available Allocated Budget of the Campaign.
1.3. Users are allowed to claim Due Rewards. Due Reward is calculated by the smart contract ad-hoc and grows with each,! blockchain block.
1.3.1. As the frozen amount is ready to be unlocked it can be claimed together with the remaining reward.
Note: ECS is the equivalent of ETH (native currency in our network),! buffer)...,! thrown: Error: VM Exception while processing transaction: reverted with reason string 'AccessControl: account,! 0xb04a130920446963efaaf51c4a9ba7d471a2c428 is missing role,! 0x9f2df0fed2c77648de5860a4cc508cd0818c85b8b8a1ab4ceeef8d981c8956a6'
The output is presented below.
| 39Tests passed | 2Failed |
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.
The Leading Engineers of Blockchain Infrastructure