draft-AccountERC7579.sol 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. // SPDX-License-Identifier: MIT
  2. // OpenZeppelin Contracts (last updated v5.4.0) (account/extensions/draft-AccountERC7579.sol)
  3. pragma solidity ^0.8.26;
  4. import {PackedUserOperation} from "../../interfaces/draft-IERC4337.sol";
  5. import {IERC1271} from "../../interfaces/IERC1271.sol";
  6. import {
  7. IERC7579Module,
  8. IERC7579Validator,
  9. IERC7579Execution,
  10. IERC7579AccountConfig,
  11. IERC7579ModuleConfig,
  12. MODULE_TYPE_VALIDATOR,
  13. MODULE_TYPE_EXECUTOR,
  14. MODULE_TYPE_FALLBACK
  15. } from "../../interfaces/draft-IERC7579.sol";
  16. import {ERC7579Utils, Mode, CallType, ExecType} from "../../account/utils/draft-ERC7579Utils.sol";
  17. import {EnumerableSet} from "../../utils/structs/EnumerableSet.sol";
  18. import {Bytes} from "../../utils/Bytes.sol";
  19. import {Packing} from "../../utils/Packing.sol";
  20. import {Calldata} from "../../utils/Calldata.sol";
  21. import {Account} from "../Account.sol";
  22. /**
  23. * @dev Extension of {Account} that implements support for ERC-7579 modules.
  24. *
  25. * To comply with the ERC-1271 support requirement, this contract defers signature validation to
  26. * installed validator modules by calling {IERC7579Validator-isValidSignatureWithSender}.
  27. *
  28. * This contract does not implement validation logic for user operations since this functionality
  29. * is often delegated to self-contained validation modules. Developers must install a validator module
  30. * upon initialization (or any other mechanism to enable execution from the account):
  31. *
  32. * ```solidity
  33. * contract MyAccountERC7579 is AccountERC7579, Initializable {
  34. * function initializeAccount(address validator, bytes calldata validatorData) public initializer {
  35. * _installModule(MODULE_TYPE_VALIDATOR, validator, validatorData);
  36. * }
  37. * }
  38. * ```
  39. *
  40. * [NOTE]
  41. * ====
  42. * * Hook support is not included. See {AccountERC7579Hooked} for a version that hooks to execution.
  43. * * Validator selection, when verifying either ERC-1271 signature or ERC-4337 UserOperation is implemented in
  44. * internal virtual functions {_extractUserOpValidator} and {_extractSignatureValidator}. Both are implemented
  45. * following common practices. However, this part is not standardized in ERC-7579 (or in any follow-up ERC). Some
  46. * accounts may want to override these internal functions.
  47. * * When combined with {ERC7739}, resolution ordering of {isValidSignature} may have an impact ({ERC7739} does not
  48. * call super). Manual resolution might be necessary.
  49. * * Static calls (using callType `0xfe`) are currently NOT supported.
  50. * ====
  51. *
  52. * WARNING: Removing all validator modules will render the account inoperable, as no user operations can be validated thereafter.
  53. */
  54. abstract contract AccountERC7579 is Account, IERC1271, IERC7579Execution, IERC7579AccountConfig, IERC7579ModuleConfig {
  55. using Bytes for *;
  56. using ERC7579Utils for *;
  57. using EnumerableSet for *;
  58. using Packing for bytes32;
  59. EnumerableSet.AddressSet private _validators;
  60. EnumerableSet.AddressSet private _executors;
  61. mapping(bytes4 selector => address) private _fallbacks;
  62. /// @dev The account's {fallback} was called with a selector that doesn't have an installed handler.
  63. error ERC7579MissingFallbackHandler(bytes4 selector);
  64. /// @dev Modifier that checks if the caller is an installed module of the given type.
  65. modifier onlyModule(uint256 moduleTypeId, bytes calldata additionalContext) {
  66. _checkModule(moduleTypeId, msg.sender, additionalContext);
  67. _;
  68. }
  69. /// @dev See {_fallback}.
  70. fallback(bytes calldata) external payable virtual returns (bytes memory) {
  71. return _fallback();
  72. }
  73. /// @inheritdoc IERC7579AccountConfig
  74. function accountId() public view virtual returns (string memory) {
  75. // vendorname.accountname.semver
  76. return "@openzeppelin/community-contracts.AccountERC7579.v0.0.0";
  77. }
  78. /**
  79. * @inheritdoc IERC7579AccountConfig
  80. *
  81. * @dev Supported call types:
  82. * * Single (`0x00`): A single transaction execution.
  83. * * Batch (`0x01`): A batch of transactions execution.
  84. * * Delegate (`0xff`): A delegate call execution.
  85. *
  86. * Supported exec types:
  87. * * Default (`0x00`): Default execution type (revert on failure).
  88. * * Try (`0x01`): Try execution type (emits ERC7579TryExecuteFail on failure).
  89. */
  90. function supportsExecutionMode(bytes32 encodedMode) public view virtual returns (bool) {
  91. (CallType callType, ExecType execType, , ) = Mode.wrap(encodedMode).decodeMode();
  92. return
  93. (callType == ERC7579Utils.CALLTYPE_SINGLE ||
  94. callType == ERC7579Utils.CALLTYPE_BATCH ||
  95. callType == ERC7579Utils.CALLTYPE_DELEGATECALL) &&
  96. (execType == ERC7579Utils.EXECTYPE_DEFAULT || execType == ERC7579Utils.EXECTYPE_TRY);
  97. }
  98. /**
  99. * @inheritdoc IERC7579AccountConfig
  100. *
  101. * @dev Supported module types:
  102. *
  103. * * Validator: A module used during the validation phase to determine if a transaction is valid and
  104. * should be executed on the account.
  105. * * Executor: A module that can execute transactions on behalf of the smart account via a callback.
  106. * * Fallback Handler: A module that can extend the fallback functionality of a smart account.
  107. */
  108. function supportsModule(uint256 moduleTypeId) public view virtual returns (bool) {
  109. return
  110. moduleTypeId == MODULE_TYPE_VALIDATOR ||
  111. moduleTypeId == MODULE_TYPE_EXECUTOR ||
  112. moduleTypeId == MODULE_TYPE_FALLBACK;
  113. }
  114. /// @inheritdoc IERC7579ModuleConfig
  115. function installModule(
  116. uint256 moduleTypeId,
  117. address module,
  118. bytes calldata initData
  119. ) public virtual onlyEntryPointOrSelf {
  120. _installModule(moduleTypeId, module, initData);
  121. }
  122. /// @inheritdoc IERC7579ModuleConfig
  123. function uninstallModule(
  124. uint256 moduleTypeId,
  125. address module,
  126. bytes calldata deInitData
  127. ) public virtual onlyEntryPointOrSelf {
  128. _uninstallModule(moduleTypeId, module, deInitData);
  129. }
  130. /// @inheritdoc IERC7579ModuleConfig
  131. function isModuleInstalled(
  132. uint256 moduleTypeId,
  133. address module,
  134. bytes calldata additionalContext
  135. ) public view virtual returns (bool) {
  136. if (moduleTypeId == MODULE_TYPE_VALIDATOR) return _validators.contains(module);
  137. if (moduleTypeId == MODULE_TYPE_EXECUTOR) return _executors.contains(module);
  138. if (moduleTypeId == MODULE_TYPE_FALLBACK) return _fallbacks[bytes4(additionalContext[0:4])] == module;
  139. return false;
  140. }
  141. /// @inheritdoc IERC7579Execution
  142. function execute(bytes32 mode, bytes calldata executionCalldata) public payable virtual onlyEntryPointOrSelf {
  143. _execute(Mode.wrap(mode), executionCalldata);
  144. }
  145. /// @inheritdoc IERC7579Execution
  146. function executeFromExecutor(
  147. bytes32 mode,
  148. bytes calldata executionCalldata
  149. )
  150. public
  151. payable
  152. virtual
  153. onlyModule(MODULE_TYPE_EXECUTOR, Calldata.emptyBytes())
  154. returns (bytes[] memory returnData)
  155. {
  156. return _execute(Mode.wrap(mode), executionCalldata);
  157. }
  158. /**
  159. * @dev Implement ERC-1271 through IERC7579Validator modules. If module based validation fails, fallback to
  160. * "native" validation by the abstract signer.
  161. *
  162. * NOTE: when combined with {ERC7739}, resolution ordering may have an impact ({ERC7739} does not call super).
  163. * Manual resolution might be necessary.
  164. */
  165. function isValidSignature(bytes32 hash, bytes calldata signature) public view virtual returns (bytes4) {
  166. // check signature length is enough for extraction
  167. if (signature.length >= 20) {
  168. (address module, bytes calldata innerSignature) = _extractSignatureValidator(signature);
  169. // if module is not installed, skip
  170. if (isModuleInstalled(MODULE_TYPE_VALIDATOR, module, Calldata.emptyBytes())) {
  171. // try validation, skip any revert
  172. try IERC7579Validator(module).isValidSignatureWithSender(msg.sender, hash, innerSignature) returns (
  173. bytes4 magic
  174. ) {
  175. return magic;
  176. } catch {}
  177. }
  178. }
  179. return bytes4(0xffffffff);
  180. }
  181. /**
  182. * @dev Validates a user operation with {_signableUserOpHash} and returns the validation data
  183. * if the module specified by the first 20 bytes of the nonce key is installed. Falls back to
  184. * {Account-_validateUserOp} otherwise.
  185. *
  186. * See {_extractUserOpValidator} for the module extraction logic.
  187. */
  188. function _validateUserOp(
  189. PackedUserOperation calldata userOp,
  190. bytes32 userOpHash
  191. ) internal virtual override returns (uint256) {
  192. address module = _extractUserOpValidator(userOp);
  193. return
  194. isModuleInstalled(MODULE_TYPE_VALIDATOR, module, Calldata.emptyBytes())
  195. ? IERC7579Validator(module).validateUserOp(userOp, _signableUserOpHash(userOp, userOpHash))
  196. : super._validateUserOp(userOp, userOpHash);
  197. }
  198. /**
  199. * @dev ERC-7579 execution logic. See {supportsExecutionMode} for supported modes.
  200. *
  201. * Reverts if the call type is not supported.
  202. */
  203. function _execute(
  204. Mode mode,
  205. bytes calldata executionCalldata
  206. ) internal virtual returns (bytes[] memory returnData) {
  207. (CallType callType, ExecType execType, , ) = mode.decodeMode();
  208. if (callType == ERC7579Utils.CALLTYPE_SINGLE) return executionCalldata.execSingle(execType);
  209. if (callType == ERC7579Utils.CALLTYPE_BATCH) return executionCalldata.execBatch(execType);
  210. if (callType == ERC7579Utils.CALLTYPE_DELEGATECALL) return executionCalldata.execDelegateCall(execType);
  211. revert ERC7579Utils.ERC7579UnsupportedCallType(callType);
  212. }
  213. /**
  214. * @dev Installs a module of the given type with the given initialization data.
  215. *
  216. * For the fallback module type, the `initData` is expected to be the (packed) concatenation of a 4-byte
  217. * selector and the rest of the data to be sent to the handler when calling {IERC7579Module-onInstall}.
  218. *
  219. * Requirements:
  220. *
  221. * * Module type must be supported. See {supportsModule}. Reverts with {ERC7579Utils-ERC7579UnsupportedModuleType}.
  222. * * Module must be of the given type. Reverts with {ERC7579Utils-ERC7579MismatchedModuleTypeId}.
  223. * * Module must not be already installed. Reverts with {ERC7579Utils-ERC7579AlreadyInstalledModule}.
  224. *
  225. * Emits a {IERC7579ModuleConfig-ModuleInstalled} event.
  226. */
  227. function _installModule(uint256 moduleTypeId, address module, bytes memory initData) internal virtual {
  228. require(supportsModule(moduleTypeId), ERC7579Utils.ERC7579UnsupportedModuleType(moduleTypeId));
  229. require(
  230. IERC7579Module(module).isModuleType(moduleTypeId),
  231. ERC7579Utils.ERC7579MismatchedModuleTypeId(moduleTypeId, module)
  232. );
  233. if (moduleTypeId == MODULE_TYPE_VALIDATOR) {
  234. require(_validators.add(module), ERC7579Utils.ERC7579AlreadyInstalledModule(moduleTypeId, module));
  235. } else if (moduleTypeId == MODULE_TYPE_EXECUTOR) {
  236. require(_executors.add(module), ERC7579Utils.ERC7579AlreadyInstalledModule(moduleTypeId, module));
  237. } else if (moduleTypeId == MODULE_TYPE_FALLBACK) {
  238. bytes4 selector;
  239. (selector, initData) = _decodeFallbackData(initData);
  240. require(
  241. _fallbacks[selector] == address(0),
  242. ERC7579Utils.ERC7579AlreadyInstalledModule(moduleTypeId, module)
  243. );
  244. _fallbacks[selector] = module;
  245. }
  246. IERC7579Module(module).onInstall(initData);
  247. emit ModuleInstalled(moduleTypeId, module);
  248. }
  249. /**
  250. * @dev Uninstalls a module of the given type with the given de-initialization data.
  251. *
  252. * For the fallback module type, the `deInitData` is expected to be the (packed) concatenation of a 4-byte
  253. * selector and the rest of the data to be sent to the handler when calling {IERC7579Module-onUninstall}.
  254. *
  255. * Requirements:
  256. *
  257. * * Module must be already installed. Reverts with {ERC7579Utils-ERC7579UninstalledModule} otherwise.
  258. */
  259. function _uninstallModule(uint256 moduleTypeId, address module, bytes memory deInitData) internal virtual {
  260. require(supportsModule(moduleTypeId), ERC7579Utils.ERC7579UnsupportedModuleType(moduleTypeId));
  261. if (moduleTypeId == MODULE_TYPE_VALIDATOR) {
  262. require(_validators.remove(module), ERC7579Utils.ERC7579UninstalledModule(moduleTypeId, module));
  263. } else if (moduleTypeId == MODULE_TYPE_EXECUTOR) {
  264. require(_executors.remove(module), ERC7579Utils.ERC7579UninstalledModule(moduleTypeId, module));
  265. } else if (moduleTypeId == MODULE_TYPE_FALLBACK) {
  266. bytes4 selector;
  267. (selector, deInitData) = _decodeFallbackData(deInitData);
  268. require(
  269. _fallbackHandler(selector) == module && module != address(0),
  270. ERC7579Utils.ERC7579UninstalledModule(moduleTypeId, module)
  271. );
  272. delete _fallbacks[selector];
  273. }
  274. IERC7579Module(module).onUninstall(deInitData);
  275. emit ModuleUninstalled(moduleTypeId, module);
  276. }
  277. /**
  278. * @dev Fallback function that delegates the call to the installed handler for the given selector.
  279. *
  280. * Reverts with {ERC7579MissingFallbackHandler} if the handler is not installed.
  281. *
  282. * Calls the handler with the original `msg.sender` appended at the end of the calldata following
  283. * the ERC-2771 format.
  284. */
  285. function _fallback() internal virtual returns (bytes memory) {
  286. address handler = _fallbackHandler(msg.sig);
  287. require(handler != address(0), ERC7579MissingFallbackHandler(msg.sig));
  288. // From https://eips.ethereum.org/EIPS/eip-7579#fallback[ERC-7579 specifications]:
  289. // - MUST utilize ERC-2771 to add the original msg.sender to the calldata sent to the fallback handler
  290. // - MUST use call to invoke the fallback handler
  291. (bool success, bytes memory returndata) = handler.call{value: msg.value}(
  292. abi.encodePacked(msg.data, msg.sender)
  293. );
  294. if (success) return returndata;
  295. assembly ("memory-safe") {
  296. revert(add(returndata, 0x20), mload(returndata))
  297. }
  298. }
  299. /// @dev Returns the fallback handler for the given selector. Returns `address(0)` if not installed.
  300. function _fallbackHandler(bytes4 selector) internal view virtual returns (address) {
  301. return _fallbacks[selector];
  302. }
  303. /// @dev Checks if the module is installed. Reverts if the module is not installed.
  304. function _checkModule(
  305. uint256 moduleTypeId,
  306. address module,
  307. bytes calldata additionalContext
  308. ) internal view virtual {
  309. require(
  310. isModuleInstalled(moduleTypeId, module, additionalContext),
  311. ERC7579Utils.ERC7579UninstalledModule(moduleTypeId, module)
  312. );
  313. }
  314. /**
  315. * @dev Extracts the nonce validator from the user operation.
  316. *
  317. * To construct a nonce key, set nonce as follows:
  318. *
  319. * ```
  320. * <module address (20 bytes)> | <key (4 bytes)> | <nonce (8 bytes)>
  321. * ```
  322. * NOTE: The default behavior of this function replicates the behavior of
  323. * https://github.com/rhinestonewtf/safe7579/blob/bb29e8b1a66658790c4169e72608e27d220f79be/src/Safe7579.sol#L266[Safe adapter],
  324. * https://github.com/etherspot/etherspot-prime-contracts/blob/cfcdb48c4172cea0d66038324c0bae3288aa8caa/src/modular-etherspot-wallet/wallet/ModularEtherspotWallet.sol#L227[Etherspot's Prime Account], and
  325. * https://github.com/erc7579/erc7579-implementation/blob/16138d1afd4e9711f6c1425133538837bd7787b5/src/MSAAdvanced.sol#L247[ERC7579 reference implementation].
  326. *
  327. * This is not standardized in ERC-7579 (or in any follow-up ERC). Some accounts may want to override these internal functions.
  328. *
  329. * For example, https://github.com/bcnmy/nexus/blob/54f4e19baaff96081a8843672977caf712ef19f4/contracts/lib/NonceLib.sol#L17[Biconomy's Nexus]
  330. * uses a similar yet incompatible approach (the validator address is also part of the nonce, but not at the same location)
  331. */
  332. function _extractUserOpValidator(PackedUserOperation calldata userOp) internal pure virtual returns (address) {
  333. return address(bytes32(userOp.nonce).extract_32_20(0));
  334. }
  335. /**
  336. * @dev Extracts the signature validator from the signature.
  337. *
  338. * To construct a signature, set the first 20 bytes as the module address and the remaining bytes as the
  339. * signature data:
  340. *
  341. * ```
  342. * <module address (20 bytes)> | <signature data>
  343. * ```
  344. *
  345. * NOTE: The default behavior of this function replicates the behavior of
  346. * https://github.com/rhinestonewtf/safe7579/blob/bb29e8b1a66658790c4169e72608e27d220f79be/src/Safe7579.sol#L350[Safe adapter],
  347. * https://github.com/bcnmy/nexus/blob/54f4e19baaff96081a8843672977caf712ef19f4/contracts/Nexus.sol#L239[Biconomy's Nexus],
  348. * https://github.com/etherspot/etherspot-prime-contracts/blob/cfcdb48c4172cea0d66038324c0bae3288aa8caa/src/modular-etherspot-wallet/wallet/ModularEtherspotWallet.sol#L252[Etherspot's Prime Account], and
  349. * https://github.com/erc7579/erc7579-implementation/blob/16138d1afd4e9711f6c1425133538837bd7787b5/src/MSAAdvanced.sol#L296[ERC7579 reference implementation].
  350. *
  351. * This is not standardized in ERC-7579 (or in any follow-up ERC). Some accounts may want to override these internal functions.
  352. */
  353. function _extractSignatureValidator(
  354. bytes calldata signature
  355. ) internal pure virtual returns (address module, bytes calldata innerSignature) {
  356. return (address(bytes20(signature[0:20])), signature[20:]);
  357. }
  358. /**
  359. * @dev Extract the function selector from initData/deInitData for MODULE_TYPE_FALLBACK
  360. *
  361. * NOTE: If we had calldata here, we could use calldata slice which are cheaper to manipulate and don't require
  362. * actual copy. However, this would require `_installModule` to get a calldata bytes object instead of a memory
  363. * bytes object. This would prevent calling `_installModule` from a contract constructor and would force the use
  364. * of external initializers. That may change in the future, as most accounts will probably be deployed as
  365. * clones/proxy/ERC-7702 delegates and therefore rely on initializers anyway.
  366. */
  367. function _decodeFallbackData(
  368. bytes memory data
  369. ) internal pure virtual returns (bytes4 selector, bytes memory remaining) {
  370. return (bytes4(data), data.slice(4));
  371. }
  372. /// @dev By default, only use the modules for validation of userOp and signature. Disable raw signatures.
  373. function _rawSignatureValidation(
  374. bytes32 /*hash*/,
  375. bytes calldata /*signature*/
  376. ) internal view virtual override returns (bool) {
  377. return false;
  378. }
  379. }