|
| 1 | +// SPDX-License-Identifier: MIT |
| 2 | + |
| 3 | +pragma solidity ^0.8.20; |
| 4 | + |
| 5 | +import {ERC4337Utils, PackedUserOperation} from "@openzeppelin/contracts/account/utils/draft-ERC4337Utils.sol"; |
| 6 | +import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; |
| 7 | +import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol"; |
| 8 | +import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; |
| 9 | +import {PaymasterCore} from "./PaymasterCore.sol"; |
| 10 | + |
| 11 | +/** |
| 12 | + * @dev Extension of {PaymasterCore} that enables users to pay gas with ERC-20 tokens. |
| 13 | + * |
| 14 | + * To enable this feature, developers must implement the {fetchDetails} function: |
| 15 | + * |
| 16 | + * ```solidity |
| 17 | + * function _fetchDetails( |
| 18 | + * PackedUserOperation calldata userOp, |
| 19 | + * bytes32 userOpHash |
| 20 | + * ) internal view override returns (uint256 validationData, IERC20 token, uint256 tokenPrice, address guarantor) { |
| 21 | + * // Implement logic to fetch the token, token price, and guarantor address from the userOp |
| 22 | + * } |
| 23 | + * ``` |
| 24 | + */ |
| 25 | +abstract contract PaymasterERC20 is PaymasterCore { |
| 26 | + using ERC4337Utils for *; |
| 27 | + using Math for *; |
| 28 | + using SafeERC20 for IERC20; |
| 29 | + |
| 30 | + event UserOperationSponsored( |
| 31 | + bytes32 indexed userOpHash, |
| 32 | + address indexed user, |
| 33 | + address indexed guarantor, |
| 34 | + uint256 tokenAmount, |
| 35 | + uint256 tokenPrice, |
| 36 | + bool paidByGuarantor |
| 37 | + ); |
| 38 | + |
| 39 | + // Over-estimations: ERC-20 balances/allowances may be cold and contracts may not be optimized |
| 40 | + uint256 private constant POST_OP_COST = 30_000; |
| 41 | + uint256 private constant POST_OP_COST_WITH_GUARANTOR = 45_000; |
| 42 | + |
| 43 | + /// @inheritdoc PaymasterCore |
| 44 | + function _validatePaymasterUserOp( |
| 45 | + PackedUserOperation calldata userOp, |
| 46 | + bytes32 userOpHash, |
| 47 | + uint256 maxCost |
| 48 | + ) internal virtual override returns (bytes memory context, uint256 validationData) { |
| 49 | + (uint256 validationData_, IERC20 token, uint256 tokenPrice, address guarantor) = _fetchDetails( |
| 50 | + userOp, |
| 51 | + userOpHash |
| 52 | + ); |
| 53 | + |
| 54 | + uint256 prefundAmount = (maxCost + |
| 55 | + (guarantor == address(0)).ternary(POST_OP_COST, POST_OP_COST_WITH_GUARANTOR) * |
| 56 | + userOp.maxFeePerGas()).mulDiv(tokenPrice, _tokenPriceDenominator()); |
| 57 | + |
| 58 | + // if validation is obviously failed, don't even try to do the ERC-20 transfer |
| 59 | + return |
| 60 | + (validationData_ != ERC4337Utils.SIG_VALIDATION_FAILED && |
| 61 | + token.trySafeTransferFrom( |
| 62 | + guarantor == address(0) ? userOp.sender : guarantor, |
| 63 | + address(this), |
| 64 | + prefundAmount |
| 65 | + )) |
| 66 | + ? ( |
| 67 | + abi.encodePacked(userOpHash, token, prefundAmount, tokenPrice, userOp.sender, guarantor), |
| 68 | + validationData_ |
| 69 | + ) |
| 70 | + : (bytes(""), ERC4337Utils.SIG_VALIDATION_FAILED); |
| 71 | + } |
| 72 | + |
| 73 | + /// @inheritdoc PaymasterCore |
| 74 | + function _postOp( |
| 75 | + PostOpMode /* mode */, |
| 76 | + bytes calldata context, |
| 77 | + uint256 actualGasCost, |
| 78 | + uint256 actualUserOpFeePerGas |
| 79 | + ) internal virtual override { |
| 80 | + bytes32 userOpHash = bytes32(context[0x00:0x20]); |
| 81 | + IERC20 token = IERC20(address(bytes20(context[0x20:0x34]))); |
| 82 | + uint256 prefundAmount = uint256(bytes32(context[0x34:0x54])); |
| 83 | + uint256 tokenPrice = uint256(bytes32(context[0x54:0x74])); |
| 84 | + address user = address(bytes20(context[0x74:0x88])); |
| 85 | + address guarantor = address(bytes20(context[0x88:0x9C])); |
| 86 | + |
| 87 | + uint256 actualAmount = (actualGasCost + |
| 88 | + (guarantor == address(0)).ternary(POST_OP_COST, POST_OP_COST_WITH_GUARANTOR) * |
| 89 | + actualUserOpFeePerGas).mulDiv(tokenPrice, _tokenPriceDenominator()); |
| 90 | + |
| 91 | + if (guarantor == address(0)) { |
| 92 | + token.safeTransfer(user, prefundAmount - actualAmount); |
| 93 | + emit UserOperationSponsored(userOpHash, user, address(0), actualAmount, tokenPrice, false); |
| 94 | + } else if (token.trySafeTransferFrom(user, address(this), actualAmount)) { |
| 95 | + token.safeTransfer(guarantor, prefundAmount); |
| 96 | + emit UserOperationSponsored(userOpHash, user, guarantor, actualAmount, tokenPrice, false); |
| 97 | + } else { |
| 98 | + token.safeTransfer(guarantor, prefundAmount - actualAmount); |
| 99 | + emit UserOperationSponsored(userOpHash, user, guarantor, actualAmount, tokenPrice, true); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + /** |
| 104 | + * @dev Retrieves payment details for a user operation |
| 105 | + * |
| 106 | + * The values returned by this internal function are: |
| 107 | + * * `validationData`: ERC-4337 validation data, indicating success/failure and optional time validity (`validAfter`, `validUntil`). |
| 108 | + * * `token`: Address of the ERC-20 token used for payment to the paymaster. |
| 109 | + * * `tokenPrice`: Price of the token in native currency, scaled by `_tokenPriceDenominator()`. |
| 110 | + * * `guarantor`: Address of an entity advancing funds if the user lacks them; receives tokens during execution or pays if the user can't. |
| 111 | + * |
| 112 | + * ==== Calculating the token price |
| 113 | + * |
| 114 | + * Given gas fees are paid in native currency, developers can use the `ERC20 price unit / native price unit` ratio to |
| 115 | + * calculate the price of an ERC20 token price in native currency. However, the token may have a different number of decimals |
| 116 | + * than the native currency. For a a generalized formula considering prices in USD and decimals, consider using: |
| 117 | + * |
| 118 | + * `(<ERC-20 token price in $> / 10**<ERC-20 decimals>) / (<Native token price in $> / 1e18) * _tokenPriceDenominator()` |
| 119 | + * |
| 120 | + * For example, suppose token is USDC ($1 with 6 decimals) and native currency is ETH (assuming $2524.86 with 18 decimals), |
| 121 | + * then each unit (1e-6) of USDC is worth `(1 / 1e6) / ((252486 / 1e2) / 1e18) = 396061563.8094785` wei. The `_tokenPriceDenominator()` |
| 122 | + * ensures precision by avoiding fractional value loss. (i.e. the 0.8094785 part). |
| 123 | + * |
| 124 | + * ==== Guarantor |
| 125 | + * |
| 126 | + * To support a guarantor, developers can use the `paymasterData` field to store the guarantor's address. Developers can disable |
| 127 | + * support for a guarantor by returning `address(0)`. If supported, ensure explicit consent (e.g., signature verification) to prevent |
| 128 | + * unauthorized use. |
| 129 | + */ |
| 130 | + function _fetchDetails( |
| 131 | + PackedUserOperation calldata userOp, |
| 132 | + bytes32 userOpHash |
| 133 | + ) internal view virtual returns (uint256 validationData, IERC20 token, uint256 tokenPrice, address guarantor); |
| 134 | + |
| 135 | + /// @dev Denominator used for interpreting the `tokenPrice` returned by {_fetchDetails} as "fixed point". |
| 136 | + function _tokenPriceDenominator() internal view virtual returns (uint256) { |
| 137 | + return 1e18; |
| 138 | + } |
| 139 | + |
| 140 | + /// @dev Public function that allows the withdrawer to extract ERC-20 tokens resulting from gas payments. |
| 141 | + function withdrawTokens(IERC20 token, address recipient, uint256 amount) public virtual onlyWithdrawer { |
| 142 | + if (amount == type(uint256).max) amount = token.balanceOf(address(this)); |
| 143 | + token.safeTransfer(recipient, amount); |
| 144 | + } |
| 145 | +} |
0 commit comments