Pimlico
ERC20 Paymaster

Pimlico builds account abstraction infrastructure. We reviewed its ERC-20 Paymaster, which lets ERC-4337 users pay gas in tokens instead of ETH.
report id
0083
category
Infra & Wallets
language
Solidity
final report
May 2, 2023
lines of code
86
Content

Download audit report

1

Executive Summary

This document presents the security review performed by Nethermind on the Pimlico ERC20 Paymaster contract. Pimlico is a company that specializes in providing infrastructure for the EIP-4337 account abstraction standard, which aims to improve the efficiency and flexibility of account management on blockchain networks. This standard allows for easier and more secure management of accounts, by implementing account logic into a smart contract rather than relying on an EOA. Pimlico’s focus is on building infrastructure for the EIP-4337 standard, particularly for paymasters and bundlers, while also developing an API that allows developers to easily integrate with account abstraction and sponsored transactions.

The audit was performed using manual analysis of the codebase as well as automated analysis tools.

Audit assessment
Audit TypeSecurity Review
Initial ReportApr. 24, 2023
Response from ClientApr. 30, 2023
Final ReportMay. 2, 2023
MethodsManual Review, Automated Analysis
Repositorypimlicolabs/erc20-paymaster-contracts
Commit Hash (Initial Audit)1d32643ff9
DocumentationREADME.md, Pimlico Documentation Site, EIP-4337
Documentation AssessmentHigh
Test Suite AssessmentMedium
Total findings
4
Fixed
4
Acknowledged
0
Mitigated
0
Unresolved
0

Findings by severity

  • Critical0
  • High1
  • Medium0
  • Low2
  • Informational0
  • Best Practices1

2

Audited Files

#ContractLoCCommentsRatioBlankTotal
1src/PimlicoERC20Paymaster.sol863237.2%13131
Total863237.2%13131

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 tokenAmount calculation can be incorrect depending on token decimals

FileFix commitTypeStatus
PimlicoERC20Paymaster.solPR #4HighFixed

In the function _validatePaymasterUserOp(...) the paymaster contract will transferFrom ERC20 tokens from the user as payment for the transaction execution. The contract employs a Chainlink oracle to determine the price of ETH and calculate the correspending amount of ERC20 tokens required. However, the calculation does not take into account the number of decimals in the token, which can lead to users paying more or less than expected.

/////////////////////////////////////////////////////////
// @audit Wrong formula, not accounted for the decimals
/////////////////////////////////////////////////////////
uint256 tokenAmount = (
requiredPreFund + (REFUND_POSTOP_COST) * userOp.maxFeePerGas
) * priceMarkup / cachedPrice;

Since priceMarkup has 6 decimals, this calculation will only output a correct result when the token is also 6 decimals. If the token decimal has any other value, it will affect the resulting tokenAmount value which can lead to one of the two situations:

  • When token decimals is less than 6 decimals, the user will pay more tokens than expected;
  • When token decimals is more than 6 decimals, the user will pay less tokens than expected;

The following is a demonstration of this behavior using the DAI token, which is 18 decimals:

1. The Chainlink feed DAI/ETH returns latestAnswer = 518927045882705. This means that 1 DAI is equal to 518927045882705 Wei, or 0.0005189 Ether; 2. To make calculations simple, we assume REFUND_POSTOP_COST to be zero, and priceMarkup to be 100%; 3. For a requiredPreFund of 1 Ether, the required amount of ERC20 tokens can be calculated as follows:;

tokenAmount = 1e18 * 1e6 / 518927045882705 = 1927053153;

4. Since DAI has 18 decimal places, the resulting tokenAmount actually represents an extremely small USD value even though the user was expected to pay 1 Ether worth of DAI. In this case, the user only has to pay 0.000000001927053153 DAI for 1 Ether of execution gas cost;

Recommendation

Correct the formula by taking into account the decimals of the token to ensure pricing is correct.

Resolution

Supporting non 6 decimal tokens by calculating the tokenAmount with token’s decimal which is given on constructor. Fixed in PR: https://github.com/pimlicolabs/erc20-paymaster-contracts/pull/4

6.2 Chainlink’s latestRoundData might return stale or incorrect results

FileFix commitTypeStatus
PimlicoERC20Paymaster.solPR #5LowFixed

