TruFin
MATIC Staking

TruFin gives institutions access to MATIC staking with auto-compounding rewards, open only to KYC'd users. We reviewed the ERC-4626 staking vault and how rewards are allocated and distributed.
report id
0098
category
DeFi & Yield
language
Solidity
final report
June 13, 2023
lines of code
1324
Content

Download audit report

1

Executive Summary

This document outlines the security review conducted by Nethermind for the TruFin protocol. TruFin provides access to MATIC staking on Ethereum for institutions featuring auto-compounding of rewards and the ability to allocate rewards to other addresses. The protocol is permissioned, ensuring that each user has passed know-your-customer (KYC) checks and that only whitelisted users can stake. A user’s stake is represented by ERC4626 tokens which track the increase in value from the accrual of rewards.

The audited code comprises 1,324 lines of Solidity, with a code test coverage of 97.22% for the primary contract TruStakeMATICv2. The TruFin team has provided detailed documentation explaining the protocol summary, deposit/withdraw flows, precision and rounding choices, and rewards allocation/distribution.

The audit was performed using (a) manual analysis of the codebase, (b) automated analysis tools, (c) simulation of the smart contracts, and (d) creation of test cases.

Audit assessment
Audit TypeSecurity Review
Initial ReportJune 5, 2023
Response from ClientJune 12, 2023
Final ReportJune 13, 2023
MethodsManual Review, Automated Analysis
Repositoryhttps://github.com/TruFin-io/staker-audit-april/
Commit Hash (Initial Audit)e5065cb2e3
Branch (Review Audit)Branch: fixes-1
DocumentationProvided protocol documentation (PDFs)
Documentation AssessmentHigh
Test Suite AssessmentHigh
Total findings
11
Fixed
10
Acknowledged
1
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High0
  • Medium2
  • Low1
  • Informational1
  • Best Practices7

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1main/TruStakeMATICv2.sol91541245.0%2791606
2main/TruStakeMATICv2Storage.sol2828100.0%2076
3helpers/MasterWhitelist.sol29525887.5%85638
4interfaces/IValidatorShare.sol15320.0%1331
5interfaces/IStakeManager.sol5523.6%2178
6interfaces/IMasterWhitelist.sol1639243.8%1065
Total132474256.0%4282494

4

System Overview

No system overview is included in this report.

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 Changing stakingTokenAddress will affect share pricing and staking calculations

FileFix commitTypeStatus
TruStakeMATICv2.sol—MediumFixed

In the TruStakeMATICv2 contract, it is possible to change the staking token through the function setStakingToken(...). However, it does not consider that the ERC4626 private storage variable _asset won’t be changed. Most original functions that rely on _asset have been overridden to use stakingTokenAddress, except for totalAssets(...). This means that when a new staking token is used, totalAssets(...) will return the balance count for the original token used during initialization. The following functions use totalAssets(...) and may be affected:

  • sharePrice(...);
  • _deposit(...);
  • _withdrawRequest(...);
  • compoundRewards(...);

Incorrect reported staking token balances through totalAssets(...) may affect share pricing and rewards and staking calculations.

Recommendation

Consider overriding the totalAssets(...) function to return the balance of stakingTokenAddress instead of _asset.

Resolution

Setting the token address is now only possible at initialization time to prevent the issues evoked above.

6.2 Inflation attack can lead to loss of value for depositors

FileFix commitTypeStatus
TruStakeMATICv2.sol—MediumFixed

In the TruStakeMATICv2 contract, the initial depositor can use an inflation attack to cause the second depositor to pay more than expected for their shares, leading to a loss of value. The steps to manipulate the pricing are shown below:

1. Attacker makes an initial deposit of 1 MATIC using the function deposit(. . . ); 2. Attacker immediately requests for a withdrawal of 0.9 MATIC, leaving a small amount remaining; 3. Before the second depositor starts their deposit, the attacker directly transfers a large amount of MATIC to the contract (without depositing);

