Download audit report
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 Type | Security Review |
| Initial Report | June 5, 2023 |
| Response from Client | June 12, 2023 |
| Final Report | June 13, 2023 |
| Methods | Manual Review, Automated Analysis |
| Repository | https://github.com/TruFin-io/staker-audit-april/ |
| Commit Hash (Initial Audit) | e5065cb2e3 |
| Branch (Review Audit) | Branch: fixes-1 |
| Documentation | Provided protocol documentation (PDFs) |
| Documentation Assessment | High |
| Test Suite Assessment | High |
Findings by severity
| # | Contract | LoC | Comments | Ratio | Blank | Total |
| 1 | main/TruStakeMATICv2.sol | 915 | 412 | 45.0% | 279 | 1606 |
| 2 | main/TruStakeMATICv2Storage.sol | 28 | 28 | 100.0% | 20 | 76 |
| 3 | helpers/MasterWhitelist.sol | 295 | 258 | 87.5% | 85 | 638 |
| 4 | interfaces/IValidatorShare.sol | 15 | 3 | 20.0% | 13 | 31 |
| 5 | interfaces/IStakeManager.sol | 55 | 2 | 3.6% | 21 | 78 |
| 6 | interfaces/IMasterWhitelist.sol | 16 | 39 | 243.8% | 10 | 65 |
| Total | 1324 | 742 | 56.0% | 428 | 2494 |
| # | Finding | Severity | Update |
| 1 | Changing stakingTokenAddress will affect share pricing and staking calculations | Medium | Fixed |
| 2 | Inflation attack can lead to loss of value for depositors | Medium | Fixed |
| 3 | The setCap(...) function can set a cap lower than the current deposited amount | Low | Fixed |
| 4 | Shadowed variables and functions | Info | Fixed |
| 5 | Boolean comparisons can be avoided | Best Practices | Fixed |
| 6 | Usage of outdated solidity compiler | Best Practices | Fixed |
| 7 | Using enum instead of arbitrary number for userType. | Best Practices | Acknowledged |
| 8 | Incorrect comment in reallocate(...) | Best Practices | Fixed |
| 9 | NatSpec documentation refers to outdated variables | Best Practices | Fixed |
| 10 | Solidity code style | Best Practices | Fixed |
| 11 | Unnecessary storage write in deallocate(...) | Best Practices | Fixed |
No system overview is included in this report.
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.
stakingTokenAddress will affect share pricing and staking calculations| File | Fix commit | Type | Status |
TruStakeMATICv2.sol | — | Medium | Fixed |
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.
| File | Fix commit | Type | Status |
TruStakeMATICv2.sol | — | Medium | Fixed |
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.
setCap(...) function can set a cap lower than the current deposited amount| File | Fix commit | Type | Status |
TruStakeMATICv2.sol | — | Low | Fixed |
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.
| File | Fix commit | Type | Status |
TruStakeMATICv2.sol | — | Info | Fixed |
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.
| File | Fix commit | Type | Status |
TruStakeMATICv2.sol | — | Best Practices | Fixed |
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.
| File | Fix commit | Type | Status |
contracts | — | Best Practices | Fixed |
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.
enum instead of arbitrary number for userType.| File | Fix commit | Type | Status |
MasterWhitelist.sol | — | Best Practices | Acknowledged |
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 respectivelyBut 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.
reallocate(...)| File | Fix commit | Type | Status |
TruStakeMATICv2.sol | — | Best Practices | Fixed |
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.
| File | Fix commit | Type | Status |
TruStakeMATICv2.sol | — | Best Practices | Fixed |
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.
| File | Fix commit | Type | Status |
FileName | — | Best Practices | Fixed |
The following is a collection of Solidity code style inconsistencies that do not align with the current recommended style guide.
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.
deallocate(...)| File | Fix commit | Type | Status |
TruStakeMATICv2.sol | — | Best Practices | Fixed |
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.
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 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:
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.
The relevant output is presented below.
| 263Tests passed | 0Failed |
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