The functions updatePrice(...) and _postOp(...) both make a call to a Chainlink oracle to receive the latestRoundData. If there are any problems with Chainlink starting a new round and finding consensus on the new price for the oracle (e.g. Chainlink nodes abandon the oracle, chain congestion, vulnerability/attack on the Chainlink system), the PimlicoERC20Paymaster contract may continue using stale or incorrect data. This could lead to users paying more or less ERC20 tokens to cover their gas costs than expected.

Recommendation

The function updatePrice(...) can prevent updates with potentially stale or incorrect data by adding the following checks:

(
uint80 roundId,
int256 answer,
,
uint256 updatedAt,
uint80 answeredInRound
) = oracle.latestRoundData();

require(answer > 0, "Chainlink price <= 0");
require(updatedAt != 0, "Incomplete round");
require(answeredInRound >= roundId, "Stale price");

It should be noted that this recommendation could have some side-effects if applied to _postOp(...), since a reverting post-operation could affect reputation.

One potential solution for _postOp(...) is to accept the potential reputation risk, as the effects of accepting mispriced assets could lead to loss of funds, whereas reputation can be recovered. Alternatively, to avoid reputation loss the function could refer to a backup price via Uniswap if the Chainlink data is stale.

Resolution

Using 2 days as indicator for checking if oracle is not getting maintained. Also we use 2 oracles instead of one. EG. use USDC/USD oracle and ETH/USD oracle to calculate the USD/ETH ratio. Fixed in PR: https://github.com/pimlicolabs/erc20- paymaster-contracts/pull/5

6.3 Missing input validation for priceUpdateThreshold

FileFix commitTypeStatus
PimlicoERC20Paymaster.solPR #3LowFixed

The function updateConfig(...) is missing input validation for the priceUpdateThreshold argument. If this is set to a very high value (e.g. above priceDenominator), it may lead to an overflow in the function _postOp(...) when calculating whether the price should be updated. This overflow would not revert since it is located within an unchecked block. This could cause price updates to behave incorrectly.

function updateConfig(uint32 _priceMarkup, uint32 _updateThreshold) external onlyOwner {
require(_priceMarkup <= 120e4, "price markup too high");
require(_priceMarkup >= 1e6, "price markeup too low");
priceMarkup = _priceMarkup;

///////////////////////////////////////////////////////
// @audit no input validation for priceUpdateThreshold
///////////////////////////////////////////////////////
priceUpdateThreshold = _updateThreshold;
emit ConfigUpdated(_priceMarkup, _updateThreshold);
}

Recommendation

Consider adding input validation for priceUpdateThreshold.

Resolution

Fixed in PR: https://github.com/pimlicolabs/erc20-paymaster-contracts/pull/3

6.4 Missing use of SafeERC20

FileFix commitTypeStatus
PimlicoERC20Paymaster.solPR #2Best PracticesFixed

When transferring ERC20 tokens, the functions transfer(...) and transferFrom(...) may not account for some edge cases in token behavior. An example of such a behavior is ZRX, which does not revert on failure but instead returns false. This could lead to silent transfer failures, where the paymaster contract would continue to execute even though no tokens have been transferred.

Recommendation

Consider using safeTransfer(...) and safeTransferFrom(...) from the OpenZeppelin SafeERC20 library.

Resolution

As addressed in audit report, enabling any token with same code base will be easier for us to maintain the project. Thus using safeTransfer, using modified version of solady’s SafeTransferLib Library has been modified because Entrypoint reverts on short errors. Fixed in PR: https://github.com/pimlicolabs/erc20-paymaster-contracts/pull/2

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

Three sources of documentation were used during the audit, (a) README, (b) EIP-4337 Abstract, (c) NatSpec and inline comments. A summary on each of the sources is presented below:

README: The README is highly detailed, containing a general overview as well as a detailed list of each function and event. A development setup section is also present, explaining how to prepare the environment as well as build and execute tests.

EIP-4337 Abstract: Although this is not official documentation provided by Pimlico, this specification has served to be very useful throughout the audit. It contains the entire EIP-4337 standard in full detail.

NatSpec and inline comments: The in-line documentation is high quality and covers every function. For each function its general purpose, arguments and returns and described. In-line comments are also present for areas in the code that need further explanations.

7.3 Code Coverage

The relevant output is presented below.

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