After these steps, the second deposit will calculate pricing based on a higher share price since part of the pricing calculation is to check the balance of assets on the contract, which has been manipulated due to a direct transfer.

Recommendation

Consider establishing a minimum remaining balance amount after withdrawal, and if a withdrawal leads to a remaining amount less than this minimum, then withdraw the entire user’s balance.

Resolution

We fixed this issue by not allowing users to leave small amounts in the vault.

6.3 The setCap(...) function can set a cap lower than the current deposited amount

FileFix commitTypeStatus
TruStakeMATICv2.sol—LowFixed

The function setCap(...) is missing input validation to prevent the cap from being lower than the current deposited amount. Without this check, the following logic in maxDeposit(...) could revert due to an underflow.

function maxDeposit(address) public view override returns (uint256) {
return cap - totalStaked();
}

Recommendation

Consider adding input validation to setCap(...) to prevent a cap smaller than the deposit amount from being set.

Resolution

We check the cap is always set to be higher than the totalStaked.

6.4 Shadowed variables and functions

FileFix commitTypeStatus
TruStakeMATICv2.sol—InfoFixed

The TruStakeMATICv2 contract contains some functions which have variables with the same name as storage variables or functions from other imported contracts. This can lead to confusion where it may be unclear which data the variables are actually referring to. A list of all the shadowing variables are presented below:

  • distributeAll(...): Variable totalAllocated shadows storage variable TruStakeMATICv2Storage.totalAllocated;
  • maxWithdraw(...): Argument owner shadows function OwnableUpgradeable.owner(...);
  • maxRedeem(...): Argument owner shadows function OwnableUpgradeable.owner(...);
  • getUserInfo(...): Argument _owner shadows storage variable OwnableUpgradeable._owner;
  • withdraw(...): Argument owner shadows function OwnableUpgradeable.owner(...);
  • redeem(...): Argument owner shadows function OwnableUpgradeable.owner(...);

Recommendation

Consider changing the names of the variables and arguments listed above to ensure they do not have the same name as existing inherited functions or storage variables.

Resolution

All shadowing variables have been renamed.

6.5 Boolean comparisons can be avoided

FileFix commitTypeStatus
TruStakeMATICv2.sol—Best PracticesFixed

In the function allocate(...) boolean comparisons are used as below:

function allocate(
uint256 _amount,
address _recipient,
bool _strict
) external onlyWhitelist nonReentrant {
if (_strict == true && allowStrict == false) {
revert StrictAllocationDisabled();
}
...
}

Recommendation

Boolean comparisons can be simplified. The above can be simplified as below.

if (_strict && !allowStrict) {
revert StrictAllocationDisabled();
}

Resolution

We removed the boolean comparison per the recommendation.

6.6 Usage of outdated solidity compiler

FileFix commitTypeStatus
contracts—Best PracticesFixed

Solidity pragma version 0.8.14 is used in all contracts. Version 0.8.14 has some known optimizer-related bugs.

Recommendation

Consider using an updated and stable version like 0.8.18 of solidity.

Resolution

The compiler has been updated to 0.8.19.

6.7 Using enum instead of arbitrary number for userType.

FileFix commitTypeStatus
MasterWhitelist.sol—Best PracticesAcknowledged

In the contract MasterWhitelist, the userTypes in the events are declared by arbitrary numbers. It is mentioned in the comments:

* @param userType can take values 0,1,2,3,4 if the address is a user, market maker, vault, lawyer, or swapManager respectively

But it would be easier for readability to have enums instead of numbers to describe the user types and less prone to mistakes.

Recommendation

Consider using enums that describe the type of user.

Resolution

Other parts of the system (on-chain and off-chain) are relying on these numbers today, so changing them will require a more coordinated effort on our part. We’re also planning to add more KYC providers so we’ll make these changes at that time.

6.8 Incorrect comment in reallocate(...)

FileFix commitTypeStatus
TruStakeMATICv2.sol—Best PracticesFixed

