draft-AccountERC7579.sol 19 KB

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