Skip to content

Commit ee79c98

Browse files
james-toussaintclaudeluiz-lvj
authored
PaymasterERC20: pass the selected token to _minTokensPerNative (#6831)
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com> Co-authored-by: Luiz Vasconcelos Júnior <64055364+luiz-lvj@users.noreply.github.com>
1 parent 09cc5cc commit ee79c98

5 files changed

Lines changed: 60 additions & 24 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'openzeppelin-solidity': minor
3+
---
4+
5+
[BREAKING] `PaymasterERC20`: Pass the selected `token` to the `_minTokensPerNative` hook so multi-token paymasters can set a per-token minimum. The hook signature changes from `_minTokensPerNative()` to `_minTokensPerNative(IERC20 token)`; overrides must adopt the new signature.

‎contracts/account/paymaster/extensions/PaymasterERC20.sol‎

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,9 @@ abstract contract PaymasterERC20 is Paymaster {
9999
address userOpSender = userOp.sender;
100100
(validationData, token, tokenPerNative) = _fetchDetails(userOp, userOpHash);
101101

102-
if (uint160(validationData) == ERC4337Utils.SIG_VALIDATION_FAILED || tokenPerNative < _minTokensPerNative())
103-
return (bytes(""), ERC4337Utils.SIG_VALIDATION_FAILED);
102+
if (
103+
uint160(validationData) == ERC4337Utils.SIG_VALIDATION_FAILED || tokenPerNative < _minTokensPerNative(token)
104+
) return (bytes(""), ERC4337Utils.SIG_VALIDATION_FAILED);
104105

105106
// Worst-case unused-gas penalty that the EntryPoint may debit from the paymaster's deposit for the
106107
// user-controlled `paymasterPostOpGasLimit` (see {_postOpGasPenalty}). The EntryPoint computes this penalty
@@ -346,28 +347,34 @@ abstract contract PaymasterERC20 is Paymaster {
346347
* @dev Lower bound on `tokenPerNative` (see {_fetchDetails} for units). Operations whose `tokenPerNative`
347348
* is strictly below this value are rejected with `SIG_VALIDATION_FAILED` before {_prefund} runs.
348349
*
350+
* The `token` selected by {_fetchDetails} is passed in so multi-token paymasters can set the bound per
351+
* token. The default (0) accepts any price, for all tokens.
352+
*
353+
* WARNING: When storing per-token bounds (e.g. in a mapping), make sure every token {_fetchDetails} can return
354+
* has one. An unset entry reads as 0 and disables the check for that token. Consider returning
355+
* `type(uint256).max` for unconfigured tokens so they are rejected.
349356
* To pick a value, decide:
350357
*
351358
* * `minCharge`: smallest token amount you want to bill per op (e.g. `0.01 USDC = 10_000` units).
352359
* * `minGasCost`: smallest `actualGasCost + _postOpCost() * actualUserOpFeePerGas` you expect, in wei
353360
* (= `minGas * minFeePerGas`; `minFeePerGas` can be as low as 1 wei on some L2s).
354361
*
355-
* Then set `_minTokensPerNative() >= minCharge * _tokenPerNativeDenominator() / minGasCost`.
362+
* Then set `_minTokensPerNative(token) >= minCharge * _tokenPerNativeDenominator() / minGasCost`.
356363
*
357364
* Example: a USDC (6 decimals) paymaster on a chain with `minFeePerGas = 1 gwei`, sponsoring
358365
* ops of at least 100_000 gas and charging at least 0.01 USDC per op:
359366
*
360367
* ```solidity
361-
* function _minTokensPerNative() internal view override returns (uint256) {
368+
* function _minTokensPerNative(IERC20) internal view override returns (uint256) {
362369
* return 100e6; // = 1e4 (0.01 USDC) * 1e18 / 1e14 (100_000 gas * 1 gwei) = 100 USDC/ETH
363370
* }
364371
* ```
365372
*
366-
* WARNING: Setting `_minTokensPerNative()` below `minCharge * _tokenPerNativeDenominator() / minGasCost`
373+
* WARNING: Setting `_minTokensPerNative(IERC20)` below `minCharge * _tokenPerNativeDenominator() / minGasCost`
367374
* lets {_erc20Cost} round to zero or to dust for the cheapest ops the paymaster accepts,
368375
* sponsoring them at a low (or zero) price.
369376
*/
370-
function _minTokensPerNative() internal view virtual returns (uint256) {
377+
function _minTokensPerNative(IERC20 /*token*/) internal view virtual returns (uint256) {
371378
return 0;
372379
}
373380

‎contracts/mocks/account/paymaster/PaymasterERC20Mock.sol‎

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ abstract contract PaymasterERC20Mock is EIP712, PaymasterERC20, AccessControl {
2626
bytes32 private constant WITHDRAWER_ROLE = keccak256("WITHDRAWER_ROLE");
2727
bytes32 private constant TOKEN_PRICE_TYPEHASH =
2828
keccak256("TokenPrice(address token,uint48 validAfter,uint48 validUntil,uint256 tokenPerNative)");
29+
mapping(IERC20 token => uint256 min) private _minTokensPerNativeByToken;
2930

3031
function _fetchDetails(
3132
PackedUserOperation calldata userOp,
@@ -77,8 +78,12 @@ abstract contract PaymasterERC20Mock is EIP712, PaymasterERC20, AccessControl {
7778
_withdrawStake(to);
7879
}
7980

80-
function _minTokensPerNative() internal view virtual override returns (uint256) {
81-
return 1;
81+
function setMinTokensPerNative(IERC20 token, uint256 min) public virtual {
82+
_minTokensPerNativeByToken[token] = min;
83+
}
84+
85+
function _minTokensPerNative(IERC20 token) internal view virtual override returns (uint256) {
86+
return _minTokensPerNativeByToken[token]; // unset tokens keep the inherited default (0 = no minimum)
8287
}
8388

8489
function withdrawTokens(IERC20 token, address recipient, uint256 amount) public virtual onlyRole(WITHDRAWER_ROLE) {
@@ -186,14 +191,10 @@ abstract contract PaymasterERC20GuarantorMock is PaymasterERC20Mock, PaymasterER
186191
);
187192
}
188193

189-
function _minTokensPerNative()
190-
internal
191-
view
192-
virtual
193-
override(PaymasterERC20, PaymasterERC20Mock)
194-
returns (uint256)
195-
{
196-
return super._minTokensPerNative();
194+
function _minTokensPerNative(
195+
IERC20 token
196+
) internal view virtual override(PaymasterERC20, PaymasterERC20Mock) returns (uint256) {
197+
return super._minTokensPerNative(token);
197198
}
198199
}
199200

‎docs/modules/ROOT/pages/paymasters.adoc‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ contract PaymasterUSDCChainlink is PaymasterERC20, Ownable {
208208
209209
/// @dev Floor: refuse to sponsor when 1 ETH is worth less than 100 USDC.
210210
/// 1e8 = 100 (USDC per ETH) * 10**6 (USDC decimals); the 1e18 denom cancels 1e18 wei/ETH.
211-
function _minTokensPerNative() internal view virtual override returns (uint256) {
211+
function _minTokensPerNative(IERC20) internal view virtual override returns (uint256) {
212212
return 1e8;
213213
}
214214
@@ -239,7 +239,7 @@ contract PaymasterUSDCChainlink is PaymasterERC20, Ownable {
239239

240240
NOTE: The `PaymasterUSDCChainlink` contract uses specific Chainlink price feeds (ETH/USD and USDC/USD) on Sepolia. For production use or other networks, you'll need to modify the contract to use the appropriate price feed addresses.
241241

242-
NOTE: xref:api:account.adoc#PaymasterERC20-_minTokensPerNative--[`_minTokensPerNative`] defaults to `0` in `PaymasterERC20` and should be overridden. It is a lower bound on `tokenPerNative` (same units: token-units per native coin, scaled by xref:api:account.adoc#PaymasterERC20-_tokenPerNativeDenominator--[`_tokenPerNativeDenominator`]); any operation whose `_fetchDetails` returns a `tokenPerNative` strictly below this floor is rejected with `SIG_VALIDATION_FAILED` before pre-charging the user. The example above returns `1e8`, which refuses to sponsor when 1 ETH is worth less than 100 USDC — a conservative sanity check against misconfigured oracles or extreme market conditions. Returning `0` disables the check and re-opens the "free sponsorship" footgun if `_fetchDetails` ever returns a near-zero price.
242+
NOTE: xref:api:account.adoc#PaymasterERC20-_minTokensPerNative-contract-IERC20-[`_minTokensPerNative`] defaults to `0` in `PaymasterERC20` and should be overridden. It receives the `token` selected by `_fetchDetails`, so a multi-token paymaster can return a different floor per token. It is a lower bound on `tokenPerNative` (same units: token-units per native coin, scaled by xref:api:account.adoc#PaymasterERC20-_tokenPerNativeDenominator--[`_tokenPerNativeDenominator`]); any operation whose `_fetchDetails` returns a `tokenPerNative` strictly below this floor is rejected with `SIG_VALIDATION_FAILED` before pre-charging the user. The example above returns `1e8`, which refuses to sponsor when 1 ETH is worth less than 100 USDC — a conservative sanity check against misconfigured oracles or extreme market conditions. Returning `0` disables the check and re-opens the "free sponsorship" footgun if `_fetchDetails` ever returns a near-zero price.
243243

244244
As you can see, a `_fetchOracleDetails` function is specified to fetch the token price that will be used as a reference for calculating the final ERC-20 payment. One can fetch and process price data from Chainlink oracles to determine the exchange rate between ETH and a concrete ERC-20. An example with USDC would be:
245245

‎test/account/paymaster/PaymasterERC20.test.js‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,7 @@ describe('PaymasterERC20', function () {
124124
await this.paymaster.deposit({ value });
125125
this.userOp ??= {};
126126
this.userOp.paymaster = this.paymaster;
127+
this.userOp.paymasterVerificationGasLimit = 200_000n; // Give headroom for the coverage
127128
});
128129

129130
it('succeeds paying with ERC-20 tokens', async function () {
@@ -329,18 +330,40 @@ describe('PaymasterERC20', function () {
329330
.withArgs(0n, 'AA34 signature error');
330331
});
331332

332-
it('rejects tokenPerNative below _minTokensPerNative', async function () {
333-
await this.token.$_mint(this.account, value);
334-
await this.token.$_approve(this.account, this.paymaster, ethers.MaxUint256);
333+
it('rejects tokenPerNative below _minTokensPerNative for the selected token', async function () {
334+
// A second token with a minimum of 2; the default token keeps the inherited default (0 = no minimum).
335+
const token2 = await ethers.deployContract('$ERC20', ['Name2', 'Symbol2']);
336+
await this.paymaster.setMinTokensPerNative(token2, 2n * ethers.WeiPerEther);
335337

336-
const signedUserOp = await this.account
338+
// Fund both tokens identically so the only difference between the two ops is the minimum,
339+
// not the account's ability to pay (otherwise a failed prefund would also surface as AA34).
340+
for (const erc20 of [this.token, token2]) {
341+
await erc20.$_mint(this.account, value);
342+
await erc20.$_approve(this.account, this.paymaster, ethers.MaxUint256);
343+
}
344+
345+
// Price below token2's minimum (2), but accepted by the default token (which has no minimum).
346+
const tokenPerNative = 1n * ethers.WeiPerEther;
347+
348+
// Same price, token2 selected: rejected because 1 < token2's minimum (2).
349+
const rejected = await this.account
337350
.createUserOp(this.userOp)
338-
.then(op => this.paymasterSignUserOp(op, { tokenPerNative: 0n }))
351+
.then(op => this.paymasterSignUserOp(op, { tokenPerNative, erc20: token2 }))
339352
.then(op => this.signUserOp(op));
340353

341-
await expect(ethers.predeploy.entrypoint.v09.handleOps([signedUserOp.packed], this.receiver))
354+
await expect(ethers.predeploy.entrypoint.v09.handleOps([rejected.packed], this.receiver))
342355
.to.be.revertedWithCustomError(ethers.predeploy.entrypoint.v09, 'FailedOp')
343356
.withArgs(0n, 'AA34 signature error');
357+
358+
// Same op, same price, but the default token: sponsored because it keeps the default minimum of 0.
359+
const accepted = await this.account
360+
.createUserOp(this.userOp)
361+
.then(op => this.paymasterSignUserOp(op, { tokenPerNative }))
362+
.then(op => this.signUserOp(op));
363+
364+
await expect(ethers.predeploy.entrypoint.v09.handleOps([accepted.packed], this.receiver))
365+
.to.emit(this.paymaster, 'UserOperationSponsored')
366+
.withArgs(accepted.hash(), this.token, anyValue, tokenPerNative);
344367
});
345368
});
346369

0 commit comments

Comments
 (0)