In TruStakeMATICv2, the function reallocate(...), if you are reallocating to a user that you already have an allocation for, the recipients array, is searched for the _oldRecipient and replaced by the _newRecipient by directly overwriting. However, the comment appears to be copied from a different section of the code, as it refers to popping an item in the array, which does not happen in this part of the code.

Recommendation

Consider updating the comment to accurately reflect the approach to updating the recipients array.

Resolution

This comment has been updated, along with other comments in the contract, to more accurately reflect the code.

6.9 NatSpec documentation refers to outdated variables

FileFix commitTypeStatus
TruStakeMATICv2.sol—Best PracticesFixed

In TruStakeMATICv2 the function sharePrice(...) has NatSpec documentation that refers to two return variables priceNum and priceDenom. However, the variable names and all other returned data from sharePrice(...) refer to the variables as globalPriceNum and globalPriceDenom.

/// @return priceNum numerator of share price, divide by (priceDenom * 1e18) to get actual floating point share price
/// @return priceDenom denominator of share price
function sharePrice() public view returns (uint256, uint256) {
...
//////////////////////////////////////////////////////////////////////
// @audit Returned variable names do not align with NatSpec
//////////////////////////////////////////////////////////////////////
uint256 globalPriceNum = totalCapitalTimesPhiPrecision * 1e18;
uint256 globalPriceDenom = totalSupply() * phiPrecision;
return (globalPriceNum, globalPriceDenom);
}

Recommendation

Consider updating the NatSpec documentation for sharePrice(...) to accurately reflect the return variable names.

Resolution

All NatSpec docs have been updated.

6.10 Solidity code style

FileFix commitTypeStatus
FileName—Best PracticesFixed

The following is a collection of Solidity code style inconsistencies that do not align with the current recommended style guide.

  • The constant phiPrecision should be all uppercase with underscores separating words;

Recommendation

Consider adjusting the code to follow the Solidity style guide.

Resolution

We formatted the contract to be more consistent with the Solidity style guide.

6.11 Unnecessary storage write in deallocate(...)

FileFix commitTypeStatus
TruStakeMATICv2.sol—Best PracticesFixed

In TruStakeMATICv2, the function deallocate(...) has a check to see if the callers totalAllocated amount needs to be cleared entirely or reduced and adjusted. After this if/else block, totalAllocated updated. When totalAmount is zero, the entry is deleted (set to zero) and then set to zero again outside of the if/else block, which is an unnecessary storage write. A code snippet is shown below.

uint256 totalAmount;
uint256 totalPriceNum;
uint256 totalPriceDenom;
Allocation storage totalAllocation = totalAllocated[msg.sender][_strict];
totalAmount = totalAllocation.maticAmount - _amount;

if (totalAmount == 0) {
delete totalAllocated[msg.sender][_strict];
} else {
// Calculate new `totalPriceNum` and `totalPriceDenom`
}

/////////////////////////////////////////////////////////////////////
// @audit When `totalAmount == 0`, `totalAllocated` is cleared twice
/////////////////////////////////////////////////////////////////////
totalAllocated[msg.sender][_strict] = Allocation(totalAmount, totalPriceNum, totalPriceDenom);

Recommendation

Consider moving the totalAllocated update within the else of the if/else block to avoid a double write when totalAmount is zero.

Resolution

This has been fixed in line with the recommendation.

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 TruFin team has provided extensive documentation on their GitHub repo, including an overview of the protocol and technical insights into its components. A summary of these documents is shown below:

  • General Overview
  • Variable and Mappings
  • Precision
  • Deposits and Withdrawals
  • Allocation
  • Distribution
  • Front end values
  • Off-chain (web2) sanity checks

Each function is complemented by detailed NatSpec comments describing function behavior, inputs, and outputs. Moreover, the team conducted a comprehensive code walkthrough and maintained open communication to address any inquiries or concerns raised by the Nethermind auditors.

7.3 Code Coverage

The relevant output is presented below.

Test suite
263Tests 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.