draft-AccountERC7579.sol 19 KB

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