Skip to content

Commit 7398205

Browse files
committed
PaymasterERC20: price the EntryPoint postOp unused-gas penalty (#6658)
1 parent e327aba commit 7398205

2 files changed

Lines changed: 96 additions & 7 deletions

File tree

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

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,8 @@ abstract contract PaymasterERC20 is Paymaster {
8686
* Attempts to retrieve the `token` and `tokenPerNative` from the user operation (see {_fetchDetails})
8787
* and prefund the user operation using these values and the `maxCost` argument (see {_prefund}).
8888
*
89-
* Returns `abi.encodePacked(userOpHash, token, tokenPerNative, prefundAmount, prefunder, prefundContext)` in
90-
* `context` if the prefund is successful. Otherwise, it returns empty bytes.
89+
* Returns `abi.encodePacked(userOpHash, token, tokenPerNative, prefundAmount, prefunder, penaltyGas, prefundContext)`
90+
* in `context` if the prefund is successful. Otherwise, it returns empty bytes.
9191
*/
9292
function _validatePaymasterUserOp(
9393
PackedUserOperation calldata userOp,
@@ -102,9 +102,23 @@ abstract contract PaymasterERC20 is Paymaster {
102102
if (uint160(validationData) == ERC4337Utils.SIG_VALIDATION_FAILED || tokenPerNative < _minTokensPerNative())
103103
return (bytes(""), ERC4337Utils.SIG_VALIDATION_FAILED);
104104

105+
// Worst-case unused-gas penalty that the EntryPoint may debit from the paymaster's deposit for the
106+
// user-controlled `paymasterPostOpGasLimit` (see {_postOpGasPenalty}). The EntryPoint computes this penalty
107+
// only after `postOp` returns, so it is absent from the `actualGasCost` reported to {_postOp}. We price it
108+
// into the charge here and retain it in {_postOp}, so a user cannot inflate `paymasterPostOpGasLimit` to
109+
// drain the paymaster's deposit.
110+
uint256 penaltyGas = _postOpGasPenalty(userOp.paymasterPostOpGasLimit());
111+
105112
// If the _erc20Cost math fails, the returned value will be type(uint256).max, which we will never be able
106113
// to charge as a prefund. The `trySafeTransferFrom` in the `_prefund` will fail, causing success to be false.
107-
uint256 maxTokenCost = _erc20Cost(maxCost + _postOpCost() * userOp.maxFeePerGas(), tokenPerNative);
114+
// Saturating arithmetic keeps an overflow in the native cost from wrapping: it saturates to
115+
// `type(uint256).max`, which `_erc20Cost` also returns, and fails the prefund instead of undercharging.
116+
//
117+
// native cost is computed as: maxCost + ((_postOpCost() + penaltyGas) * userOp.maxFeePerGas())
118+
uint256 maxTokenCost = _erc20Cost(
119+
_postOpCost().saturatingAdd(penaltyGas).saturatingMul(userOp.maxFeePerGas()).saturatingAdd(maxCost),
120+
tokenPerNative
121+
);
108122
(bool success, address prefunder, uint256 prefundAmount, bytes memory prefundContext) = _prefund(
109123
userOp,
110124
userOpHash,
@@ -117,7 +131,15 @@ abstract contract PaymasterERC20 is Paymaster {
117131
return
118132
success
119133
? (
120-
abi.encodePacked(userOpHash, token, tokenPerNative, prefundAmount, prefunder, prefundContext),
134+
abi.encodePacked(
135+
userOpHash,
136+
token,
137+
tokenPerNative,
138+
prefundAmount,
139+
prefunder,
140+
penaltyGas,
141+
prefundContext
142+
),
121143
validationData
122144
)
123145
: (bytes(""), ERC4337Utils.SIG_VALIDATION_FAILED);
@@ -167,11 +189,19 @@ abstract contract PaymasterERC20 is Paymaster {
167189
uint256 tokenPerNative = uint256(bytes32(context[0x34:0x54]));
168190
uint256 prefundAmount = uint256(bytes32(context[0x54:0x74]));
169191
address prefunder = address(bytes20(context[0x74:0x88]));
170-
bytes calldata prefundContext = context[0x88:];
192+
uint256 penaltyGas = uint256(bytes32(context[0x88:0xA8]));
193+
bytes calldata prefundContext = context[0xA8:];
171194

172195
// If the _erc20Cost math fails, the returned value will be type(uint256).max, which we will never be able
173-
// to charge as a refund. The `trySafeTransferFrom` in the `_refund` will fail, causing success to be false.
174-
uint256 actualTokenCost = _erc20Cost(actualGasCost + _postOpCost() * actualUserOpFeePerGas, tokenPerNative);
196+
// to charge as a refund. The `trySafeTransfer` in the `_refund` will fail, causing success to be false.
197+
// `penaltyGas` covers the EntryPoint's unused-gas penalty on `paymasterPostOpGasLimit`, which is excluded
198+
// from `actualGasCost` (the EntryPoint computes it only after `postOp` returns). See {_postOpGasPenalty}.
199+
//
200+
// native cost is computed as: actualGasCost + ((_postOpCost() + penaltyGas) * actualUserOpFeePerGas)
201+
uint256 actualTokenCost = _erc20Cost(
202+
_postOpCost().saturatingAdd(penaltyGas).saturatingMul(actualUserOpFeePerGas).saturatingAdd(actualGasCost),
203+
tokenPerNative
204+
);
175205
(bool success, uint256 actualAmount) = _refund(
176206
token,
177207
tokenPerNative,
@@ -257,6 +287,23 @@ abstract contract PaymasterERC20 is Paymaster {
257287
return 30_000;
258288
}
259289

290+
/**
291+
* @dev Worst-case unused-gas penalty (in gas units) that the EntryPoint charges the paymaster's deposit for an
292+
* over-provisioned, user-controlled `paymasterPostOpGasLimit`. This penalty is excluded from the `actualGasCost`
293+
* reported to {_postOp} (the EntryPoint computes it only after `postOp` returns), so it is priced into the charge
294+
* during validation and retained in {_postOp}. Without it, a user could inflate `paymasterPostOpGasLimit` and
295+
* have the paymaster absorb the resulting penalty on every operation, draining its deposit.
296+
*
297+
* The default mirrors the EntryPoint (v0.7-v0.9): a 10% penalty on unused postOp gas, applied only once the
298+
* unused amount reaches 40_000 gas. The worst case is a `postOp` that consumes ~0 gas (e.g. it reverts and the
299+
* maximum penalty is charged), leaving the whole limit unused.
300+
*
301+
* NOTE: Override to return 0 when targeting an EntryPoint that has no unused-gas penalty.
302+
*/
303+
function _postOpGasPenalty(uint256 postOpGasLimit) internal view virtual returns (uint256) {
304+
return Math.ternary(postOpGasLimit > 40_000, postOpGasLimit / 10, 0);
305+
}
306+
260307
/// @dev Denominator used for interpreting the `tokenPerNative` returned by {_fetchDetails} as "fixed point" in {_erc20Cost}.
261308
function _tokenPerNativeDenominator() internal view virtual returns (uint256) {
262309
return 1e18;

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

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,41 @@ describe('PaymasterERC20', function () {
189189
}
190190
});
191191

192+
it('prices the postOp unused-gas penalty so an inflated paymasterPostOpGasLimit cannot drain the paymaster', async function () {
193+
// fund account
194+
await this.token.$_mint(this.account, value);
195+
await this.token.$_approve(this.account, this.paymaster, ethers.MaxUint256);
196+
197+
const signedUserOp = await this.account
198+
.createUserOp({
199+
...this.userOp,
200+
// user inflates the postOp gas limit far beyond what postOp actually consumes
201+
paymasterPostOpGasLimit: 500_000n,
202+
callData: this.account.interface.encodeFunctionData('execute', [
203+
encodeMode({ callType: CALL_TYPE_BATCH }),
204+
encodeBatch({
205+
target: this.target,
206+
data: this.target.interface.encodeFunctionData('mockFunctionExtra'),
207+
}),
208+
]),
209+
})
210+
.then(op => this.paymasterSignUserOp(op, { tokenPrice: 2n * ethers.WeiPerEther }))
211+
.then(op => this.signUserOp(op));
212+
213+
const logs = await predeploy.entrypoint.v09
214+
.handleOps([signedUserOp.packed], this.receiver)
215+
.then(tx => tx.wait())
216+
.then(({ logs }) => logs.map(ev => this.paymaster.interface.parseLog(ev) ?? ev));
217+
218+
const { tokenAmount } = logs.find(ev => ev.fragment?.name == 'UserOperationSponsored').args;
219+
const { actualGasCost } = logs.find(ev => ev.fragment?.name == 'UserOperationEvent').args;
220+
221+
// The EntryPoint debits the paymaster's deposit `actualGasCost`, which *includes* the unused-gas penalty on
222+
// the inflated postOp limit. The token charge (tokenPrice = 2) must cover it, i.e. the user pays for the
223+
// penalty they induced rather than the paymaster subsidizing it out of its deposit.
224+
expect(tokenAmount).to.be.greaterThanOrEqual(2n * actualGasCost);
225+
});
226+
192227
it('reverts with PaymasterERC20FailedRefund when token refund fails', async function () {
193228
const erc20Blocklist = await ethers.deployContract('$ERC20BlocklistMock', ['Token', 'TKN']);
194229

@@ -325,6 +360,13 @@ describe('PaymasterERC20', function () {
325360
});
326361

327362
describe('edge cases', function () {
363+
it('_postOpGasPenalty prices the worst-case unused-gas penalty only above the threshold', async function () {
364+
await expect(this.paymaster.$_postOpGasPenalty(0n)).to.eventually.equal(0n);
365+
await expect(this.paymaster.$_postOpGasPenalty(40_000n)).to.eventually.equal(0n); // threshold is exclusive
366+
await expect(this.paymaster.$_postOpGasPenalty(40_001n)).to.eventually.equal(4_000n); // 10% of the limit
367+
await expect(this.paymaster.$_postOpGasPenalty(1_000_000n)).to.eventually.equal(100_000n);
368+
});
369+
328370
it('_erc20Cost returns max uint256 without reverting when muldiv overflows', async function () {
329371
const tokenPerNative = ethers.MaxUint256;
330372
const nativeCost = ethers.MaxUint256;

0 commit comments

Comments
 (0)