-
Notifications
You must be signed in to change notification settings - Fork 17
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
chore: Add contracts deployment logs for EPv6 for SingleOwnerMSCAFactory #65
chore: Add contracts deployment logs for EPv6 for SingleOwnerMSCAFactory #65
Conversation
Signed-off-by: Daniel Lim <[email protected]>
@@ -0,0 +1 @@ | |||
{"language":"Solidity","sources":{"src/msca/6900/v0.7/factories/semi/SingleOwnerMSCAFactory.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {Create2FailedDeployment, InvalidInitializationInput} from \"../../../shared/common/Errors.sol\";\nimport {SingleOwnerMSCA} from \"../../account/semi/SingleOwnerMSCA.sol\";\nimport {PluginManager} from \"../../managers/PluginManager.sol\";\nimport {IEntryPoint} from \"@account-abstraction/contracts/interfaces/IEntryPoint.sol\";\nimport {ERC1967Proxy} from \"@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol\";\nimport {Create2} from \"@openzeppelin/contracts/utils/Create2.sol\";\n\n/**\n * @dev Account factory that creates the semi-MSCA that enshrines single owner into the account storage.\n * No plugin installation is required during account creation.\n */\ncontract SingleOwnerMSCAFactory {\n // logic implementation\n SingleOwnerMSCA public immutable ACCOUNT_IMPLEMENTATION;\n IEntryPoint public immutable ENTRY_POINT;\n\n event FactoryDeployed(address indexed factory, address accountImplementation, address entryPoint);\n event AccountCreated(address indexed proxy, address sender, bytes32 salt);\n\n /**\n * @dev Salted deterministic deployment using create2 and a specific logic SingleOwnerMSCA implementation.\n * Tx/userOp is either gated by userOpValidationFunction or runtimeValidationFunction, and SingleOwnerMSCA\n * is a minimum account with a pre built-in owner validation, so we do not require the user to install any\n * plugins\n * during the deployment. No hooks can be injected during the account deployment, so for a future installation\n * of more complicated plugins, please call installPlugin via a separate tx/userOp after account deployment.\n */\n constructor(address _entryPointAddr, address _pluginManagerAddr) {\n ENTRY_POINT = IEntryPoint(_entryPointAddr);\n PluginManager _pluginManager = PluginManager(_pluginManagerAddr);\n ACCOUNT_IMPLEMENTATION = new SingleOwnerMSCA(ENTRY_POINT, _pluginManager);\n emit FactoryDeployed(address(this), address(ACCOUNT_IMPLEMENTATION), _entryPointAddr);\n }\n\n /**\n * @dev Salted deterministic deployment using create2 and a specific logic SingleOwnerMSCA implementation.\n * Tx/userOp is either gated by userOpValidationFunction or runtimeValidationFunction, and SingleOwnerMSCA\n * is a minimum account with a pre built-in owner validation, so we do not require the user to install any\n * plugins\n * during the deployment. No hooks can be injected during the account deployment, so for a future installation\n * of more complicated plugins, please call installPlugin via a separate tx/userOp after account deployment.\n * @param _sender sender of the account deployment tx, it could be set to owner. If you don't have the owner\n * information during account creation,\n * please use something unique, consistent and private to yourself. In the context of single owner\n * semi-MSCA, this field is mostly\n * for consistency because we also use owner to mix the salt.\n * @param _salt salt that allows for deterministic deployment\n * @param _initializingData abi.encode(address), address should not be zero\n */\n function createAccount(address _sender, bytes32 _salt, bytes memory _initializingData)\n public\n returns (SingleOwnerMSCA account)\n {\n address owner = abi.decode(_initializingData, (address));\n (address counterfactualAddr, bytes32 mixedSalt) = _getAddress(_sender, _salt, owner);\n if (counterfactualAddr.code.length > 0) {\n return SingleOwnerMSCA(payable(counterfactualAddr));\n }\n // only perform implementation upgrade by setting empty _data in ERC1967Proxy\n // meanwhile we also initialize proxy storage, which calls PluginManager._installPlugin directly to bypass\n // validateNativeFunction checks\n account = SingleOwnerMSCA(\n payable(\n new ERC1967Proxy{salt: mixedSalt}(\n address(ACCOUNT_IMPLEMENTATION), abi.encodeCall(SingleOwnerMSCA.initializeSingleOwnerMSCA, (owner))\n )\n )\n );\n if (address(account) != counterfactualAddr) {\n revert Create2FailedDeployment();\n }\n emit AccountCreated(counterfactualAddr, _sender, _salt);\n }\n\n /**\n * @dev Pre-compute the counterfactual address prior to calling createAccount.\n * After decoding, owner is used in salt, byteCodeHash and func init call to minimize the front-running risk.\n * @param _sender sender of the account deployment tx, it could be set to owner. If you don't have the owner\n * information during account creation,\n * please use something unique, consistent and private to yourself. In the context of single owner\n * semi-MSCA, this field is mostly\n * for consistency because we also use owner to mix the salt.\n * @param _salt salt that allows for deterministic deployment\n * @param _initializingData abi.encode(address), address should not be zero\n */\n function getAddress(address _sender, bytes32 _salt, bytes memory _initializingData)\n public\n view\n returns (address addr, bytes32 mixedSalt)\n {\n address owner = abi.decode(_initializingData, (address));\n return _getAddress(_sender, _salt, owner);\n }\n\n /**\n * @dev Pre-compute the counterfactual address prior to calling createAccount.\n * After decoding, owner is used in salt, byteCodeHash and func init call to minimize the front-running risk.\n * @param _sender sender of the account deployment tx, it could be set to owner. If you don't have the owner\n * information during account creation,\n * please use something unique, consistent and private to yourself. In the context of single owner\n * semi-MSCA, this field is mostly\n * for consistency because we also use owner to mix the salt.\n * @param _salt salt that allows for deterministic deployment\n * @param _owner owner of the semi MSCA\n */\n function _getAddress(address _sender, bytes32 _salt, address _owner)\n internal\n view\n returns (address addr, bytes32 mixedSalt)\n {\n if (_owner == address(0)) {\n revert InvalidInitializationInput();\n }\n mixedSalt = keccak256(abi.encodePacked(_sender, _owner, _salt));\n bytes32 code = keccak256(\n abi.encodePacked(\n type(ERC1967Proxy).creationCode,\n abi.encode(\n address(ACCOUNT_IMPLEMENTATION), abi.encodeCall(SingleOwnerMSCA.initializeSingleOwnerMSCA, (_owner))\n )\n )\n );\n addr = Create2.computeAddress(mixedSalt, code, address(this));\n return (addr, mixedSalt);\n }\n}\n"},"src/msca/6900/shared/common/Errors.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\n/**\n * @notice Throws when the selector is not found.\n */\nerror NotFoundSelector();\n\n/**\n * @notice Throws when authorizer is invalid.\n */\nerror InvalidAuthorizer();\n\nerror InvalidValidationFunctionId(uint8 functionId);\n\nerror InvalidFunctionReference();\n\nerror ItemAlreadyExists();\n\nerror ItemDoesNotExist();\n\nerror InvalidLimit();\n\nerror InvalidExecutionFunction(bytes4 selector);\n\nerror InvalidInitializationInput();\n\nerror Create2FailedDeployment();\n\nerror NotImplemented(bytes4 selector, uint8 functionId);\n\nerror InvalidItem();\n\n// v2 NotImplemented\nerror NotImplementedFunction(bytes4 selector, uint32 entityId);\n"},"src/msca/6900/v0.7/account/semi/SingleOwnerMSCA.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {DefaultCallbackHandler} from \"../../../../../callback/DefaultCallbackHandler.sol\";\n\nimport {\n EIP1271_INVALID_SIGNATURE,\n EIP1271_VALID_SIGNATURE,\n EMPTY_FUNCTION_REFERENCE,\n EMPTY_FUNCTION_REFERENCE,\n SENTINEL_BYTES21,\n SIG_VALIDATION_FAILED,\n SIG_VALIDATION_SUCCEEDED,\n WALLET_VERSION_1\n} from \"../../../../../common/Constants.sol\";\n\nimport {UnauthorizedCaller} from \"../../../../../common/Errors.sol\";\nimport {ExecutionUtils} from \"../../../../../utils/ExecutionUtils.sol\";\nimport {InvalidAuthorizer, InvalidValidationFunctionId, NotFoundSelector} from \"../../../shared/common/Errors.sol\";\nimport {ValidationData} from \"../../../shared/common/Structs.sol\";\nimport {ValidationDataLib} from \"../../../shared/libs/ValidationDataLib.sol\";\nimport {\n PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE,\n RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n} from \"../../common/Constants.sol\";\nimport {ExecutionDetail, FunctionReference, RepeatableBytes21DLL} from \"../../common/Structs.sol\";\nimport {IPlugin} from \"../../interfaces/IPlugin.sol\";\nimport {FunctionReferenceLib} from \"../../libs/FunctionReferenceLib.sol\";\nimport {RepeatableFunctionReferenceDLLLib} from \"../../libs/RepeatableFunctionReferenceDLLLib.sol\";\nimport {WalletStorageV1Lib} from \"../../libs/WalletStorageV1Lib.sol\";\nimport {PluginManager} from \"../../managers/PluginManager.sol\";\nimport {BaseMSCA} from \"../BaseMSCA.sol\";\nimport {IEntryPoint} from \"@account-abstraction/contracts/interfaces/IEntryPoint.sol\";\nimport {UserOperation} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\nimport {UUPSUpgradeable} from \"@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol\";\nimport {IERC1271} from \"@openzeppelin/contracts/interfaces/IERC1271.sol\";\n\nimport {IERC1155Receiver} from \"@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol\";\nimport {IERC721Receiver} from \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\";\n\nimport {BaseERC712CompliantAccount} from \"../../../../../erc712/BaseERC712CompliantAccount.sol\";\nimport {SignatureChecker} from \"@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol\";\n\n/**\n * @dev Semi-MSCA that enshrines single owner into the account storage.\n */\ncontract SingleOwnerMSCA is BaseMSCA, DefaultCallbackHandler, UUPSUpgradeable, IERC1271, BaseERC712CompliantAccount {\n using ExecutionUtils for address;\n using ECDSA for bytes32;\n using RepeatableFunctionReferenceDLLLib for RepeatableBytes21DLL;\n using FunctionReferenceLib for bytes21;\n using FunctionReferenceLib for FunctionReference;\n using ValidationDataLib for ValidationData;\n\n enum FunctionId {\n NATIVE_RUNTIME_VALIDATION_OWNER_OR_SELF,\n NATIVE_USER_OP_VALIDATION_OWNER\n }\n\n string public constant NAME = \"Circle_SingleOwnerMSCA\";\n bytes32 private constant _HASHED_NAME = keccak256(bytes(NAME));\n bytes32 private constant _HASHED_VERSION = keccak256(bytes(WALLET_VERSION_1));\n bytes32 private constant _MESSAGE_TYPEHASH = keccak256(\"CircleSingleOwnerMSCAMessage(bytes32 hash)\");\n\n event SingleOwnerMSCAInitialized(address indexed account, address indexed entryPointAddress, address owner);\n event OwnershipTransferred(address indexed account, address indexed previousOwner, address indexed newOwner);\n\n error InvalidOwnerForMSCA(address account, address owner);\n error NoOwnershipPluginDefined();\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyFromEntryPointOrOwnerOrSelf() {\n _checkFromEPOrOwnerOrSelf();\n _;\n }\n\n constructor(IEntryPoint _newEntryPoint, PluginManager _newPluginManager)\n BaseMSCA(_newEntryPoint, _newPluginManager)\n {}\n\n /// @notice Initializes the account with a set of plugins\n /// @dev No dependencies or hooks can be injected with this installation. For a full installation, please use\n /// installPlugin.\n /// @param owner The initial owner\n function initializeSingleOwnerMSCA(address owner) external walletStorageInitializer {\n if (owner == address(0)) {\n revert InvalidOwnerForMSCA(address(this), owner);\n }\n _transferNativeOwnership(owner);\n emit SingleOwnerMSCAInitialized(address(this), address(ENTRY_POINT), owner);\n }\n\n /// @inheritdoc IERC1271\n function isValidSignature(bytes32 hash, bytes memory signature) external view override returns (bytes4) {\n address owner = WalletStorageV1Lib.getLayout().owner;\n if (owner == address(0)) {\n ExecutionDetail storage executionDetail =\n WalletStorageV1Lib.getLayout().executionDetails[IERC1271.isValidSignature.selector];\n // this is a sanity check only, as using address(0) as a plugin is not permitted during installation\n if (executionDetail.plugin == address(0)) {\n return EIP1271_INVALID_SIGNATURE;\n }\n // isValidSignature is installed via plugin, so it should fallback to the plugin\n (bool success, bytes memory returnData) =\n executionDetail.plugin.staticcall(abi.encodeCall(IERC1271.isValidSignature, (hash, signature)));\n if (!success) {\n return EIP1271_INVALID_SIGNATURE;\n }\n return abi.decode(returnData, (bytes4));\n } else {\n // use address(this) to prevent replay attacks\n bytes32 replaySafeHash = getReplaySafeMessageHash(hash);\n if (SignatureChecker.isValidSignatureNow(owner, replaySafeHash, signature)) {\n return EIP1271_VALID_SIGNATURE;\n }\n return EIP1271_INVALID_SIGNATURE;\n }\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current msg.sender.\n */\n function transferNativeOwnership(address newOwner) public onlyFromEntryPointOrOwnerOrSelf validateNativeFunction {\n if (newOwner == address(0)) {\n revert InvalidOwnerForMSCA(address(this), newOwner);\n }\n _transferNativeOwnership(newOwner);\n }\n\n /**\n * @dev Leaves the contract without owner. Can only be initiated by the current owner.\n *\n * NOTE: Irreversible. Renouncing ownership will leave the contract without an owner,\n * thereby disabling any functionality that is only available to the owner. Please\n * make sure you've already have other backup validations before calling this method.\n * If the user wants to switch to the validations provided by plugins, please call this\n * function after you install the plugin, so owner will be disabled.\n */\n function renounceNativeOwnership() public onlyFromEntryPointOrOwnerOrSelf validateNativeFunction {\n // we need a ownership plugin in place before renouncing native ownership\n if (WalletStorageV1Lib.getLayout().executionDetails[IERC1271.isValidSignature.selector].plugin == address(0)) {\n revert NoOwnershipPluginDefined();\n }\n _transferNativeOwnership(address(0));\n }\n\n /**\n * @dev Returns the current owner.\n */\n function getNativeOwner() public view returns (address) {\n return WalletStorageV1Lib.getLayout().owner;\n }\n\n function supportsInterface(bytes4 interfaceId)\n public\n view\n override(BaseMSCA, DefaultCallbackHandler)\n returns (bool)\n {\n // BaseMSCA has already implemented ERC165\n return BaseMSCA.supportsInterface(interfaceId) || interfaceId == type(IERC721Receiver).interfaceId\n || interfaceId == type(IERC1155Receiver).interfaceId || interfaceId == type(IERC1271).interfaceId;\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferNativeOwnership(address newOwner) internal {\n address oldOwner = WalletStorageV1Lib.getLayout().owner;\n WalletStorageV1Lib.getLayout().owner = newOwner;\n emit OwnershipTransferred(address(this), oldOwner, newOwner);\n }\n\n /**\n * @dev We run the native validation function if it's enabled, otherwise we fallback to the plugin validation\n * functions.\n * In either case, we run the hooks from plugins if there's any.\n */\n function _authenticateAndAuthorizeUserOp(UserOperation calldata userOp, bytes32 userOpHash)\n internal\n override\n returns (uint256 validationData)\n {\n // onlyFromEntryPoint is applied in the caller\n // if there is no function defined for the selector, or if userOp.callData.length < 4, then execution MUST\n // revert\n if (userOp.callData.length < 4) {\n revert NotFoundSelector();\n }\n bytes4 selector = bytes4(userOp.callData[0:4]);\n if (selector == bytes4(0)) {\n revert NotFoundSelector();\n }\n ExecutionDetail storage executionDetail = WalletStorageV1Lib.getLayout().executionDetails[selector];\n // check validation function for non native case first\n FunctionReference memory validationFunction = executionDetail.userOpValidationFunction;\n address owner = WalletStorageV1Lib.getLayout().owner;\n if (owner == address(0)) {\n bytes21 packedValidationFunction = validationFunction.pack();\n if (\n packedValidationFunction == EMPTY_FUNCTION_REFERENCE\n || packedValidationFunction == RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n || packedValidationFunction == PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n ) {\n revert InvalidValidationFunctionId(validationFunction.functionId);\n }\n }\n // pre hook\n ValidationData memory unpackedValidationData =\n _processPreUserOpValidationHooks(executionDetail, userOp, userOpHash);\n uint256 currentValidationData;\n // userOp validation\n // no native validation function\n if (owner == address(0)) {\n IPlugin userOpValidatorPlugin = IPlugin(validationFunction.plugin);\n // execute the validation function with the user operation and its hash as parameters using the call opcode\n currentValidationData = userOpValidatorPlugin.userOpValidationFunction(\n executionDetail.userOpValidationFunction.functionId, userOp, userOpHash\n );\n } else {\n if (SignatureChecker.isValidSignatureNow(owner, userOpHash.toEthSignedMessageHash(), userOp.signature)) {\n currentValidationData = SIG_VALIDATION_SUCCEEDED;\n } else {\n currentValidationData = SIG_VALIDATION_FAILED;\n }\n }\n\n // intercept with last result\n unpackedValidationData = unpackedValidationData._intersectValidationData(currentValidationData);\n if (unpackedValidationData.authorizer != address(0) && unpackedValidationData.authorizer != address(1)) {\n // only revert on unexpected values\n revert InvalidAuthorizer();\n }\n validationData = unpackedValidationData._packValidationData();\n }\n\n function _processPreRuntimeHooksAndValidation(bytes4 selector) internal override {\n if (msg.sender == address(ENTRY_POINT)) {\n // ENTRY_POINT should go through validateUserOp flow which calls userOpValidationFunction\n return;\n }\n ExecutionDetail storage executionDetail = WalletStorageV1Lib.getLayout().executionDetails[selector];\n FunctionReference memory validationFunction = executionDetail.runtimeValidationFunction;\n RepeatableBytes21DLL storage preRuntimeValidationHooksDLL = executionDetail.preRuntimeValidationHooks;\n uint256 totalUniqueHookCount = preRuntimeValidationHooksDLL.getUniqueItems();\n FunctionReference memory startHook = EMPTY_FUNCTION_REFERENCE.unpack();\n FunctionReference[] memory preRuntimeValidationHooks;\n FunctionReference memory nextHook;\n for (uint256 i = 0; i < totalUniqueHookCount; ++i) {\n (preRuntimeValidationHooks, nextHook) = preRuntimeValidationHooksDLL.getPaginated(startHook, 10);\n for (uint256 j = 0; j < preRuntimeValidationHooks.length; ++j) {\n // revert on EMPTY_FUNCTION_REFERENCE, RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE,\n // PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n // if any revert, the outer call MUST revert\n bytes21 packedPreRuntimeValidationHook = preRuntimeValidationHooks[j].pack();\n if (\n packedPreRuntimeValidationHook == EMPTY_FUNCTION_REFERENCE\n || packedPreRuntimeValidationHook == RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n || packedPreRuntimeValidationHook == PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n ) {\n revert InvalidValidationFunctionId(preRuntimeValidationHooks[j].functionId);\n }\n IPlugin preRuntimeValidationHookPlugin = IPlugin(preRuntimeValidationHooks[j].plugin);\n // solhint-disable no-empty-blocks\n try preRuntimeValidationHookPlugin.preRuntimeValidationHook(\n preRuntimeValidationHooks[j].functionId, msg.sender, msg.value, msg.data\n ) {} catch (bytes memory revertReason) {\n revert PreRuntimeValidationHookFailed(\n preRuntimeValidationHooks[j].plugin, preRuntimeValidationHooks[j].functionId, revertReason\n );\n }\n // solhint-enable no-empty-blocks\n }\n if (nextHook.pack() == SENTINEL_BYTES21) {\n break;\n }\n startHook = nextHook;\n }\n address owner = WalletStorageV1Lib.getLayout().owner;\n // no native validation function\n if (owner == address(0)) {\n bytes21 packedValidationFunction = validationFunction.pack();\n if (\n packedValidationFunction == EMPTY_FUNCTION_REFERENCE\n || packedValidationFunction == PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n ) {\n revert InvalidValidationFunctionId(validationFunction.functionId);\n }\n // call runtimeValidationFunction if it's not always allowed\n if (packedValidationFunction != RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE) {\n // solhint-disable no-empty-blocks\n try IPlugin(validationFunction.plugin).runtimeValidationFunction(\n validationFunction.functionId, msg.sender, msg.value, msg.data\n ) {} catch (bytes memory revertReason) {\n revert RuntimeValidationFailed(\n validationFunction.plugin, validationFunction.functionId, revertReason\n );\n }\n // solhint-enable no-empty-blocks\n }\n return;\n } else {\n // the msg.sender should be the owner of the account or itself\n if (msg.sender == owner || msg.sender == address(this)) {\n return;\n } else {\n revert UnauthorizedCaller();\n }\n }\n }\n\n /// @inheritdoc UUPSUpgradeable\n function upgradeTo(address newImplementation) public override onlyProxy validateNativeFunction {\n _authorizeUpgrade(newImplementation);\n _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);\n }\n\n /// @inheritdoc UUPSUpgradeable\n function upgradeToAndCall(address newImplementation, bytes memory data)\n public\n payable\n override\n onlyProxy\n validateNativeFunction\n {\n _authorizeUpgrade(newImplementation);\n _upgradeToAndCallUUPS(newImplementation, data, true);\n }\n\n /**\n * @dev The function is overridden here so more granular ACLs to the upgrade mechanism should be enforced by\n * plugins.\n */\n // solhint-disable-next-line no-empty-blocks\n function _authorizeUpgrade(address newImplementation) internal override {}\n\n function _processPreUserOpValidationHooks(\n ExecutionDetail storage executionDetail,\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) internal override returns (ValidationData memory unpackedValidationData) {\n unpackedValidationData = ValidationData(0, 0xFFFFFFFFFFFF, address(0));\n // if the function selector has associated pre user operation validation hooks, then those hooks MUST be run\n // sequentially\n uint256 totalUniqueHookCount = executionDetail.preUserOpValidationHooks.getUniqueItems();\n FunctionReference memory startHook = EMPTY_FUNCTION_REFERENCE.unpack();\n FunctionReference[] memory preUserOpValidatorHooks;\n FunctionReference memory nextHook;\n uint256 currentValidationData;\n for (uint256 i = 0; i < totalUniqueHookCount; ++i) {\n (preUserOpValidatorHooks, nextHook) = executionDetail.preUserOpValidationHooks.getPaginated(startHook, 10);\n for (uint256 j = 0; j < preUserOpValidatorHooks.length; ++j) {\n bytes21 packedUserOpValidatorHook = preUserOpValidatorHooks[j].pack();\n // if any revert, the outer call MUST revert\n if (\n packedUserOpValidatorHook == EMPTY_FUNCTION_REFERENCE\n || packedUserOpValidatorHook == RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n || packedUserOpValidatorHook == PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n ) {\n revert InvalidHookFunctionId(preUserOpValidatorHooks[j].functionId);\n }\n IPlugin preUserOpValidationHookPlugin = IPlugin(preUserOpValidatorHooks[j].plugin);\n currentValidationData = preUserOpValidationHookPlugin.preUserOpValidationHook(\n preUserOpValidatorHooks[j].functionId, userOp, userOpHash\n );\n unpackedValidationData = unpackedValidationData._intersectValidationData(currentValidationData);\n // if any return an authorizer value other than 0 or 1, execution MUST revert\n if (unpackedValidationData.authorizer != address(0) && unpackedValidationData.authorizer != address(1))\n {\n revert InvalidAuthorizer();\n }\n }\n if (nextHook.pack() == SENTINEL_BYTES21) {\n break;\n }\n startHook = nextHook;\n }\n return unpackedValidationData;\n }\n\n function _checkFromEPOrOwnerOrSelf() internal view {\n // all need to go through validation first, which means being initiated by the owner or account\n if (\n msg.sender != address(ENTRY_POINT) && msg.sender != WalletStorageV1Lib.getLayout().owner\n && msg.sender != address(this)\n ) {\n revert UnauthorizedCaller();\n }\n }\n\n /// @inheritdoc BaseERC712CompliantAccount\n function _getAccountTypeHash() internal pure override returns (bytes32) {\n return _MESSAGE_TYPEHASH;\n }\n\n /// @inheritdoc BaseERC712CompliantAccount\n function _getAccountName() internal pure override returns (bytes32) {\n return _HASHED_NAME;\n }\n\n /// @inheritdoc BaseERC712CompliantAccount\n function _getAccountVersion() internal pure override returns (bytes32) {\n return _HASHED_VERSION;\n }\n}\n"},"src/msca/6900/v0.7/managers/PluginManager.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {EMPTY_FUNCTION_REFERENCE} from \"../../../../common/Constants.sol\";\nimport {InvalidFunctionReference} from \"../../shared/common/Errors.sol\";\nimport {AddressDLL} from \"../../shared/common/Structs.sol\";\nimport {AddressDLLLib} from \"../../shared/libs/AddressDLLLib.sol\";\nimport {\n PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE,\n RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n} from \"../common/Constants.sol\";\nimport {\n ManifestAssociatedFunctionType,\n ManifestExecutionHook,\n ManifestExternalCallPermission,\n ManifestFunction,\n PluginManifest\n} from \"../common/PluginManifest.sol\";\nimport {\n Bytes21DLL,\n FunctionReference,\n HookGroup,\n PermittedExternalCall,\n RepeatableBytes21DLL\n} from \"../common/Structs.sol\";\nimport {IPlugin} from \"../interfaces/IPlugin.sol\";\nimport {FunctionReferenceDLLLib} from \"../libs/FunctionReferenceDLLLib.sol\";\nimport {FunctionReferenceLib} from \"../libs/FunctionReferenceLib.sol\";\nimport {RepeatableFunctionReferenceDLLLib} from \"../libs/RepeatableFunctionReferenceDLLLib.sol\";\nimport {SelectorRegistryLib} from \"../libs/SelectorRegistryLib.sol\";\nimport {WalletStorageV1Lib} from \"../libs/WalletStorageV1Lib.sol\";\nimport {ERC165Checker} from \"@openzeppelin/contracts/utils/introspection/ERC165Checker.sol\";\n\n/**\n * @dev Default implementation of https://eips.ethereum.org/EIPS/eip-6900. MSCAs must implement this interface to\n * support installing and uninstalling plugins.\n */\ncontract PluginManager {\n using AddressDLLLib for AddressDLL;\n using FunctionReferenceDLLLib for Bytes21DLL;\n using RepeatableFunctionReferenceDLLLib for RepeatableBytes21DLL;\n using FunctionReferenceLib for FunctionReference;\n using FunctionReferenceLib for bytes21;\n using SelectorRegistryLib for bytes4;\n\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment\n address private immutable SELF = address(this);\n\n enum AssociatedFunctionType {\n HOOK,\n VALIDATION_FUNCTION\n }\n\n error PluginNotImplementInterface();\n error InvalidPluginManifest();\n error InvalidPluginManifestHash();\n error InvalidPluginDependency(address plugin);\n error PluginUsedByOthers(address plugin);\n error ExecutionDetailAlreadySet(address plugin, bytes4 selector);\n error ExecuteFromPluginExternalAlreadySet(address plugin, address externalAddress);\n error ExecuteFromPluginExternalAlreadyUnset(address plugin, address externalAddress);\n error ValidationFunctionAlreadySet(bytes4 selector);\n error FailToCallOnInstall(address plugin, bytes revertReason);\n error OnlyDelegated();\n error HookDependencyNotPermitted();\n error InvalidExecutionSelector(address plugin, bytes4 selector);\n\n modifier onlyDelegated() {\n if (address(this) == SELF) {\n revert OnlyDelegated();\n }\n _;\n }\n\n /// @dev Refer to IPluginManager\n function install(\n address plugin,\n bytes32 manifestHash,\n bytes memory pluginInstallData,\n FunctionReference[] memory dependencies,\n address msca\n ) external onlyDelegated {\n // revert if the plugin does not implement ERC-165 or does not support the IPlugin interface\n if (!ERC165Checker.supportsInterface(plugin, type(IPlugin).interfaceId)) {\n revert PluginNotImplementInterface();\n }\n WalletStorageV1Lib.Layout storage storageLayout = WalletStorageV1Lib.getLayout();\n // revert internally if the plugin has already been installed on the modular account\n storageLayout.installedPlugins.append(plugin);\n IPlugin pluginToInstall = IPlugin(plugin);\n // revert if manifestHash does not match the computed Keccak-256 hash of the plugin’s returned manifest\n PluginManifest memory pluginManifest = pluginToInstall.pluginManifest();\n if (manifestHash != keccak256(abi.encode(pluginManifest))) {\n revert InvalidPluginManifestHash();\n }\n uint256 length = pluginManifest.interfaceIds.length;\n for (uint256 i = 0; i < length; ++i) {\n storageLayout.supportedInterfaces[pluginManifest.interfaceIds[i]] += 1;\n }\n // revert if any address in dependencies does not support the interface at its matching index in the manifest’s\n // dependencyInterfaceIds,\n // or if the two array lengths do not match,\n // or if any of the dependencies are not already installed on the modular account\n length = dependencies.length;\n if (length != pluginManifest.dependencyInterfaceIds.length) {\n revert InvalidPluginDependency(plugin);\n }\n for (uint256 i = 0; i < length; ++i) {\n address dependencyPluginAddr = dependencies[i].plugin;\n // if dependencyPluginAddr is msca address, then we don't actually introduce any new plugin dependency\n // other than native dependency, so we do not need to perform any plugin dependency related logic\n if (dependencyPluginAddr == msca) {\n continue;\n }\n // verify that the dependency is installed, which also prevents self-dependencies\n if (storageLayout.pluginDetails[dependencyPluginAddr].manifestHash == bytes32(0)) {\n revert InvalidPluginDependency(dependencyPluginAddr);\n }\n if (!ERC165Checker.supportsInterface(dependencyPluginAddr, pluginManifest.dependencyInterfaceIds[i])) {\n revert InvalidPluginDependency(dependencyPluginAddr);\n }\n // each dependency’s record MUST also be updated to reflect that it has a new dependent\n // record the plugin dependency, will revert if it's already installed\n storageLayout.pluginDetails[plugin].dependencies.append(dependencies[i]);\n // increment the dependency's dependentCounter since the current plugin is dependent on dependencyPlugin\n storageLayout.pluginDetails[dependencyPluginAddr].dependentCounter += 1;\n }\n\n // record if this plugin is allowed to spend native token\n if (pluginManifest.canSpendNativeToken) {\n storageLayout.pluginDetails[plugin].canSpendNativeToken = true;\n }\n\n // record execution details\n //////////////////////////////////////////////\n // install execution functions and hooks\n //////////////////////////////////////////////\n length = pluginManifest.executionFunctions.length;\n for (uint256 i = 0; i < length; ++i) {\n bytes4 selector = pluginManifest.executionFunctions[i];\n if (storageLayout.executionDetails[selector].plugin != address(0)) {\n revert ExecutionDetailAlreadySet(plugin, selector);\n }\n if (\n selector._isNativeFunctionSelector() || selector._isErc4337FunctionSelector()\n || selector._isIPluginFunctionSelector()\n ) {\n revert InvalidExecutionSelector(plugin, selector);\n }\n storageLayout.executionDetails[selector].plugin = plugin;\n }\n\n // install pre and post execution hooks\n length = pluginManifest.executionHooks.length;\n for (uint256 i = 0; i < length; ++i) {\n bytes4 selector = pluginManifest.executionHooks[i].selector;\n FunctionReference memory preExecHook = _resolveManifestFunction(\n pluginManifest.executionHooks[i].preExecHook,\n plugin,\n dependencies,\n ManifestAssociatedFunctionType.PRE_HOOK_ALWAYS_DENY,\n AssociatedFunctionType.HOOK\n );\n FunctionReference memory postExecHook = _resolveManifestFunction(\n pluginManifest.executionHooks[i].postExecHook,\n plugin,\n dependencies,\n ManifestAssociatedFunctionType.NONE,\n AssociatedFunctionType.HOOK\n );\n _addHookGroup(storageLayout.executionDetails[selector].executionHooks, preExecHook, postExecHook);\n }\n\n //////////////////////////////////////////////\n // install validation functions and hooks\n //////////////////////////////////////////////\n // install userOpValidationFunctions\n length = pluginManifest.userOpValidationFunctions.length;\n for (uint256 i = 0; i < length; ++i) {\n bytes4 selector = pluginManifest.userOpValidationFunctions[i].executionSelector;\n if (storageLayout.executionDetails[selector].userOpValidationFunction.pack() != EMPTY_FUNCTION_REFERENCE) {\n revert ValidationFunctionAlreadySet(selector);\n }\n storageLayout.executionDetails[selector].userOpValidationFunction = _resolveManifestFunction(\n pluginManifest.userOpValidationFunctions[i].associatedFunction,\n plugin,\n dependencies,\n ManifestAssociatedFunctionType.NONE,\n AssociatedFunctionType.VALIDATION_FUNCTION\n );\n }\n // install runtimeValidationFunctions\n length = pluginManifest.runtimeValidationFunctions.length;\n for (uint256 i = 0; i < length; ++i) {\n bytes4 selector = pluginManifest.runtimeValidationFunctions[i].executionSelector;\n if (storageLayout.executionDetails[selector].runtimeValidationFunction.pack() != EMPTY_FUNCTION_REFERENCE) {\n revert ValidationFunctionAlreadySet(selector);\n }\n storageLayout.executionDetails[selector].runtimeValidationFunction = _resolveManifestFunction(\n pluginManifest.runtimeValidationFunctions[i].associatedFunction,\n plugin,\n dependencies,\n ManifestAssociatedFunctionType.RUNTIME_VALIDATION_ALWAYS_ALLOW, // risk burning gas from the account\n AssociatedFunctionType.VALIDATION_FUNCTION\n );\n }\n // install preUserOpValidationHooks\n length = pluginManifest.preUserOpValidationHooks.length;\n // force override to be safe\n FunctionReference[] memory emptyDependencies = new FunctionReference[](0);\n for (uint256 i = 0; i < length; ++i) {\n bytes4 selector = pluginManifest.preUserOpValidationHooks[i].executionSelector;\n // revert internally\n storageLayout.executionDetails[selector].preUserOpValidationHooks.append(\n _resolveManifestFunction(\n pluginManifest.preUserOpValidationHooks[i].associatedFunction,\n plugin,\n emptyDependencies,\n ManifestAssociatedFunctionType.PRE_HOOK_ALWAYS_DENY,\n AssociatedFunctionType.HOOK\n )\n );\n }\n // install preRuntimeValidationHooks\n length = pluginManifest.preRuntimeValidationHooks.length;\n for (uint256 i = 0; i < length; ++i) {\n // revert internally\n storageLayout.executionDetails[pluginManifest.preRuntimeValidationHooks[i].executionSelector]\n .preRuntimeValidationHooks\n .append(\n _resolveManifestFunction(\n pluginManifest.preRuntimeValidationHooks[i].associatedFunction,\n plugin,\n emptyDependencies,\n ManifestAssociatedFunctionType.PRE_HOOK_ALWAYS_DENY,\n AssociatedFunctionType.HOOK\n )\n );\n }\n\n // store the plugin’s permitted function selectors and external contract calls to be able to validate calls\n // to executeFromPlugin and executeFromPluginExternal\n //////////////////////////////////////////////\n // permissions for executeFromPlugin\n //////////////////////////////////////////////\n // native functions or execution functions already installed on the MSCA that this plugin will be able to call\n length = pluginManifest.permittedExecutionSelectors.length;\n for (uint256 i = 0; i < length; ++i) {\n // enable PermittedPluginCall\n storageLayout.permittedPluginCalls[plugin][pluginManifest.permittedExecutionSelectors[i]] = true;\n }\n\n //////////////////////////////////////////////\n // permissions for executeFromPluginExternal\n //////////////////////////////////////////////\n // is the plugin permitted to call any external contracts and selectors\n if (pluginManifest.permitAnyExternalAddress) {\n storageLayout.pluginDetails[plugin].anyExternalAddressPermitted = true;\n } else {\n // more limited access - record external contract calls that this plugin will be able to make\n length = pluginManifest.permittedExternalCalls.length;\n for (uint256 i = 0; i < length; ++i) {\n ManifestExternalCallPermission memory externalCallPermission = pluginManifest.permittedExternalCalls[i];\n PermittedExternalCall storage permittedExternalCall =\n storageLayout.permittedExternalCalls[plugin][externalCallPermission.externalAddress];\n if (permittedExternalCall.addressPermitted) {\n revert ExecuteFromPluginExternalAlreadySet(plugin, externalCallPermission.externalAddress);\n }\n permittedExternalCall.addressPermitted = true;\n if (externalCallPermission.permitAnySelector) {\n permittedExternalCall.anySelector = true;\n } else {\n uint256 permittedExternalCallSelectorsLength = externalCallPermission.selectors.length;\n for (uint256 j = 0; j < permittedExternalCallSelectorsLength; ++j) {\n permittedExternalCall.selectors[externalCallPermission.selectors[j]] = true;\n }\n }\n }\n }\n\n // store the plugin manifest hash at the end, which serves to prevent self-dependencies\n storageLayout.pluginDetails[plugin].manifestHash = manifestHash;\n // call onInstall to initialize plugin data for the modular account\n // solhint-disable-next-line no-empty-blocks\n try IPlugin(plugin).onInstall(pluginInstallData) {}\n catch (bytes memory revertReason) {\n revert FailToCallOnInstall(plugin, revertReason);\n }\n }\n\n /// @dev Refer to IPluginManager\n function uninstall(address plugin, bytes memory config, bytes memory pluginUninstallData)\n external\n onlyDelegated\n returns (bool)\n {\n WalletStorageV1Lib.Layout storage storageLayout = WalletStorageV1Lib.getLayout();\n // revert internally if plugin was not installed before\n storageLayout.installedPlugins.remove(plugin);\n PluginManifest memory pluginManifest;\n if (config.length > 0) {\n // the modular account MAY implement the capability for the manifest to be encoded in the config field as a\n // parameter\n pluginManifest = abi.decode(config, (PluginManifest));\n } else {\n pluginManifest = IPlugin(plugin).pluginManifest();\n }\n // revert if the hash of the manifest used at install time does not match the computed Keccak-256 hash of the\n // plugin’s current manifest\n if (storageLayout.pluginDetails[plugin].manifestHash != keccak256(abi.encode(pluginManifest))) {\n revert InvalidPluginManifestHash();\n }\n // revert if there is at least 1 other installed plugin that depends on validation functions or hooks added by\n // this plugin;\n // plugins used as dependencies must not be uninstalled while dependent plugins exist\n if (storageLayout.pluginDetails[plugin].dependentCounter != 0) {\n revert PluginUsedByOthers(plugin);\n }\n // each dependency’s record SHOULD be updated to reflect that it has no longer has this plugin as a dependent\n _removeDependencies(plugin, storageLayout);\n // remove records for the plugin’s dependencies, injected permitted call hooks, permitted function selectors,\n // and permitted external contract calls\n // uninstall the components in reverse order (by component type) of their installation\n //////////////////////////////////////////////\n // permissions for executeFromPluginExternal\n //////////////////////////////////////////////\n if (pluginManifest.permitAnyExternalAddress) {\n storageLayout.pluginDetails[plugin].anyExternalAddressPermitted = false;\n }\n uint256 length;\n if (!pluginManifest.permitAnyExternalAddress) {\n length = pluginManifest.permittedExternalCalls.length;\n for (uint256 i = 0; i < length; ++i) {\n ManifestExternalCallPermission memory externalCallPermission = pluginManifest.permittedExternalCalls[i];\n PermittedExternalCall storage permittedExternalCall =\n storageLayout.permittedExternalCalls[plugin][externalCallPermission.externalAddress];\n if (!permittedExternalCall.addressPermitted) {\n revert ExecuteFromPluginExternalAlreadyUnset(plugin, externalCallPermission.externalAddress);\n }\n permittedExternalCall.addressPermitted = false;\n if (externalCallPermission.permitAnySelector) {\n permittedExternalCall.anySelector = false;\n } else {\n uint256 permittedExternalCallSelectorsLength = externalCallPermission.selectors.length;\n for (uint256 j = 0; j < permittedExternalCallSelectorsLength; ++j) {\n permittedExternalCall.selectors[externalCallPermission.selectors[j]] = false;\n }\n }\n }\n }\n\n length = pluginManifest.permittedExecutionSelectors.length;\n for (uint256 i = 0; i < length; ++i) {\n // disable PermittedPluginCall\n storageLayout.permittedPluginCalls[plugin][pluginManifest.permittedExecutionSelectors[i]] = false;\n }\n\n //////////////////////////////////////////////\n // uninstall validation functions and hooks\n //////////////////////////////////////////////\n // uninstall preRuntimeValidationHooks\n FunctionReference[] memory emptyDependencies = new FunctionReference[](0);\n length = pluginManifest.preRuntimeValidationHooks.length;\n for (uint256 i = 0; i < length; ++i) {\n // revert internally\n storageLayout.executionDetails[pluginManifest.preRuntimeValidationHooks[i].executionSelector]\n .preRuntimeValidationHooks\n .remove(\n _resolveManifestFunction(\n pluginManifest.preRuntimeValidationHooks[i].associatedFunction,\n plugin,\n emptyDependencies,\n ManifestAssociatedFunctionType.PRE_HOOK_ALWAYS_DENY,\n AssociatedFunctionType.HOOK\n )\n );\n }\n // uninstall preUserOpValidationHooks\n length = pluginManifest.preUserOpValidationHooks.length;\n for (uint256 i = 0; i < length; ++i) {\n // revert internally\n storageLayout.executionDetails[pluginManifest.preUserOpValidationHooks[i].executionSelector]\n .preUserOpValidationHooks\n .remove(\n _resolveManifestFunction(\n pluginManifest.preUserOpValidationHooks[i].associatedFunction,\n plugin,\n emptyDependencies,\n ManifestAssociatedFunctionType.PRE_HOOK_ALWAYS_DENY,\n AssociatedFunctionType.HOOK\n )\n );\n }\n // uninstall runtimeValidationFunctions\n FunctionReference memory emptyFunctionReference = EMPTY_FUNCTION_REFERENCE.unpack();\n length = pluginManifest.runtimeValidationFunctions.length;\n for (uint256 i = 0; i < length; ++i) {\n storageLayout.executionDetails[pluginManifest.runtimeValidationFunctions[i].executionSelector]\n .runtimeValidationFunction = emptyFunctionReference;\n }\n // uninstall userOpValidationFunctions\n length = pluginManifest.userOpValidationFunctions.length;\n for (uint256 i = 0; i < length; ++i) {\n storageLayout.executionDetails[pluginManifest.userOpValidationFunctions[i].executionSelector]\n .userOpValidationFunction = emptyFunctionReference;\n }\n\n //////////////////////////////////////////////\n // uninstall execution functions and hooks\n //////////////////////////////////////////////\n _removeExecutionHooks(plugin, pluginManifest.executionHooks, storageLayout);\n length = pluginManifest.executionFunctions.length;\n for (uint256 i = 0; i < length; ++i) {\n storageLayout.executionDetails[pluginManifest.executionFunctions[i]].plugin = address(0);\n }\n\n length = pluginManifest.interfaceIds.length;\n for (uint256 i = 0; i < length; ++i) {\n storageLayout.supportedInterfaces[pluginManifest.interfaceIds[i]] -= 1;\n }\n // reset all members that are not mappings and also recurse into the members unless they're mappings\n delete storageLayout.pluginDetails[plugin];\n // call the plugin’s onUninstall callback with the data provided in the uninstallData parameter;\n // This serves to clear the plugin state for the modular account;\n // If onUninstall reverts, execution SHOULD continue to allow the uninstall to complete\n bool onUninstallSucceeded = true;\n // solhint-disable-next-line no-empty-blocks\n try IPlugin(plugin).onUninstall(pluginUninstallData) {}\n catch {\n // leave it up to the caller if we want to revert if the plugin storage isn't cleaned up\n onUninstallSucceeded = false;\n }\n return onUninstallSucceeded;\n }\n\n /**\n * @dev Resolve manifest function.\n * For functions of type `ManifestAssociatedFunctionType.DEPENDENCY`, the MSCA MUST find the plugin address\n * of the function at `dependencies[dependencyIndex]` during the call to `installPlugin(config)`.\n * A plugin can no longer use hooks from other plugins to be added on Execution and/or Validation function\n * selectors\n * in its own manifest. We'll revert if hook is provided as dependency from an external plugin.\n * @param allowedMagicValue which magic value (if any) is permissible for the function type to resolve.\n * @param associatedFunctionType the type of associated function, either a validation function or a hook, as opposed\n * to execution functions\n */\n function _resolveManifestFunction(\n ManifestFunction memory manifestFunction,\n address plugin,\n FunctionReference[] memory dependencies,\n ManifestAssociatedFunctionType allowedMagicValue,\n AssociatedFunctionType associatedFunctionType\n ) internal pure returns (FunctionReference memory) {\n // revert if it's hook and provided as dependency\n if (\n associatedFunctionType == AssociatedFunctionType.HOOK\n && manifestFunction.functionType == ManifestAssociatedFunctionType.DEPENDENCY\n ) {\n revert HookDependencyNotPermitted();\n }\n if (manifestFunction.functionType == ManifestAssociatedFunctionType.SELF) {\n return FunctionReference(plugin, manifestFunction.functionId);\n } else if (manifestFunction.functionType == ManifestAssociatedFunctionType.DEPENDENCY) {\n // out of boundary\n if (manifestFunction.dependencyIndex >= dependencies.length) {\n revert InvalidPluginManifest();\n }\n return dependencies[manifestFunction.dependencyIndex];\n } else if (manifestFunction.functionType == ManifestAssociatedFunctionType.RUNTIME_VALIDATION_ALWAYS_ALLOW) {\n if (allowedMagicValue == ManifestAssociatedFunctionType.RUNTIME_VALIDATION_ALWAYS_ALLOW) {\n return RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE.unpack();\n } else {\n revert InvalidPluginManifest();\n }\n } else if (manifestFunction.functionType == ManifestAssociatedFunctionType.PRE_HOOK_ALWAYS_DENY) {\n if (allowedMagicValue == ManifestAssociatedFunctionType.PRE_HOOK_ALWAYS_DENY) {\n return PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE.unpack();\n } else {\n revert InvalidPluginManifest();\n }\n } else {\n return EMPTY_FUNCTION_REFERENCE.unpack();\n }\n }\n\n function _addHookGroup(\n HookGroup storage hookGroup,\n FunctionReference memory preExecHook,\n FunctionReference memory postExecHook\n ) internal {\n bytes21 packedPreExecHook = preExecHook.pack();\n if (packedPreExecHook == EMPTY_FUNCTION_REFERENCE) {\n if (postExecHook.pack() == EMPTY_FUNCTION_REFERENCE) {\n // pre and post hooks cannot be null at the same time\n revert InvalidFunctionReference();\n }\n hookGroup.postOnlyHooks.append(postExecHook);\n } else {\n hookGroup.preHooks.append(preExecHook);\n if (postExecHook.pack() != EMPTY_FUNCTION_REFERENCE) {\n hookGroup.preToPostHooks[packedPreExecHook].append(postExecHook);\n }\n }\n }\n\n function _removeHookGroup(\n HookGroup storage hookGroup,\n FunctionReference memory preExecHook,\n FunctionReference memory postExecHook\n ) internal {\n bytes21 packedPreExecHook = preExecHook.pack();\n if (packedPreExecHook == EMPTY_FUNCTION_REFERENCE) {\n // pre and post hooks cannot be null at the same time\n hookGroup.postOnlyHooks.remove(postExecHook);\n } else {\n hookGroup.preHooks.remove(preExecHook);\n // remove postExecHook if any\n if (postExecHook.pack() != EMPTY_FUNCTION_REFERENCE) {\n hookGroup.preToPostHooks[packedPreExecHook].remove(postExecHook);\n }\n }\n }\n\n function _removeDependencies(address plugin, WalletStorageV1Lib.Layout storage storageLayout) internal {\n Bytes21DLL storage pluginDependencies = storageLayout.pluginDetails[plugin].dependencies;\n uint256 length = pluginDependencies.size();\n FunctionReference memory startFR = EMPTY_FUNCTION_REFERENCE.unpack();\n FunctionReference[] memory dependencies;\n for (uint256 i = 0; i < length; ++i) {\n // if the max length of dependencies is reached, the loop will break early\n (dependencies, startFR) = pluginDependencies.getPaginated(startFR, 10);\n for (uint256 j = 0; j < dependencies.length; ++j) {\n storageLayout.pluginDetails[dependencies[j].plugin].dependentCounter -= 1;\n storageLayout.pluginDetails[plugin].dependencies.remove(dependencies[j]);\n }\n if (startFR.pack() == EMPTY_FUNCTION_REFERENCE) {\n break;\n }\n }\n }\n\n function _removeExecutionHooks(\n address plugin,\n ManifestExecutionHook[] memory executionHooks,\n WalletStorageV1Lib.Layout storage storageLayout\n ) internal {\n uint256 length = executionHooks.length;\n FunctionReference[] memory dependencies = new FunctionReference[](0);\n for (uint256 i = 0; i < length; ++i) {\n bytes4 selector = executionHooks[i].selector;\n FunctionReference memory preExecHook = _resolveManifestFunction(\n executionHooks[i].preExecHook,\n plugin,\n dependencies,\n ManifestAssociatedFunctionType.PRE_HOOK_ALWAYS_DENY,\n AssociatedFunctionType.HOOK\n );\n FunctionReference memory postExecHookToRemove = _resolveManifestFunction(\n executionHooks[i].postExecHook,\n plugin,\n dependencies,\n ManifestAssociatedFunctionType.NONE,\n AssociatedFunctionType.HOOK\n );\n _removeHookGroup(storageLayout.executionDetails[selector].executionHooks, preExecHook, postExecHookToRemove);\n }\n }\n}\n"},"lib/account-abstraction/contracts/interfaces/IEntryPoint.sol":{"content":"/**\n ** Account-Abstraction (EIP-4337) singleton EntryPoint implementation.\n ** Only one instance required on each chain.\n **/\n// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\n/* solhint-disable avoid-low-level-calls */\n/* solhint-disable no-inline-assembly */\n/* solhint-disable reason-string */\n\nimport \"./UserOperation.sol\";\nimport \"./IStakeManager.sol\";\nimport \"./IAggregator.sol\";\nimport \"./INonceManager.sol\";\n\ninterface IEntryPoint is IStakeManager, INonceManager {\n\n /***\n * An event emitted after each successful request\n * @param userOpHash - unique identifier for the request (hash its entire content, except signature).\n * @param sender - the account that generates this request.\n * @param paymaster - if non-null, the paymaster that pays for this request.\n * @param nonce - the nonce value from the request.\n * @param success - true if the sender transaction succeeded, false if reverted.\n * @param actualGasCost - actual amount paid (by account or paymaster) for this UserOperation.\n * @param actualGasUsed - total gas used by this UserOperation (including preVerification, creation, validation and execution).\n */\n event UserOperationEvent(bytes32 indexed userOpHash, address indexed sender, address indexed paymaster, uint256 nonce, bool success, uint256 actualGasCost, uint256 actualGasUsed);\n\n /**\n * account \"sender\" was deployed.\n * @param userOpHash the userOp that deployed this account. UserOperationEvent will follow.\n * @param sender the account that is deployed\n * @param factory the factory used to deploy this account (in the initCode)\n * @param paymaster the paymaster used by this UserOp\n */\n event AccountDeployed(bytes32 indexed userOpHash, address indexed sender, address factory, address paymaster);\n\n /**\n * An event emitted if the UserOperation \"callData\" reverted with non-zero length\n * @param userOpHash the request unique identifier.\n * @param sender the sender of this request\n * @param nonce the nonce used in the request\n * @param revertReason - the return bytes from the (reverted) call to \"callData\".\n */\n event UserOperationRevertReason(bytes32 indexed userOpHash, address indexed sender, uint256 nonce, bytes revertReason);\n\n /**\n * an event emitted by handleOps(), before starting the execution loop.\n * any event emitted before this event, is part of the validation.\n */\n event BeforeExecution();\n\n /**\n * signature aggregator used by the following UserOperationEvents within this bundle.\n */\n event SignatureAggregatorChanged(address indexed aggregator);\n\n /**\n * a custom revert error of handleOps, to identify the offending op.\n * NOTE: if simulateValidation passes successfully, there should be no reason for handleOps to fail on it.\n * @param opIndex - index into the array of ops to the failed one (in simulateValidation, this is always zero)\n * @param reason - revert reason\n * The string starts with a unique code \"AAmn\", where \"m\" is \"1\" for factory, \"2\" for account and \"3\" for paymaster issues,\n * so a failure can be attributed to the correct entity.\n * Should be caught in off-chain handleOps simulation and not happen on-chain.\n * Useful for mitigating DoS attempts against batchers or for troubleshooting of factory/account/paymaster reverts.\n */\n error FailedOp(uint256 opIndex, string reason);\n\n /**\n * error case when a signature aggregator fails to verify the aggregated signature it had created.\n */\n error SignatureValidationFailed(address aggregator);\n\n /**\n * Successful result from simulateValidation.\n * @param returnInfo gas and time-range returned values\n * @param senderInfo stake information about the sender\n * @param factoryInfo stake information about the factory (if any)\n * @param paymasterInfo stake information about the paymaster (if any)\n */\n error ValidationResult(ReturnInfo returnInfo,\n StakeInfo senderInfo, StakeInfo factoryInfo, StakeInfo paymasterInfo);\n\n /**\n * Successful result from simulateValidation, if the account returns a signature aggregator\n * @param returnInfo gas and time-range returned values\n * @param senderInfo stake information about the sender\n * @param factoryInfo stake information about the factory (if any)\n * @param paymasterInfo stake information about the paymaster (if any)\n * @param aggregatorInfo signature aggregation info (if the account requires signature aggregator)\n * bundler MUST use it to verify the signature, or reject the UserOperation\n */\n error ValidationResultWithAggregation(ReturnInfo returnInfo,\n StakeInfo senderInfo, StakeInfo factoryInfo, StakeInfo paymasterInfo,\n AggregatorStakeInfo aggregatorInfo);\n\n /**\n * return value of getSenderAddress\n */\n error SenderAddressResult(address sender);\n\n /**\n * return value of simulateHandleOp\n */\n error ExecutionResult(uint256 preOpGas, uint256 paid, uint48 validAfter, uint48 validUntil, bool targetSuccess, bytes targetResult);\n\n //UserOps handled, per aggregator\n struct UserOpsPerAggregator {\n UserOperation[] userOps;\n\n // aggregator address\n IAggregator aggregator;\n // aggregated signature\n bytes signature;\n }\n\n /**\n * Execute a batch of UserOperation.\n * no signature aggregator is used.\n * if any account requires an aggregator (that is, it returned an aggregator when\n * performing simulateValidation), then handleAggregatedOps() must be used instead.\n * @param ops the operations to execute\n * @param beneficiary the address to receive the fees\n */\n function handleOps(UserOperation[] calldata ops, address payable beneficiary) external;\n\n /**\n * Execute a batch of UserOperation with Aggregators\n * @param opsPerAggregator the operations to execute, grouped by aggregator (or address(0) for no-aggregator accounts)\n * @param beneficiary the address to receive the fees\n */\n function handleAggregatedOps(\n UserOpsPerAggregator[] calldata opsPerAggregator,\n address payable beneficiary\n ) external;\n\n /**\n * generate a request Id - unique identifier for this request.\n * the request ID is a hash over the content of the userOp (except the signature), the entrypoint and the chainid.\n */\n function getUserOpHash(UserOperation calldata userOp) external view returns (bytes32);\n\n /**\n * Simulate a call to account.validateUserOp and paymaster.validatePaymasterUserOp.\n * @dev this method always revert. Successful result is ValidationResult error. other errors are failures.\n * @dev The node must also verify it doesn't use banned opcodes, and that it doesn't reference storage outside the account's data.\n * @param userOp the user operation to validate.\n */\n function simulateValidation(UserOperation calldata userOp) external;\n\n /**\n * gas and return values during simulation\n * @param preOpGas the gas used for validation (including preValidationGas)\n * @param prefund the required prefund for this operation\n * @param sigFailed validateUserOp's (or paymaster's) signature check failed\n * @param validAfter - first timestamp this UserOp is valid (merging account and paymaster time-range)\n * @param validUntil - last timestamp this UserOp is valid (merging account and paymaster time-range)\n * @param paymasterContext returned by validatePaymasterUserOp (to be passed into postOp)\n */\n struct ReturnInfo {\n uint256 preOpGas;\n uint256 prefund;\n bool sigFailed;\n uint48 validAfter;\n uint48 validUntil;\n bytes paymasterContext;\n }\n\n /**\n * returned aggregated signature info.\n * the aggregator returned by the account, and its current stake.\n */\n struct AggregatorStakeInfo {\n address aggregator;\n StakeInfo stakeInfo;\n }\n\n /**\n * Get counterfactual sender address.\n * Calculate the sender contract address that will be generated by the initCode and salt in the UserOperation.\n * this method always revert, and returns the address in SenderAddressResult error\n * @param initCode the constructor code to be passed into the UserOperation.\n */\n function getSenderAddress(bytes memory initCode) external;\n\n\n /**\n * simulate full execution of a UserOperation (including both validation and target execution)\n * this method will always revert with \"ExecutionResult\".\n * it performs full validation of the UserOperation, but ignores signature error.\n * an optional target address is called after the userop succeeds, and its value is returned\n * (before the entire call is reverted)\n * Note that in order to collect the the success/failure of the target call, it must be executed\n * with trace enabled to track the emitted events.\n * @param op the UserOperation to simulate\n * @param target if nonzero, a target address to call after userop simulation. If called, the targetSuccess and targetResult\n * are set to the return from that call.\n * @param targetCallData callData to pass to target address\n */\n function simulateHandleOp(UserOperation calldata op, address target, bytes calldata targetCallData) external;\n}\n\n"},"node_modules/@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/ERC1967/ERC1967Proxy.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Proxy.sol\";\nimport \"./ERC1967Upgrade.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n */\ncontract ERC1967Proxy is Proxy, ERC1967Upgrade {\n /**\n * @dev Initializes the upgradeable proxy with an initial implementation specified by `_logic`.\n *\n * If `_data` is nonempty, it's used as data in a delegate call to `_logic`. This will typically be an encoded\n * function call, and allows initializing the storage of the proxy like a Solidity constructor.\n */\n constructor(address _logic, bytes memory _data) payable {\n _upgradeToAndCall(_logic, _data, false);\n }\n\n /**\n * @dev Returns the current implementation address.\n */\n function _implementation() internal view virtual override returns (address impl) {\n return ERC1967Upgrade._getImplementation();\n }\n}\n"},"node_modules/@openzeppelin/contracts/utils/Create2.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Create2.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.\n * `CREATE2` can be used to compute in advance the address where a smart\n * contract will be deployed, which allows for interesting new mechanisms known\n * as 'counterfactual interactions'.\n *\n * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more\n * information.\n */\nlibrary Create2 {\n /**\n * @dev Deploys a contract using `CREATE2`. The address where the contract\n * will be deployed can be known in advance via {computeAddress}.\n *\n * The bytecode for a contract can be obtained from Solidity with\n * `type(contractName).creationCode`.\n *\n * Requirements:\n *\n * - `bytecode` must not be empty.\n * - `salt` must have not been used for `bytecode` already.\n * - the factory must have a balance of at least `amount`.\n * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.\n */\n function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {\n require(address(this).balance >= amount, \"Create2: insufficient balance\");\n require(bytecode.length != 0, \"Create2: bytecode length is zero\");\n /// @solidity memory-safe-assembly\n assembly {\n addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)\n }\n require(addr != address(0), \"Create2: Failed on deploy\");\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the\n * `bytecodeHash` or `salt` will result in a new destination address.\n */\n function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {\n return computeAddress(salt, bytecodeHash, address(this));\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n */\n function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {\n /// @solidity memory-safe-assembly\n assembly {\n let ptr := mload(0x40) // Get free memory pointer\n\n // | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |\n // |-------------------|---------------------------------------------------------------------------|\n // | bytecodeHash | CCCCCCCCCCCCC...CC |\n // | salt | BBBBBBBBBBBBB...BB |\n // | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |\n // | 0xFF | FF |\n // |-------------------|---------------------------------------------------------------------------|\n // | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |\n // | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |\n\n mstore(add(ptr, 0x40), bytecodeHash)\n mstore(add(ptr, 0x20), salt)\n mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes\n let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff\n mstore8(start, 0xff)\n addr := keccak256(start, 85)\n }\n }\n}\n"},"src/callback/DefaultCallbackHandler.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {IERC777Recipient} from \"@openzeppelin/contracts/interfaces/IERC777Recipient.sol\";\nimport {IERC1155Receiver} from \"@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol\";\nimport {IERC721Receiver} from \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\n/**\n * @dev Token callback handler. Allowing account receiving these tokens.\n * @notice The user will have to register itself in the ERC1820 global registry\n * in order to fully support ERC777 token operations upon the installation of this plugin.\n */\ncontract DefaultCallbackHandler is IERC721Receiver, IERC1155Receiver, IERC777Recipient {\n function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {\n return interfaceId == type(IERC721Receiver).interfaceId || interfaceId == type(IERC1155Receiver).interfaceId\n || interfaceId == type(IERC165).interfaceId;\n }\n\n function onERC1155Received(address, address, uint256, uint256, bytes calldata)\n external\n pure\n override\n returns (bytes4)\n {\n return IERC1155Receiver.onERC1155Received.selector;\n }\n\n function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata)\n external\n pure\n override\n returns (bytes4)\n {\n return IERC1155Receiver.onERC1155BatchReceived.selector;\n }\n\n function onERC721Received(address, address, uint256, bytes calldata) external pure override returns (bytes4) {\n return IERC721Receiver.onERC721Received.selector;\n }\n\n // ERC777\n function tokensReceived(\n address operator,\n address from,\n address to,\n uint256 amount,\n bytes calldata userData,\n bytes calldata operatorData\n ) external pure override \n // solhint-disable-next-line no-empty-blocks\n {}\n}\n"},"src/common/Constants.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\n// ERC4337 constants\n\n// return value in case of signature failure, with no time-range.\n// equivalent to _packValidationData(true,0,0);\nuint256 constant SIG_VALIDATION_FAILED = 1;\nuint256 constant SIG_VALIDATION_SUCCEEDED = 0;\n\n// sentinel values\n// any values less than or equal to this will not be allowed in storage\nbytes21 constant SENTINEL_BYTES21 = bytes21(0);\nbytes23 constant SENTINEL_BYTES23 = bytes23(0);\nbytes32 constant SENTINEL_BYTES32 = bytes32(0);\n\n// empty or unset function reference\n// we don't store the empty function reference\nbytes21 constant EMPTY_FUNCTION_REFERENCE = bytes21(0);\n\n// wallet constants\nstring constant WALLET_AUTHOR = \"Circle Internet Financial\";\nstring constant WALLET_VERSION_1 = \"1.0.0\";\n\n// plugin constants\nstring constant PLUGIN_AUTHOR = \"Circle Internet Financial\";\nstring constant PLUGIN_VERSION_1 = \"1.0.0\";\n\n// bytes4(keccak256(\"isValidSignature(bytes32,bytes)\")\nbytes4 constant EIP1271_VALID_SIGNATURE = 0x1626ba7e;\nbytes4 constant EIP1271_INVALID_SIGNATURE = 0xffffffff;\n\n// keccak256('')\nbytes32 constant EMPTY_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n\nuint256 constant ZERO = 0;\n\nbytes32 constant ZERO_BYTES32 = bytes32(0);\nbytes24 constant EMPTY_MODULE_ENTITY = bytes24(0);\n"},"src/common/Errors.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\n/**\n * @notice Throws when the caller is unexpected.\n */\nerror UnauthorizedCaller();\n\nerror InvalidLength();\n\nerror Unsupported();\n"},"src/utils/ExecutionUtils.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\n/**\n * Utility functions helpful when making different kinds of contract calls in Solidity.\n * For inline assembly, please refer to https://docs.soliditylang.org/en/latest/assembly.html\n * For opcodes, please refer to https://ethereum.org/en/developers/docs/evm/opcodes/ and https://www.evm.codes/\n */\nlibrary ExecutionUtils {\n function call(address to, uint256 value, bytes memory data)\n internal\n returns (bool success, bytes memory returnData)\n {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n success := call(gas(), to, value, add(data, 0x20), mload(data), 0, 0)\n let len := returndatasize()\n let ptr := mload(0x40)\n mstore(0x40, add(ptr, add(len, 0x20)))\n mstore(ptr, len)\n returndatacopy(add(ptr, 0x20), 0, len)\n returnData := ptr\n }\n }\n\n function revertWithData(bytes memory returnData) internal pure {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n revert(add(returnData, 32), mload(returnData))\n }\n }\n\n function callAndRevert(address to, uint256 value, bytes memory data) internal {\n (bool success, bytes memory returnData) = call(to, value, data);\n if (!success) {\n revertWithData(returnData);\n }\n }\n\n function callWithReturnDataOrRevert(address to, uint256 value, bytes memory data) internal returns (bytes memory) {\n (bool success, bytes memory returnData) = call(to, value, data);\n if (!success) {\n // bubble up revert reason\n revertWithData(returnData);\n }\n return returnData;\n }\n\n /// @dev Return data or revert.\n function delegateCall(address to, bytes memory data) internal returns (bytes memory) {\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returnData) = to.delegatecall(data);\n if (!success) {\n // bubble up revert reason\n revertWithData(returnData);\n }\n return returnData;\n }\n\n /// @dev Allocates memory for and retrieves return data from the previous external function call. The end of the\n /// allocated data may not be aligned to 32 bytes, which means the next free memory slot might fall somewhere\n /// between two 32-byte words. Therefore the memory address is aligned to the next 32-byte boundary to ensure\n /// efficient memory usage. The function also stores the size of the return data and copies the return data\n /// itself into the allocated memory.\n /// @return returnData the data returned by the last external function call.\n /// @notice The function ensures memory alignment by adding 63 (0x3f = 0x1f + 0x20) and clearing the last 5 bits,\n /// ensuring the memory is pushed to the nearest multiple of 32 bytes. This avoids unaligned memory access,\n /// which can lead to inefficiencies.\n function fetchReturnData() internal pure returns (bytes memory returnData) {\n // solhint-disable-next-line no-inline-assembly\n assembly (\"memory-safe\") {\n // allocate memory for the return data starting at the free memory pointer\n returnData := mload(0x40)\n // update the free memory pointer after adding the size of the return data and ensuring it is aligned to the\n // next 32-byte boundary\n mstore(0x40, add(returnData, and(add(returndatasize(), 0x3f), not(0x1f))))\n // store the size of the return data at the start of the allocated memory\n mstore(returnData, returndatasize())\n // copy the return data to the allocated memory space\n returndatacopy(add(returnData, 0x20), 0, returndatasize())\n }\n }\n}\n"},"src/msca/6900/shared/common/Structs.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\n/**\n * @dev Returned data from validateUserOp.\n * validateUserOp returns a uint256, with is created by `_packedValidationData` and parsed by `_parseValidationData`\n * @param validAfter - this UserOp is valid only after this timestamp.\n * @param validaUntil - this UserOp is valid only up to this timestamp.\n * @param authorizer - address(0) - the account validated the signature by itself.\n * address(1) - the account failed to validate the signature.\n * otherwise - this is an address of a signature aggregator that must be used to validate the\n * signature.\n */\nstruct ValidationData {\n uint48 validAfter;\n uint48 validUntil;\n address authorizer;\n}\n\nstruct AddressDLL {\n mapping(address => address) next;\n mapping(address => address) prev;\n uint256 count;\n}\n\nstruct Bytes4DLL {\n mapping(bytes4 => bytes4) next;\n mapping(bytes4 => bytes4) prev;\n uint256 count;\n}\n\nstruct Bytes32DLL {\n mapping(bytes32 => bytes32) next;\n mapping(bytes32 => bytes32) prev;\n uint256 count;\n}\n"},"src/msca/6900/shared/libs/ValidationDataLib.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {ValidationData} from \"../common/Structs.sol\";\n\nlibrary ValidationDataLib {\n error WrongTimeBounds();\n\n /**\n * @dev Intercept the time bounds `[validAfter, validUntil]` and the signature validation result,\n * prioritizing the invalid authorizer (`!=0 && !=1`), followed by prioritizing failure (`==1`),\n * and finally returning success (`==0`). Please note that both `authorizer(2)` and `authorizer(3)` are invalid,\n * and calling this function with `(2, 3)` ensures that only one invalid authorizer will be returned.\n * @notice address(0) is a successful validation, address(1) is a failed validation,\n * and address(2), address(3) and others are invalid authorizers (also failed).\n */\n function _intersectValidationData(ValidationData memory a, uint256 uintb)\n internal\n pure\n returns (ValidationData memory validationData)\n {\n ValidationData memory b = _unpackValidationData(uintb);\n if (a.validAfter > a.validUntil) {\n revert WrongTimeBounds();\n }\n if (b.validAfter > b.validUntil) {\n revert WrongTimeBounds();\n }\n // 0 is successful validation\n if (!_isValidAuthorizer(a.authorizer)) {\n validationData.authorizer = a.authorizer;\n } else if (!_isValidAuthorizer(b.authorizer)) {\n validationData.authorizer = b.authorizer;\n } else {\n if (a.authorizer == address(0)) {\n validationData.authorizer = b.authorizer;\n } else {\n validationData.authorizer = a.authorizer;\n }\n }\n if (a.validAfter > b.validAfter) {\n validationData.validAfter = a.validAfter;\n } else {\n validationData.validAfter = b.validAfter;\n }\n if (a.validUntil < b.validUntil) {\n validationData.validUntil = a.validUntil;\n } else {\n validationData.validUntil = b.validUntil;\n }\n // make sure the caller (e.g. entryPoint) reverts\n // set to address(1) if and only if the authorizer is address(0) (successful validation)\n // we don't want to set to address(1) if the authorizer is invalid such as address(2)\n if (validationData.validAfter >= validationData.validUntil && validationData.authorizer == address(0)) {\n validationData.authorizer = address(1);\n }\n return validationData;\n }\n\n /**\n * @dev Unpack into the deserialized packed format from validAfter | validUntil | authorizer.\n */\n function _unpackValidationData(uint256 validationDataInt)\n internal\n pure\n returns (ValidationData memory validationData)\n {\n address authorizer = address(uint160(validationDataInt));\n uint48 validUntil = uint48(validationDataInt >> 160);\n if (validUntil == 0) {\n validUntil = type(uint48).max;\n }\n uint48 validAfter = uint48(validationDataInt >> (48 + 160));\n return ValidationData(validAfter, validUntil, authorizer);\n }\n\n function _packValidationData(ValidationData memory data) internal pure returns (uint256) {\n return uint160(data.authorizer) | (uint256(data.validUntil) << 160) | (uint256(data.validAfter) << (160 + 48));\n }\n\n function _isValidAuthorizer(address authorizer) internal pure returns (bool) {\n return authorizer == address(0) || authorizer == address(1);\n }\n}\n"},"src/msca/6900/v0.7/common/Constants.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\n// magic value for runtime validation functions that always allow access\nbytes21 constant RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE = bytes21(uint168(1));\n\n// magic value for hooks that should always revert\nbytes21 constant PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE = bytes21(uint168(2));\n"},"src/msca/6900/v0.7/common/Structs.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\n// Standard executor\nstruct Call {\n // The target address for the account to call.\n address target;\n // The value to send with the call.\n uint256 value;\n // The calldata for the call.\n bytes data;\n}\n\nstruct FunctionReference {\n address plugin;\n uint8 functionId;\n}\n\n// Account loupe\n// @notice Config for an execution function, given a selector\nstruct ExecutionFunctionConfig {\n address plugin;\n FunctionReference userOpValidationFunction;\n FunctionReference runtimeValidationFunction;\n}\n\n/// @notice Pre and post hooks for a given selector\n/// @dev It's possible for one of either `preExecHook` or `postExecHook` to be empty\nstruct ExecutionHooks {\n FunctionReference preExecHook;\n FunctionReference postExecHook;\n}\n\n// internal data structure\nstruct Bytes21DLL {\n mapping(bytes21 => bytes21) next;\n mapping(bytes21 => bytes21) prev;\n uint256 count;\n}\n\nstruct RepeatableBytes21DLL {\n mapping(bytes21 => bytes21) next;\n mapping(bytes21 => bytes21) prev;\n mapping(bytes21 => uint256) counter;\n // unique items\n uint256 uniqueItems;\n // total items with repeatable ones\n uint256 totalItems;\n}\n\n// Represents a set of pre and post hooks. Used to store execution hooks.\nstruct HookGroup {\n RepeatableBytes21DLL preHooks;\n // key = preExecHook.pack()\n mapping(bytes21 => RepeatableBytes21DLL) preToPostHooks;\n RepeatableBytes21DLL postOnlyHooks;\n}\n\n// plugin's permission to call external (to the account and its plugins) contracts and addresses\n// through `executeFromPluginExternal`\nstruct PermittedExternalCall {\n bool addressPermitted;\n // either anySelector or selectors permitted\n bool anySelector;\n mapping(bytes4 => bool) selectors;\n}\n\nstruct PostExecHookToRun {\n bytes preExecHookReturnData;\n FunctionReference postExecHook;\n}\n\n// plugin detail stored in wallet storage\nstruct PluginDetail {\n // permitted to call any external contracts and selectors\n bool anyExternalAddressPermitted;\n // boolean to indicate if the plugin can spend native tokens, if any of the execution function can spend\n // native tokens, a plugin is considered to be able to spend native tokens of the accounts\n bool canSpendNativeToken;\n // tracks the count this plugin has been used as a dependency function\n uint256 dependentCounter;\n bytes32 manifestHash;\n Bytes21DLL dependencies;\n}\n\n// execution detail associated with selector\nstruct ExecutionDetail {\n address plugin; // plugin address that implements the execution function, for native functions, the value should be\n // address(0)\n FunctionReference userOpValidationFunction;\n RepeatableBytes21DLL preUserOpValidationHooks;\n FunctionReference runtimeValidationFunction;\n RepeatableBytes21DLL preRuntimeValidationHooks;\n HookGroup executionHooks;\n}\n"},"src/msca/6900/v0.7/interfaces/IPlugin.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {PluginManifest, PluginMetadata} from \"../common/PluginManifest.sol\";\nimport {UserOperation} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\n\n/**\n * @dev Implements https://eips.ethereum.org/EIPS/eip-6900. Plugins must implement this interface to support plugin\n * management and interactions with MSCAs.\n */\ninterface IPlugin {\n /// @notice Initialize plugin data for the modular account.\n /// @dev Called by the modular account during `installPlugin`.\n /// @param data Optional bytes array to be decoded and used by the plugin to setup initial plugin data for the\n /// modular account.\n function onInstall(bytes calldata data) external;\n\n /// @notice Clear plugin data for the modular account.\n /// @dev Called by the modular account during `uninstallPlugin`.\n /// @param data Optional bytes array to be decoded and used by the plugin to clear plugin data for the modular\n /// account.\n function onUninstall(bytes calldata data) external;\n\n /// @notice Run the pre user operation validation hook specified by the `functionId`.\n /// @dev Pre user operation validation hooks MUST NOT return an authorizer value other than 0 or 1.\n /// @param functionId An identifier that routes the call to different internal implementations, should there be more\n /// than one.\n /// @param userOp The user operation.\n /// @param userOpHash The user operation hash.\n /// @return Packed validation data for validAfter (6 bytes), validUntil (6 bytes), and authorizer (20 bytes).\n function preUserOpValidationHook(uint8 functionId, UserOperation calldata userOp, bytes32 userOpHash)\n external\n returns (uint256);\n\n /// @notice Run the user operation validationFunction specified by the `functionId`.\n /// @param functionId An identifier that routes the call to different internal implementations, should there be\n /// more than one.\n /// @param userOp The user operation.\n /// @param userOpHash The user operation hash.\n /// @return Packed validation data for validAfter (6 bytes), validUntil (6 bytes), and authorizer (20 bytes).\n function userOpValidationFunction(uint8 functionId, UserOperation calldata userOp, bytes32 userOpHash)\n external\n returns (uint256);\n\n /// @notice Run the pre runtime validation hook specified by the `functionId`.\n /// @dev To indicate the entire call should revert, the function MUST revert.\n /// @param functionId An identifier that routes the call to different internal implementations, should there be more\n /// than one.\n /// @param sender The caller address.\n /// @param value The call value.\n /// @param data The calldata sent.\n function preRuntimeValidationHook(uint8 functionId, address sender, uint256 value, bytes calldata data) external;\n\n /// @notice Run the runtime validationFunction specified by the `functionId`.\n /// @dev To indicate the entire call should revert, the function MUST revert.\n /// @param functionId An identifier that routes the call to different internal implementations, should there be\n /// more than one.\n /// @param sender The caller address.\n /// @param value The call value.\n /// @param data The calldata sent.\n function runtimeValidationFunction(uint8 functionId, address sender, uint256 value, bytes calldata data) external;\n\n /// @notice Run the pre execution hook specified by the `functionId`.\n /// @dev To indicate the entire call should revert, the function MUST revert.\n /// @param functionId An identifier that routes the call to different internal implementations, should there be more\n /// than one.\n /// @param sender The caller address.\n /// @param value The call value.\n /// @param data The calldata sent.\n /// @return context Context to pass to a post execution hook, if present. An empty bytes array MAY be returned.\n function preExecutionHook(uint8 functionId, address sender, uint256 value, bytes calldata data)\n external\n returns (bytes memory context);\n\n /// @notice Run the post execution hook specified by the `functionId`.\n /// @dev To indicate the entire call should revert, the function MUST revert.\n /// @param functionId An identifier that routes the call to different internal implementations, should there be more\n /// than one.\n /// @param preExecHookData The context returned by its associated pre execution hook.\n function postExecutionHook(uint8 functionId, bytes calldata preExecHookData) external;\n\n /// @notice Describe the contents and intended configuration of the plugin.\n /// @dev This manifest MUST stay constant over time.\n /// @return A manifest describing the contents and intended configuration of the plugin.\n function pluginManifest() external pure returns (PluginManifest memory);\n\n /// @notice Describe the metadata of the plugin.\n /// @dev This metadata MUST stay constant over time.\n /// @return A metadata struct describing the plugin.\n function pluginMetadata() external pure returns (PluginMetadata memory);\n}\n"},"src/msca/6900/v0.7/libs/FunctionReferenceLib.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {FunctionReference} from \"../common/Structs.sol\";\n\nlibrary FunctionReferenceLib {\n function unpack(bytes21 frBytes) internal pure returns (FunctionReference memory) {\n return FunctionReference(address(bytes20(frBytes)), uint8(bytes1(frBytes << 160)));\n }\n\n function pack(FunctionReference memory functionReference) internal pure returns (bytes21) {\n return (bytes21(bytes20(functionReference.plugin)) | bytes21(uint168(functionReference.functionId)));\n }\n}\n"},"src/msca/6900/v0.7/libs/RepeatableFunctionReferenceDLLLib.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {SENTINEL_BYTES21} from \"../../../../common/Constants.sol\";\nimport {InvalidFunctionReference, InvalidLimit, ItemDoesNotExist} from \"../../shared/common/Errors.sol\";\nimport {FunctionReference, RepeatableBytes21DLL} from \"../common/Structs.sol\";\nimport {FunctionReferenceLib} from \"./FunctionReferenceLib.sol\";\n\n/**\n * @dev Enumerable & ordered doubly linked list built using RepeatableBytes21DLL.\n * Item is expected to be have a counter that tracks repeated number.\n */\nlibrary RepeatableFunctionReferenceDLLLib {\n using FunctionReferenceLib for FunctionReference;\n using FunctionReferenceLib for bytes21;\n\n modifier validFunctionReference(FunctionReference memory fr) {\n if (fr.pack() <= SENTINEL_BYTES21) {\n revert InvalidFunctionReference();\n }\n _;\n }\n\n /**\n * @dev Check the counter of an item. O(1).\n * @return the counter\n */\n function getRepeatedCount(RepeatableBytes21DLL storage dll, FunctionReference memory fr)\n internal\n view\n returns (uint256)\n {\n bytes21 item = fr.pack();\n if (item == SENTINEL_BYTES21) {\n // sentinel should not considered as the value of the list\n return 0;\n }\n return dll.counter[item];\n }\n\n /**\n * @dev Get the total items of dll. O(1).\n */\n function getTotalItems(RepeatableBytes21DLL storage dll) internal view returns (uint256) {\n return dll.totalItems;\n }\n\n /**\n * @dev Get the unique items of dll. O(1).\n */\n function getUniqueItems(RepeatableBytes21DLL storage dll) internal view returns (uint256) {\n return dll.uniqueItems;\n }\n\n /**\n * @dev Add an new item. O(1).\n */\n function append(RepeatableBytes21DLL storage dll, FunctionReference memory fr)\n internal\n validFunctionReference(fr)\n returns (uint256)\n {\n bytes21 item = fr.pack();\n uint256 currentCount = getRepeatedCount(dll, fr);\n if (currentCount == 0) {\n bytes21 prev = getTailWithoutUnpack(dll);\n bytes21 next = SENTINEL_BYTES21;\n // prev.next = item\n dll.next[prev] = item;\n // item.next = next\n dll.next[item] = next;\n // next.prev = item\n dll.prev[next] = item;\n // item.prev = prev\n dll.prev[item] = prev;\n dll.uniqueItems++;\n }\n dll.counter[item]++;\n dll.totalItems++;\n return dll.counter[item];\n }\n\n /**\n * @dev Remove or decrease the counter of already existing item. Otherwise the function reverts. O(1).\n */\n function remove(RepeatableBytes21DLL storage dll, FunctionReference memory fr)\n internal\n validFunctionReference(fr)\n returns (uint256)\n {\n uint256 currentCount = getRepeatedCount(dll, fr);\n if (currentCount == 0) {\n revert ItemDoesNotExist();\n }\n bytes21 item = fr.pack();\n if (currentCount == 1) {\n // delete the item\n // item.prev.next = item.next\n dll.next[dll.prev[item]] = dll.next[item];\n // item.next.prev = item.prev\n dll.prev[dll.next[item]] = dll.prev[item];\n delete dll.next[item];\n delete dll.prev[item];\n delete dll.counter[item];\n dll.uniqueItems--;\n } else {\n dll.counter[item]--;\n }\n dll.totalItems--;\n return dll.counter[item];\n }\n\n /**\n * @dev Remove all copies of already existing items. O(1).\n */\n function removeAllRepeated(RepeatableBytes21DLL storage dll, FunctionReference memory fr)\n internal\n validFunctionReference(fr)\n returns (bool)\n {\n uint256 currentCount = getRepeatedCount(dll, fr);\n if (currentCount == 0) {\n revert ItemDoesNotExist();\n }\n bytes21 item = fr.pack();\n // item.prev.next = item.next\n dll.next[dll.prev[item]] = dll.next[item];\n // item.next.prev = item.prev\n dll.prev[dll.next[item]] = dll.prev[item];\n delete dll.next[item];\n delete dll.prev[item];\n delete dll.counter[item];\n dll.uniqueItems--;\n dll.totalItems -= currentCount;\n return true;\n }\n\n /**\n * @dev Return paginated results and next pointer without counter information. O(n).\n * In order to get counter information (which our current use case does not need), please call\n * getRepeatedCount.\n * @param startFR Starting item, inclusive, if start == bytes21(0), this method searches from the head.\n */\n function getPaginated(RepeatableBytes21DLL storage dll, FunctionReference memory startFR, uint256 limit)\n internal\n view\n returns (FunctionReference[] memory, FunctionReference memory)\n {\n if (limit == 0) {\n revert InvalidLimit();\n }\n bytes21 start = startFR.pack();\n FunctionReference[] memory results = new FunctionReference[](limit);\n bytes21 current = start;\n if (start == SENTINEL_BYTES21) {\n current = getHeadWithoutUnpack(dll);\n }\n uint256 count = 0;\n for (; count < limit && current > SENTINEL_BYTES21; ++count) {\n results[count] = current.unpack();\n current = dll.next[current];\n }\n // solhint-disable-next-line no-inline-assembly\n assembly (\"memory-safe\") {\n mstore(results, count)\n }\n return (results, current.unpack());\n }\n\n /**\n * @dev Return all the unique items without counter information. O(n).\n * In order to get counter information (which our current use case does not need), please call\n * getRepeatedCount.\n */\n function getAll(RepeatableBytes21DLL storage dll) internal view returns (FunctionReference[] memory results) {\n uint256 totalUniqueCount = getUniqueItems(dll);\n results = new FunctionReference[](totalUniqueCount);\n bytes21 current = getHeadWithoutUnpack(dll);\n uint256 count = 0;\n for (; count < totalUniqueCount && current > SENTINEL_BYTES21; ++count) {\n results[count] = current.unpack();\n current = dll.next[current];\n }\n return results;\n }\n\n function getHead(RepeatableBytes21DLL storage dll) internal view returns (FunctionReference memory) {\n return dll.next[SENTINEL_BYTES21].unpack();\n }\n\n function getTail(RepeatableBytes21DLL storage dll) internal view returns (FunctionReference memory) {\n return dll.prev[SENTINEL_BYTES21].unpack();\n }\n\n function getHeadWithoutUnpack(RepeatableBytes21DLL storage dll) private view returns (bytes21) {\n return dll.next[SENTINEL_BYTES21];\n }\n\n function getTailWithoutUnpack(RepeatableBytes21DLL storage dll) private view returns (bytes21) {\n return dll.prev[SENTINEL_BYTES21];\n }\n}\n"},"src/msca/6900/v0.7/libs/WalletStorageV1Lib.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {AddressDLL} from \"../../shared/common/Structs.sol\";\nimport {ExecutionDetail, PermittedExternalCall, PluginDetail} from \"../common/Structs.sol\";\n\n/// @dev The same storage will be used for v1.x.y of MSCAs.\nlibrary WalletStorageV1Lib {\n // @notice When we initially calculated the storage slot, EIP-7201 was still under active discussion,\n // so we didn’t fully adopt the storage alignment proposed by the EIP, which reduces gas costs\n // for subsequent operations, as a single cold storage access warms all 256 slots within the group.\n // To avoid introducing breaking changes and the complexity of migration, we chose not to make changes midway.\n // For v2 accounts, which will feature a different storage layout, we will adopt EIP-7201.\n // keccak256(abi.encode(uint256(keccak256(abi.encode(\"circle.msca.v1.storage\"))) - 1))\n bytes32 internal constant WALLET_STORAGE_SLOT = 0xc6a0cc20c824c4eecc4b0fbb7fb297d07492a7bd12c83d4fa4d27b4249f9bfc8;\n\n struct Layout {\n // installed plugin addresses for quick query\n AddressDLL installedPlugins;\n // installed plugin details such as manifest, dependencies\n mapping(address => PluginDetail) pluginDetails;\n // permissions for executeFromPlugin into another plugin\n // callingPluginAddress => callingExecutionSelector => permittedOrNot\n mapping(address => mapping(bytes4 => bool)) permittedPluginCalls;\n // permissions for executeFromPluginExternal into external contract\n // callingPluginAddress => targetContractAddress => permission\n mapping(address => mapping(address => PermittedExternalCall)) permittedExternalCalls;\n // list of ERC-165 interfaceIds to add to account to support introspection checks\n // interfaceId => counter\n mapping(bytes4 => uint256) supportedInterfaces;\n // find plugin or native function execution detail by selector\n mapping(bytes4 => ExecutionDetail) executionDetails;\n /// indicates that the contract has been initialized\n uint8 initialized;\n /// indicates that the contract is in the process of being initialized\n bool initializing;\n // optional fields\n address owner;\n }\n\n /**\n * @dev Function to read structured wallet storage.\n */\n function getLayout() internal pure returns (Layout storage walletStorage) {\n // solhint-disable-next-line no-inline-assembly\n assembly (\"memory-safe\") {\n walletStorage.slot := WALLET_STORAGE_SLOT\n }\n }\n}\n"},"src/msca/6900/v0.7/account/BaseMSCA.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {\n EMPTY_FUNCTION_REFERENCE,\n SENTINEL_BYTES21,\n WALLET_AUTHOR,\n WALLET_VERSION_1\n} from \"../../../../common/Constants.sol\";\n\nimport {UnauthorizedCaller} from \"../../../../common/Errors.sol\";\nimport {ExecutionUtils} from \"../../../../utils/ExecutionUtils.sol\";\nimport {\n InvalidAuthorizer,\n InvalidExecutionFunction,\n InvalidValidationFunctionId,\n NotFoundSelector\n} from \"../../shared/common/Errors.sol\";\nimport {AddressDLL, ValidationData} from \"../../shared/common/Structs.sol\";\nimport {AddressDLLLib} from \"../../shared/libs/AddressDLLLib.sol\";\nimport {ValidationDataLib} from \"../../shared/libs/ValidationDataLib.sol\";\nimport {\n PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE,\n RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n} from \"../common/Constants.sol\";\nimport {\n Call,\n ExecutionDetail,\n ExecutionFunctionConfig,\n ExecutionHooks,\n FunctionReference,\n HookGroup,\n PostExecHookToRun,\n RepeatableBytes21DLL\n} from \"../common/Structs.sol\";\nimport {IAccountLoupe} from \"../interfaces/IAccountLoupe.sol\";\nimport {IPlugin} from \"../interfaces/IPlugin.sol\";\nimport {IPluginExecutor} from \"../interfaces/IPluginExecutor.sol\";\nimport {IPluginManager} from \"../interfaces/IPluginManager.sol\";\nimport {IStandardExecutor} from \"../interfaces/IStandardExecutor.sol\";\nimport {ExecutionHookLib} from \"../libs/ExecutionHookLib.sol\";\nimport {FunctionReferenceLib} from \"../libs/FunctionReferenceLib.sol\";\nimport {RepeatableFunctionReferenceDLLLib} from \"../libs/RepeatableFunctionReferenceDLLLib.sol\";\n\nimport {SelectorRegistryLib} from \"../libs/SelectorRegistryLib.sol\";\nimport {WalletStorageV1Lib} from \"../libs/WalletStorageV1Lib.sol\";\nimport {PluginExecutor} from \"../managers/PluginExecutor.sol\";\nimport {PluginManager} from \"../managers/PluginManager.sol\";\nimport {StandardExecutor} from \"../managers/StandardExecutor.sol\";\n\nimport {WalletStorageInitializable} from \"./WalletStorageInitializable.sol\";\nimport {IEntryPoint} from \"@account-abstraction/contracts/interfaces/IEntryPoint.sol\";\nimport {UserOperation} from \"@account-abstraction/contracts/interfaces/UserOperation.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\n/**\n * @dev Base MSCA implementation with **authentication**.\n * This contract provides the basic logic for implementing the MSCA interfaces;\n * specific account implementation should inherit this contract.\n */\nabstract contract BaseMSCA is\n WalletStorageInitializable,\n IPluginManager,\n IAccountLoupe,\n IStandardExecutor,\n IPluginExecutor,\n IERC165\n{\n using RepeatableFunctionReferenceDLLLib for RepeatableBytes21DLL;\n using FunctionReferenceLib for bytes21;\n using FunctionReferenceLib for FunctionReference;\n using ExecutionHookLib for HookGroup;\n using ExecutionHookLib for PostExecHookToRun[];\n using ExecutionUtils for address;\n using PluginExecutor for bytes;\n using StandardExecutor for address;\n using StandardExecutor for Call[];\n using AddressDLLLib for AddressDLL;\n using ValidationDataLib for ValidationData;\n using SelectorRegistryLib for bytes4;\n\n string public constant AUTHOR = WALLET_AUTHOR;\n string public constant VERSION = WALLET_VERSION_1;\n // 4337 related immutable storage\n IEntryPoint public immutable ENTRY_POINT;\n PluginManager public immutable PLUGIN_MANAGER;\n\n error NotNativeFunctionSelector(bytes4 selector);\n error InvalidHookFunctionId(uint8 functionId);\n error PreRuntimeValidationHookFailed(address plugin, uint8 functionId, bytes revertReason);\n error RuntimeValidationFailed(address plugin, uint8 functionId, bytes revertReason);\n\n /**\n * @dev Wraps execution of a native function (as opposed to a function added by plugins) with runtime validations\n * (not from EP)\n * and hooks. Used by execute, executeBatch, installPlugin, uninstallPlugin, upgradeTo and upgradeToAndCall.\n * If the call is from entry point, then validateUserOp will run.\n * https://eips.ethereum.org/assets/eip-6900/Modular_Account_Call_Flow.svg\n */\n modifier validateNativeFunction() {\n PostExecHookToRun[] memory postExecHooks = _processPreExecHooks();\n _;\n postExecHooks._processPostExecHooks();\n }\n\n /**\n * @dev This function allows entry point or SA itself to execute certain actions.\n * If the caller is not authorized, the function will revert with an error message.\n */\n modifier onlyFromEntryPointOrSelf() {\n _checkAccessRuleFromEPOrAcctItself();\n _;\n }\n\n constructor(IEntryPoint _newEntryPoint, PluginManager _newPluginManager) {\n ENTRY_POINT = _newEntryPoint;\n PLUGIN_MANAGER = _newPluginManager;\n // lock the implementation contract so it can only be called from proxies\n _disableWalletStorageInitializers();\n }\n\n receive() external payable {}\n\n /// @notice Manage fallback calls made to the plugins.\n /// @dev Route calls to execution functions based on incoming msg.sig\n /// If there's no plugin associated with this function selector, revert\n // solhint-disable-next-line no-complex-fallback\n fallback(bytes calldata) external payable returns (bytes memory result) {\n if (msg.data.length < 4) {\n revert NotFoundSelector();\n }\n // run runtime validation before we load the executionDetail because validation may update account state\n if (msg.sender != address(ENTRY_POINT)) {\n // ENTRY_POINT should go through validateUserOp flow which calls userOpValidationFunction\n _processPreRuntimeHooksAndValidation(msg.sig);\n }\n // load the executionDetail before we run the preExecHooks because they may modify the plugins\n ExecutionDetail storage executionDetail = WalletStorageV1Lib.getLayout().executionDetails[msg.sig];\n address executionFunctionPlugin = executionDetail.plugin;\n // valid plugin address should not be 0\n if (executionFunctionPlugin == address(0)) {\n revert InvalidExecutionFunction(msg.sig);\n }\n PostExecHookToRun[] memory postExecHooks = executionDetail.executionHooks._processPreExecHooks(msg.data);\n result = ExecutionUtils.callWithReturnDataOrRevert(executionFunctionPlugin, msg.value, msg.data);\n postExecHooks._processPostExecHooks();\n return result;\n }\n\n /**\n * @dev Return the ENTRY_POINT used by this account.\n * subclass should return the current ENTRY_POINT used by this account.\n */\n function getEntryPoint() external view returns (IEntryPoint) {\n return ENTRY_POINT;\n }\n\n /**\n * @dev Validate user's signature and nonce.\n * subclass doesn't need to override this method. Instead, it should override the specific internal validation\n * methods.\n */\n function validateUserOp(UserOperation calldata userOp, bytes32 userOpHash, uint256 missingAccountFunds)\n external\n virtual\n returns (uint256 validationData)\n {\n if (msg.sender != address(ENTRY_POINT)) {\n revert UnauthorizedCaller();\n }\n validationData = _authenticateAndAuthorizeUserOp(userOp, userOpHash);\n if (missingAccountFunds != 0) {\n (bool success,) = payable(msg.sender).call{value: missingAccountFunds, gas: type(uint256).max}(\"\");\n (success);\n // ignore failure (its EntryPoint's job to verify, not account.)\n }\n }\n\n /// @notice ERC165 introspection https://eips.ethereum.org/EIPS/eip-165\n /// @dev returns true for `IERC165.interfaceId` and false for `0xFFFFFFFF`\n /// @param interfaceId interface id to check against\n /// @return bool support for specific interface\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n if (interfaceId == 0xffffffff) {\n return false;\n }\n if (interfaceId == type(IERC165).interfaceId) {\n return true;\n }\n return WalletStorageV1Lib.getLayout().supportedInterfaces[interfaceId] > 0;\n }\n\n /**\n * @dev Return the account nonce.\n * This method returns the next sequential nonce.\n * For a nonce of a specific key, use `entrypoint.getNonce(account, key)`\n */\n function getNonce() public view virtual returns (uint256) {\n return ENTRY_POINT.getNonce(address(this), 0);\n }\n\n function installPlugin(\n address plugin,\n bytes32 manifestHash,\n bytes memory pluginInstallData,\n FunctionReference[] memory dependencies\n ) external override validateNativeFunction {\n bytes memory data = abi.encodeCall(\n PluginManager.install, (plugin, manifestHash, pluginInstallData, dependencies, address(this))\n );\n address(PLUGIN_MANAGER).delegateCall(data);\n emit PluginInstalled(plugin, manifestHash, dependencies);\n }\n\n function uninstallPlugin(address plugin, bytes memory config, bytes memory pluginUninstallData)\n external\n override\n validateNativeFunction\n {\n bytes memory data = abi.encodeCall(PluginManager.uninstall, (plugin, config, pluginUninstallData));\n address(PLUGIN_MANAGER).delegateCall(data);\n emit PluginUninstalled(plugin, true);\n }\n\n function execute(address target, uint256 value, bytes calldata data)\n external\n payable\n override\n validateNativeFunction\n returns (bytes memory returnData)\n {\n return target.execute(value, data);\n }\n\n function executeBatch(Call[] calldata calls)\n external\n payable\n override\n validateNativeFunction\n returns (bytes[] memory returnData)\n {\n return calls.executeBatch();\n }\n\n function executeFromPlugin(bytes calldata data) external payable override returns (bytes memory) {\n return data.executeFromPlugin();\n }\n\n function executeFromPluginExternal(address target, uint256 value, bytes calldata data)\n external\n payable\n override\n returns (bytes memory)\n {\n return data.executeFromPluginToExternal(target, value);\n }\n\n /// @notice Gets the validation functions and plugin address for a selector\n /// @dev If the selector is a native function, the plugin address will be the address of the account\n /// @param selector The selector to get the configuration for\n /// @return executionFunctionConfig The configuration for this selector\n function getExecutionFunctionConfig(bytes4 selector)\n external\n view\n returns (ExecutionFunctionConfig memory executionFunctionConfig)\n {\n WalletStorageV1Lib.Layout storage walletStorage = WalletStorageV1Lib.getLayout();\n if (selector._isNativeFunctionSelector()) {\n executionFunctionConfig.plugin = address(this);\n } else {\n executionFunctionConfig.plugin = walletStorage.executionDetails[selector].plugin;\n }\n executionFunctionConfig.userOpValidationFunction =\n walletStorage.executionDetails[selector].userOpValidationFunction;\n executionFunctionConfig.runtimeValidationFunction =\n walletStorage.executionDetails[selector].runtimeValidationFunction;\n return executionFunctionConfig;\n }\n\n /// @notice Gets the pre and post execution hooks for a selector\n /// @param selector The selector to get the hooks for\n /// @return executionHooks The pre and post execution hooks for this selector\n function getExecutionHooks(bytes4 selector) external view returns (ExecutionHooks[] memory executionHooks) {\n return WalletStorageV1Lib.getLayout().executionDetails[selector].executionHooks._getExecutionHooks();\n }\n\n /// @notice Gets the pre user op and runtime validation hooks associated with a selector\n /// @param selector The selector to get the hooks for\n /// @return preUserOpValidationHooks The pre user op validation hooks for this selector\n /// @return preRuntimeValidationHooks The pre runtime validation hooks for this selector\n function getPreValidationHooks(bytes4 selector)\n external\n view\n returns (\n FunctionReference[] memory preUserOpValidationHooks,\n FunctionReference[] memory preRuntimeValidationHooks\n )\n {\n preUserOpValidationHooks =\n WalletStorageV1Lib.getLayout().executionDetails[selector].preUserOpValidationHooks.getAll();\n preRuntimeValidationHooks =\n WalletStorageV1Lib.getLayout().executionDetails[selector].preRuntimeValidationHooks.getAll();\n return (preUserOpValidationHooks, preRuntimeValidationHooks);\n }\n\n /// @notice Gets an array of all installed plugins\n /// @return pluginAddresses The addresses of all installed plugins\n function getInstalledPlugins() external view returns (address[] memory pluginAddresses) {\n return WalletStorageV1Lib.getLayout().installedPlugins.getAll();\n }\n\n /**\n * Check current account deposit in the ENTRY_POINT.\n */\n function getDeposit() public view returns (uint256) {\n return ENTRY_POINT.balanceOf(address(this));\n }\n\n /**\n * Deposit more funds for this account in the ENTRY_POINT.\n */\n function addDeposit() public payable {\n ENTRY_POINT.depositTo{value: msg.value}(address(this));\n }\n\n /**\n * Withdraw value from the account's deposit.\n * @param withdrawAddress target to send to\n * @param amount to withdraw\n */\n function withdrawDepositTo(address payable withdrawAddress, uint256 amount) public onlyFromEntryPointOrSelf {\n ENTRY_POINT.withdrawTo(withdrawAddress, amount);\n }\n\n /**\n * @dev Authenticate and authorize this userOp. OnlyFromEntryPoint is applied in the caller.\n * @param userOp validate the userOp.signature field\n * @param userOpHash convenient field: the hash of the request, to check the signature against\n * (also hashes the entrypoint and chain id)\n * @return validationData signature and time-range of this operation\n * <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,\n * otherwise, an address of an \"authorizer\" contract.\n * <6-byte> validUntil - last timestamp this operation is valid. 0 for \"indefinite\"\n * <6-byte> validAfter - first timestamp this operation is valid\n * If the account doesn't use time-range, it is enough to return SIG_VALIDATION_FAILED value (1) for signature\n * failure.\n * Note that the validation code cannot use block.timestamp (or block.number) directly due to the storage rule.\n */\n function _authenticateAndAuthorizeUserOp(UserOperation calldata userOp, bytes32 userOpHash)\n internal\n virtual\n returns (uint256 validationData)\n {\n // onlyFromEntryPoint is applied in the caller\n // if there is no function defined for the selector, or if userOp.callData.length < 4, then execution MUST\n // revert\n if (userOp.callData.length < 4) {\n revert NotFoundSelector();\n }\n bytes4 selector = bytes4(userOp.callData[0:4]);\n if (selector == bytes4(0)) {\n revert NotFoundSelector();\n }\n ExecutionDetail storage executionDetail = WalletStorageV1Lib.getLayout().executionDetails[selector];\n FunctionReference memory validationFunction = executionDetail.userOpValidationFunction;\n bytes21 packedValidationFunction = validationFunction.pack();\n if (\n packedValidationFunction == EMPTY_FUNCTION_REFERENCE\n || packedValidationFunction == RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n || packedValidationFunction == PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n ) {\n revert InvalidValidationFunctionId(validationFunction.functionId);\n }\n // pre hook\n ValidationData memory unpackedValidationData =\n _processPreUserOpValidationHooks(executionDetail, userOp, userOpHash);\n IPlugin userOpValidatorPlugin = IPlugin(validationFunction.plugin);\n // execute the validation function with the user operation and its hash as parameters using the call opcode\n uint256 currentValidationData = userOpValidatorPlugin.userOpValidationFunction(\n executionDetail.userOpValidationFunction.functionId, userOp, userOpHash\n );\n // intercept with validation function call\n unpackedValidationData = unpackedValidationData._intersectValidationData(currentValidationData);\n if (unpackedValidationData.authorizer != address(0) && unpackedValidationData.authorizer != address(1)) {\n // only revert on unexpected values\n revert InvalidAuthorizer();\n }\n validationData = unpackedValidationData._packValidationData();\n }\n\n /**\n * @dev Default validation logic is from installed plugins. However, you can override this validation logic in MSCA\n * implementations. For instance, semi MSCA such as single owner semi MSCA may want to honor the validation\n * from native owner.\n */\n function _processPreRuntimeHooksAndValidation(bytes4 selector) internal virtual {\n FunctionReference memory validationFunction =\n WalletStorageV1Lib.getLayout().executionDetails[selector].runtimeValidationFunction;\n bytes21 packedValidationFunction = validationFunction.pack();\n if (\n packedValidationFunction == EMPTY_FUNCTION_REFERENCE\n || packedValidationFunction == PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n ) {\n revert InvalidValidationFunctionId(validationFunction.functionId);\n }\n RepeatableBytes21DLL storage preRuntimeValidationHooksDLL =\n WalletStorageV1Lib.getLayout().executionDetails[selector].preRuntimeValidationHooks;\n uint256 totalUniqueHookCount = preRuntimeValidationHooksDLL.getUniqueItems();\n FunctionReference memory startHook = EMPTY_FUNCTION_REFERENCE.unpack();\n FunctionReference[] memory preRuntimeValidationHooks;\n FunctionReference memory nextHook;\n for (uint256 i = 0; i < totalUniqueHookCount; ++i) {\n (preRuntimeValidationHooks, nextHook) = preRuntimeValidationHooksDLL.getPaginated(startHook, 10);\n for (uint256 j = 0; j < preRuntimeValidationHooks.length; ++j) {\n // revert on EMPTY_FUNCTION_REFERENCE, RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE,\n // PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n // if any revert, the outer call MUST revert\n bytes21 packedPreRuntimeValidationHook = preRuntimeValidationHooks[j].pack();\n if (\n packedPreRuntimeValidationHook == EMPTY_FUNCTION_REFERENCE\n || packedPreRuntimeValidationHook == RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n || packedPreRuntimeValidationHook == PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n ) {\n revert InvalidValidationFunctionId(preRuntimeValidationHooks[j].functionId);\n }\n IPlugin preRuntimeValidationHookPlugin = IPlugin(preRuntimeValidationHooks[j].plugin);\n // solhint-disable no-empty-blocks\n try preRuntimeValidationHookPlugin.preRuntimeValidationHook(\n preRuntimeValidationHooks[j].functionId, msg.sender, msg.value, msg.data\n ) {} catch (bytes memory revertReason) {\n revert PreRuntimeValidationHookFailed(\n preRuntimeValidationHooks[j].plugin, preRuntimeValidationHooks[j].functionId, revertReason\n );\n }\n // solhint-enable no-empty-blocks\n }\n if (nextHook.pack() == SENTINEL_BYTES21) {\n break;\n }\n startHook = nextHook;\n }\n // call runtimeValidationFunction if it's not always allowed\n if (packedValidationFunction != RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE) {\n // solhint-disable no-empty-blocks\n try IPlugin(validationFunction.plugin).runtimeValidationFunction(\n validationFunction.functionId, msg.sender, msg.value, msg.data\n ) {} catch (bytes memory revertReason) {\n revert RuntimeValidationFailed(validationFunction.plugin, validationFunction.functionId, revertReason);\n }\n // solhint-enable no-empty-blocks\n }\n }\n\n /// @dev Also runs runtime hooks and validation if msg.sender is not from entry point.\n function _processPreExecHooks() internal returns (PostExecHookToRun[] memory) {\n if (!msg.sig._isNativeFunctionSelector()) {\n revert NotNativeFunctionSelector(msg.sig);\n }\n if (msg.sender != address(ENTRY_POINT)) {\n // ENTRY_POINT should go through validateUserOp flow which calls userOpValidationFunction\n _processPreRuntimeHooksAndValidation(msg.sig);\n }\n return WalletStorageV1Lib.getLayout().executionDetails[msg.sig].executionHooks._processPreExecHooks(msg.data);\n }\n\n function _processPreUserOpValidationHooks(\n ExecutionDetail storage executionDetail,\n UserOperation calldata userOp,\n bytes32 userOpHash\n ) internal virtual returns (ValidationData memory unpackedValidationData) {\n unpackedValidationData = ValidationData(0, 0xFFFFFFFFFFFF, address(0));\n // if the function selector has associated pre user operation validation hooks, then those hooks MUST be run\n // sequentially\n uint256 totalUniqueHookCount = executionDetail.preUserOpValidationHooks.getUniqueItems();\n FunctionReference memory startHook = EMPTY_FUNCTION_REFERENCE.unpack();\n FunctionReference[] memory preUserOpValidatorHooks;\n FunctionReference memory nextHook;\n uint256 currentValidationData;\n for (uint256 i = 0; i < totalUniqueHookCount; ++i) {\n (preUserOpValidatorHooks, nextHook) = executionDetail.preUserOpValidationHooks.getPaginated(startHook, 10);\n for (uint256 j = 0; j < preUserOpValidatorHooks.length; ++j) {\n bytes21 packedUserOpValidatorHook = preUserOpValidatorHooks[j].pack();\n // if any revert, the outer call MUST revert\n if (\n packedUserOpValidatorHook == EMPTY_FUNCTION_REFERENCE\n || packedUserOpValidatorHook == RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n || packedUserOpValidatorHook == PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n ) {\n revert InvalidHookFunctionId(preUserOpValidatorHooks[j].functionId);\n }\n IPlugin preUserOpValidationHookPlugin = IPlugin(preUserOpValidatorHooks[j].plugin);\n currentValidationData = preUserOpValidationHookPlugin.preUserOpValidationHook(\n preUserOpValidatorHooks[j].functionId, userOp, userOpHash\n );\n unpackedValidationData = unpackedValidationData._intersectValidationData(currentValidationData);\n // if any return an authorizer value other than 0 or 1, execution MUST revert\n if (unpackedValidationData.authorizer != address(0) && unpackedValidationData.authorizer != address(1))\n {\n revert InvalidAuthorizer();\n }\n }\n if (nextHook.pack() == SENTINEL_BYTES21) {\n break;\n }\n startHook = nextHook;\n }\n return unpackedValidationData;\n }\n\n function _checkAccessRuleFromEPOrAcctItself() internal view {\n if (msg.sender != address(ENTRY_POINT) && msg.sender != address(this)) {\n revert UnauthorizedCaller();\n }\n }\n}\n"},"lib/account-abstraction/contracts/interfaces/UserOperation.sol":{"content":"// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\n/* solhint-disable no-inline-assembly */\n\nimport {calldataKeccak} from \"../core/Helpers.sol\";\n\n/**\n * User Operation struct\n * @param sender the sender account of this request.\n * @param nonce unique value the sender uses to verify it is not a replay.\n * @param initCode if set, the account contract will be created by this constructor/\n * @param callData the method call to execute on this account.\n * @param callGasLimit the gas limit passed to the callData method call.\n * @param verificationGasLimit gas used for validateUserOp and validatePaymasterUserOp.\n * @param preVerificationGas gas not calculated by the handleOps method, but added to the gas paid. Covers batch overhead.\n * @param maxFeePerGas same as EIP-1559 gas parameter.\n * @param maxPriorityFeePerGas same as EIP-1559 gas parameter.\n * @param paymasterAndData if set, this field holds the paymaster address and paymaster-specific data. the paymaster will pay for the transaction instead of the sender.\n * @param signature sender-verified signature over the entire request, the EntryPoint address and the chain ID.\n */\n struct UserOperation {\n\n address sender;\n uint256 nonce;\n bytes initCode;\n bytes callData;\n uint256 callGasLimit;\n uint256 verificationGasLimit;\n uint256 preVerificationGas;\n uint256 maxFeePerGas;\n uint256 maxPriorityFeePerGas;\n bytes paymasterAndData;\n bytes signature;\n }\n\n/**\n * Utility functions helpful when working with UserOperation structs.\n */\nlibrary UserOperationLib {\n\n function getSender(UserOperation calldata userOp) internal pure returns (address) {\n address data;\n //read sender from userOp, which is first userOp member (saves 800 gas...)\n assembly {data := calldataload(userOp)}\n return address(uint160(data));\n }\n\n //relayer/block builder might submit the TX with higher priorityFee, but the user should not\n // pay above what he signed for.\n function gasPrice(UserOperation calldata userOp) internal view returns (uint256) {\n unchecked {\n uint256 maxFeePerGas = userOp.maxFeePerGas;\n uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;\n if (maxFeePerGas == maxPriorityFeePerGas) {\n //legacy mode (for networks that don't support basefee opcode)\n return maxFeePerGas;\n }\n return min(maxFeePerGas, maxPriorityFeePerGas + block.basefee);\n }\n }\n\n function pack(UserOperation calldata userOp) internal pure returns (bytes memory ret) {\n address sender = getSender(userOp);\n uint256 nonce = userOp.nonce;\n bytes32 hashInitCode = calldataKeccak(userOp.initCode);\n bytes32 hashCallData = calldataKeccak(userOp.callData);\n uint256 callGasLimit = userOp.callGasLimit;\n uint256 verificationGasLimit = userOp.verificationGasLimit;\n uint256 preVerificationGas = userOp.preVerificationGas;\n uint256 maxFeePerGas = userOp.maxFeePerGas;\n uint256 maxPriorityFeePerGas = userOp.maxPriorityFeePerGas;\n bytes32 hashPaymasterAndData = calldataKeccak(userOp.paymasterAndData);\n\n return abi.encode(\n sender, nonce,\n hashInitCode, hashCallData,\n callGasLimit, verificationGasLimit, preVerificationGas,\n maxFeePerGas, maxPriorityFeePerGas,\n hashPaymasterAndData\n );\n }\n\n function hash(UserOperation calldata userOp) internal pure returns (bytes32) {\n return keccak256(pack(userOp));\n }\n\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n}\n"},"node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../interfaces/draft-IERC1822Upgradeable.sol\";\nimport \"../ERC1967/ERC1967UpgradeUpgradeable.sol\";\nimport {Initializable} from \"./Initializable.sol\";\n\n/**\n * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an\n * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.\n *\n * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is\n * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing\n * `UUPSUpgradeable` with a custom implementation of upgrades.\n *\n * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.\n *\n * _Available since v4.1._\n */\nabstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {\n /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment\n address private immutable __self = address(this);\n\n /**\n * @dev Check that the execution is being performed through a delegatecall call and that the execution context is\n * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case\n * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a\n * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to\n * fail.\n */\n modifier onlyProxy() {\n require(address(this) != __self, \"Function must be called through delegatecall\");\n require(_getImplementation() == __self, \"Function must be called through active proxy\");\n _;\n }\n\n /**\n * @dev Check that the execution is not being performed through a delegate call. This allows a function to be\n * callable on the implementing contract but not through proxies.\n */\n modifier notDelegated() {\n require(address(this) == __self, \"UUPSUpgradeable: must not be called through delegatecall\");\n _;\n }\n\n function __UUPSUpgradeable_init() internal onlyInitializing {\n }\n\n function __UUPSUpgradeable_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the\n * implementation. It is used to validate the implementation's compatibility when performing an upgrade.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.\n */\n function proxiableUUID() external view virtual override notDelegated returns (bytes32) {\n return _IMPLEMENTATION_SLOT;\n }\n\n /**\n * @dev Upgrade the implementation of the proxy to `newImplementation`.\n *\n * Calls {_authorizeUpgrade}.\n *\n * Emits an {Upgraded} event.\n *\n * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n */\n function upgradeTo(address newImplementation) public virtual onlyProxy {\n _authorizeUpgrade(newImplementation);\n _upgradeToAndCallUUPS(newImplementation, new bytes(0), false);\n }\n\n /**\n * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call\n * encoded in `data`.\n *\n * Calls {_authorizeUpgrade}.\n *\n * Emits an {Upgraded} event.\n *\n * @custom:oz-upgrades-unsafe-allow-reachable delegatecall\n */\n function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {\n _authorizeUpgrade(newImplementation);\n _upgradeToAndCallUUPS(newImplementation, data, true);\n }\n\n /**\n * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by\n * {upgradeTo} and {upgradeToAndCall}.\n *\n * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.\n *\n * ```solidity\n * function _authorizeUpgrade(address) internal override onlyOwner {}\n * ```\n */\n function _authorizeUpgrade(address newImplementation) internal virtual;\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"},"node_modules/@openzeppelin/contracts/interfaces/IERC1271.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC1271 standard signature validation method for\n * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].\n *\n * _Available since v4.1._\n */\ninterface IERC1271 {\n /**\n * @dev Should return whether the signature provided is valid for the provided data\n * @param hash Hash of the data to be signed\n * @param signature Signature byte array associated with _data\n */\n function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);\n}\n"},"node_modules/@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC1155/IERC1155Receiver.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165.sol\";\n\n/**\n * @dev _Available since v3.1._\n */\ninterface IERC1155Receiver is IERC165 {\n /**\n * @dev Handles the receipt of a single ERC1155 token type. This function is\n * called at the end of a `safeTransferFrom` after the balance has been updated.\n *\n * NOTE: To accept the transfer, this must return\n * `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))`\n * (i.e. 0xf23a6e61, or its own function selector).\n *\n * @param operator The address which initiated the transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param id The ID of the token being transferred\n * @param value The amount of tokens being transferred\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155Received(address,address,uint256,uint256,bytes)\"))` if transfer is allowed\n */\n function onERC1155Received(\n address operator,\n address from,\n uint256 id,\n uint256 value,\n bytes calldata data\n ) external returns (bytes4);\n\n /**\n * @dev Handles the receipt of a multiple ERC1155 token types. This function\n * is called at the end of a `safeBatchTransferFrom` after the balances have\n * been updated.\n *\n * NOTE: To accept the transfer(s), this must return\n * `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))`\n * (i.e. 0xbc197c81, or its own function selector).\n *\n * @param operator The address which initiated the batch transfer (i.e. msg.sender)\n * @param from The address which previously owned the token\n * @param ids An array containing ids of each token being transferred (order and length must match values array)\n * @param values An array containing amounts of each token being transferred (order and length must match ids array)\n * @param data Additional data with no specified format\n * @return `bytes4(keccak256(\"onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)\"))` if transfer is allowed\n */\n function onERC1155BatchReceived(\n address operator,\n address from,\n uint256[] calldata ids,\n uint256[] calldata values,\n bytes calldata data\n ) external returns (bytes4);\n}\n"},"node_modules/@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title ERC721 token receiver interface\n * @dev Interface for any contract that wants to support safeTransfers\n * from ERC721 asset contracts.\n */\ninterface IERC721Receiver {\n /**\n * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}\n * by `operator` from `from`, this function is called.\n *\n * It must return its Solidity selector to confirm the token transfer.\n * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.\n *\n * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.\n */\n function onERC721Received(\n address operator,\n address from,\n uint256 tokenId,\n bytes calldata data\n ) external returns (bytes4);\n}\n"},"node_modules/@openzeppelin/contracts/utils/cryptography/ECDSA.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Strings.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n enum RecoverError {\n NoError,\n InvalidSignature,\n InvalidSignatureLength,\n InvalidSignatureS,\n InvalidSignatureV // Deprecated in v4.8\n }\n\n function _throwError(RecoverError error) private pure {\n if (error == RecoverError.NoError) {\n return; // no error: do nothing\n } else if (error == RecoverError.InvalidSignature) {\n revert(\"ECDSA: invalid signature\");\n } else if (error == RecoverError.InvalidSignatureLength) {\n revert(\"ECDSA: invalid signature length\");\n } else if (error == RecoverError.InvalidSignatureS) {\n revert(\"ECDSA: invalid signature 's' value\");\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature` or error string. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n *\n * Documentation for signature generation:\n * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n if (signature.length == 65) {\n bytes32 r;\n bytes32 s;\n uint8 v;\n // ecrecover takes the signature parameters, and the only way to get them\n // currently is to use assembly.\n /// @solidity memory-safe-assembly\n assembly {\n r := mload(add(signature, 0x20))\n s := mload(add(signature, 0x40))\n v := byte(0, mload(add(signature, 0x60)))\n }\n return tryRecover(hash, v, r, s);\n } else {\n return (address(0), RecoverError.InvalidSignatureLength);\n }\n }\n\n /**\n * @dev Returns the address that signed a hashed message (`hash`) with\n * `signature`. This address can then be used for verification purposes.\n *\n * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n * this function rejects them by requiring the `s` value to be in the lower\n * half order, and the `v` value to be either 27 or 28.\n *\n * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n * verification to be secure: it is possible to craft signatures that\n * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n * this is by receiving a hash of the original message (which may otherwise\n * be too long), and then calling {toEthSignedMessageHash} on it.\n */\n function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, signature);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n *\n * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {\n bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n uint8 v = uint8((uint256(vs) >> 255) + 27);\n return tryRecover(hash, v, r, s);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n *\n * _Available since v4.2._\n */\n function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n * `r` and `s` signature fields separately.\n *\n * _Available since v4.3._\n */\n function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {\n // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n //\n // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n // these malleable signatures as well.\n if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n return (address(0), RecoverError.InvalidSignatureS);\n }\n\n // If the signature is valid (and not malleable), return the signer address\n address signer = ecrecover(hash, v, r, s);\n if (signer == address(0)) {\n return (address(0), RecoverError.InvalidSignature);\n }\n\n return (signer, RecoverError.NoError);\n }\n\n /**\n * @dev Overload of {ECDSA-recover} that receives the `v`,\n * `r` and `s` signature fields separately.\n */\n function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n _throwError(error);\n return recovered;\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {\n // 32 is the length in bytes of hash,\n // enforced by the type signature above\n /// @solidity memory-safe-assembly\n assembly {\n mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\")\n mstore(0x1c, hash)\n message := keccak256(0x00, 0x3c)\n }\n }\n\n /**\n * @dev Returns an Ethereum Signed Message, created from `s`. This\n * produces hash corresponding to the one signed with the\n * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n * JSON-RPC method as part of EIP-191.\n *\n * See {recover}.\n */\n function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\n }\n\n /**\n * @dev Returns an Ethereum Signed Typed Data, created from a\n * `domainSeparator` and a `structHash`. This produces hash corresponding\n * to the one signed with the\n * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n * JSON-RPC method as part of EIP-712.\n *\n * See {recover}.\n */\n function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {\n /// @solidity memory-safe-assembly\n assembly {\n let ptr := mload(0x40)\n mstore(ptr, \"\\x19\\x01\")\n mstore(add(ptr, 0x02), domainSeparator)\n mstore(add(ptr, 0x22), structHash)\n data := keccak256(ptr, 0x42)\n }\n }\n\n /**\n * @dev Returns an Ethereum Signed Data with intended validator, created from a\n * `validator` and `data` according to the version 0 of EIP-191.\n *\n * See {recover}.\n */\n function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(\"\\x19\\x00\", validator, data));\n }\n}\n"},"src/erc712/BaseERC712CompliantAccount.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {MessageHashUtils} from \"../libs/MessageHashUtils.sol\";\n\nabstract contract BaseERC712CompliantAccount {\n // keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\")\n bytes32 private constant _DOMAIN_SEPARATOR_TYPEHASH =\n keccak256(\"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)\");\n\n /// @notice Wraps a replay safe hash in an EIP-712 envelope to prevent cross-account replay attacks.\n /// domainSeparator = hashStruct(eip712Domain).\n /// eip712Domain = (string name,string version,uint256 chainId,address verifyingContract)\n /// hashStruct(s) = keccak256(typeHash ‖ encodeData(s)) where typeHash = keccak256(encodeType(typeOf(s)))\n /// @param hash Message that should be hashed.\n /// @return Replay safe message hash.\n function getReplaySafeMessageHash(bytes32 hash) public view returns (bytes32) {\n return MessageHashUtils.toTypedDataHash({\n domainSeparator: keccak256(\n abi.encode(\n _DOMAIN_SEPARATOR_TYPEHASH, _getAccountName(), _getAccountVersion(), block.chainid, address(this)\n )\n ),\n structHash: keccak256(abi.encode(_getAccountTypeHash(), hash))\n });\n }\n\n /// @dev Returns the account message typehash.\n function _getAccountTypeHash() internal pure virtual returns (bytes32);\n\n /// @dev Returns the account name.\n function _getAccountName() internal pure virtual returns (bytes32);\n\n /// @dev Returns the account version.\n function _getAccountVersion() internal pure virtual returns (bytes32);\n}\n"},"node_modules/@openzeppelin/contracts/utils/cryptography/SignatureChecker.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/SignatureChecker.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./ECDSA.sol\";\nimport \"../../interfaces/IERC1271.sol\";\n\n/**\n * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA\n * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like\n * Argent and Gnosis Safe.\n *\n * _Available since v4.1._\n */\nlibrary SignatureChecker {\n /**\n * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the\n * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`.\n *\n * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus\n * change through time. It could return true at block N and false at block N+1 (or the opposite).\n */\n function isValidSignatureNow(address signer, bytes32 hash, bytes memory signature) internal view returns (bool) {\n (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature);\n return\n (error == ECDSA.RecoverError.NoError && recovered == signer) ||\n isValidERC1271SignatureNow(signer, hash, signature);\n }\n\n /**\n * @dev Checks if a signature is valid for a given signer and data hash. The signature is validated\n * against the signer smart contract using ERC1271.\n *\n * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus\n * change through time. It could return true at block N and false at block N+1 (or the opposite).\n */\n function isValidERC1271SignatureNow(\n address signer,\n bytes32 hash,\n bytes memory signature\n ) internal view returns (bool) {\n (bool success, bytes memory result) = signer.staticcall(\n abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature)\n );\n return (success &&\n result.length >= 32 &&\n abi.decode(result, (bytes32)) == bytes32(IERC1271.isValidSignature.selector));\n }\n}\n"},"src/msca/6900/shared/libs/AddressDLLLib.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {InvalidLimit, ItemAlreadyExists, ItemDoesNotExist} from \"../common/Errors.sol\";\nimport {AddressDLL} from \"../common/Structs.sol\";\n\n/**\n * @dev Enumerable & ordered doubly linked list built using mapping(address => address).\n * Item is expected to be unique.\n */\nlibrary AddressDLLLib {\n address internal constant SENTINEL_ADDRESS = address(0x0);\n uint160 internal constant SENTINEL_ADDRESS_UINT = 0;\n\n event AddressAdded(address indexed addr);\n event AddressRemoved(address indexed addr);\n\n error InvalidAddress();\n\n modifier validAddress(address addr) {\n if (uint160(addr) <= SENTINEL_ADDRESS_UINT) {\n revert InvalidAddress();\n }\n _;\n }\n\n /**\n * @dev Check if an item exists or not. O(1).\n */\n function contains(AddressDLL storage dll, address item) internal view returns (bool) {\n if (item == SENTINEL_ADDRESS) {\n // SENTINEL_ADDRESS is not a valid item\n return false;\n }\n return getHead(dll) == item || dll.next[item] != SENTINEL_ADDRESS || dll.prev[item] != SENTINEL_ADDRESS;\n }\n\n /**\n * @dev Get the count of dll. O(1).\n */\n function size(AddressDLL storage dll) internal view returns (uint256) {\n return dll.count;\n }\n\n /**\n * @dev Add an new item which did not exist before. Otherwise the function reverts. O(1).\n */\n function append(AddressDLL storage dll, address item) internal validAddress(item) returns (bool) {\n if (contains(dll, item)) {\n revert ItemAlreadyExists();\n }\n address prev = getTail(dll);\n address next = SENTINEL_ADDRESS;\n // prev.next = item\n dll.next[prev] = item;\n // item.next = next\n dll.next[item] = next;\n // next.prev = item\n dll.prev[next] = item;\n // item.prev = prev\n dll.prev[item] = prev;\n dll.count++;\n emit AddressAdded(item);\n return true;\n }\n\n /**\n * @dev Remove an already existing item. Otherwise the function reverts. O(1).\n */\n function remove(AddressDLL storage dll, address item) internal validAddress(item) returns (bool) {\n if (!contains(dll, item)) {\n revert ItemDoesNotExist();\n }\n // item.prev.next = item.next\n dll.next[dll.prev[item]] = dll.next[item];\n // item.next.prev = item.prev\n dll.prev[dll.next[item]] = dll.prev[item];\n delete dll.next[item];\n delete dll.prev[item];\n dll.count--;\n emit AddressRemoved(item);\n return true;\n }\n\n /**\n * @dev Return paginated addresses and next pointer address. O(n).\n * @param start Starting address, inclusive, if start == address(0x0), this method searches from the head.\n */\n function getPaginated(AddressDLL storage dll, address start, uint256 limit)\n internal\n view\n returns (address[] memory, address)\n {\n if (limit == 0) {\n revert InvalidLimit();\n }\n address[] memory results = new address[](limit);\n address current = start;\n if (start == SENTINEL_ADDRESS) {\n current = getHead(dll);\n }\n uint256 count = 0;\n for (; count < limit && uint160(current) > SENTINEL_ADDRESS_UINT; ++count) {\n results[count] = current;\n current = dll.next[current];\n }\n\n // solhint-disable-next-line no-inline-assembly\n assembly (\"memory-safe\") {\n mstore(results, count)\n }\n return (results, current);\n }\n\n /**\n * @dev Return all the data. O(n).\n */\n function getAll(AddressDLL storage dll) internal view returns (address[] memory results) {\n uint256 totalCount = size(dll);\n results = new address[](totalCount);\n address current = getHead(dll);\n uint256 count = 0;\n for (; count < totalCount && uint160(current) > SENTINEL_ADDRESS_UINT; ++count) {\n results[count] = current;\n current = dll.next[current];\n }\n return results;\n }\n\n function getHead(AddressDLL storage dll) internal view returns (address) {\n return dll.next[SENTINEL_ADDRESS];\n }\n\n function getTail(AddressDLL storage dll) internal view returns (address) {\n return dll.prev[SENTINEL_ADDRESS];\n }\n}\n"},"src/msca/6900/v0.7/common/PluginManifest.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\n// Plugin Manifest\nenum ManifestAssociatedFunctionType {\n // Function is not defined.\n NONE,\n // Function belongs to this plugin.\n SELF,\n // Function belongs to an external plugin provided as a dependency during plugin installation.\n DEPENDENCY,\n // Resolves to a magic value to always bypass runtime validation for a given function.\n // This is only assignable on runtime validation functions. If it were to be used on a user op validation function,\n // it would risk burning gas from the account. When used as a hook in any hook location, it is equivalent to not\n // setting a hook and is therefore disallowed.\n RUNTIME_VALIDATION_ALWAYS_ALLOW,\n // Resolves to a magic value to always fail in a hook for a given function.\n // This is only assignable to pre hooks (pre validation and pre execution). It should not be used on\n // validation functions themselves, because this is equivalent to leaving the validation functions unset.\n // It should not be used in post-exec hooks, because if it is known to always revert, that should happen\n // as early as possible to save gas.\n PRE_HOOK_ALWAYS_DENY\n}\n\n/// @dev For functions of type `ManifestAssociatedFunctionType.DEPENDENCY`, the MSCA MUST find the plugin address\n/// of the function at `dependencies[dependencyIndex]` during the call to `installPlugin(config)`.\nstruct ManifestFunction {\n ManifestAssociatedFunctionType functionType;\n uint8 functionId;\n uint256 dependencyIndex;\n}\n\nstruct ManifestAssociatedFunction {\n bytes4 executionSelector;\n ManifestFunction associatedFunction;\n}\n\nstruct ManifestExecutionHook {\n bytes4 selector;\n ManifestFunction preExecHook;\n ManifestFunction postExecHook;\n}\n\nstruct ManifestExternalCallPermission {\n address externalAddress;\n bool permitAnySelector;\n bytes4[] selectors;\n}\n\nstruct SelectorPermission {\n bytes4 functionSelector;\n string permissionDescription;\n}\n\n/// @dev A struct holding fields to describe the plugin in a purely view context. Intended for front end clients.\nstruct PluginMetadata {\n // A human-readable name of the plugin.\n string name;\n // The version of the plugin, following the semantic versioning scheme.\n string version;\n // The author field SHOULD be a username representing the identity of the user or organization\n // that created this plugin.\n string author;\n // String descriptions of the relative sensitivity of specific functions. The selectors MUST be selectors for\n // functions implemented by this plugin.\n SelectorPermission[] permissionDescriptors;\n}\n\n/// @dev A struct describing how the plugin should be installed on a modular account.\nstruct PluginManifest {\n // List of ERC-165 interface IDs to add to account to support introspection checks. This MUST NOT include\n // IPlugin's interface ID.\n bytes4[] interfaceIds;\n // If this plugin depends on other plugins' validation functions, the interface IDs of those plugins MUST be\n // provided here, with its position in the array matching the `dependencyIndex` members of `ManifestFunction`\n bytes4[] dependencyInterfaceIds;\n // Execution functions defined in this plugin to be installed on the MSCA.\n bytes4[] executionFunctions;\n // Plugin execution functions already installed on the MSCA that this plugin will be able to call.\n bytes4[] permittedExecutionSelectors;\n // Boolean to indicate whether the plugin can call any external address.\n bool permitAnyExternalAddress;\n // Boolean to indicate whether the plugin needs access to spend native tokens of the account. If false, the\n // plugin MUST still be able to spend up to the balance that it sends to the account in the same call.\n bool canSpendNativeToken;\n // More granular control\n ManifestExternalCallPermission[] permittedExternalCalls;\n ManifestAssociatedFunction[] userOpValidationFunctions;\n ManifestAssociatedFunction[] runtimeValidationFunctions;\n ManifestAssociatedFunction[] preUserOpValidationHooks;\n ManifestAssociatedFunction[] preRuntimeValidationHooks;\n // for executionFunctions\n ManifestExecutionHook[] executionHooks;\n}\n"},"src/msca/6900/v0.7/libs/FunctionReferenceDLLLib.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {SENTINEL_BYTES21} from \"../../../../common/Constants.sol\";\nimport {\n InvalidFunctionReference, InvalidLimit, ItemAlreadyExists, ItemDoesNotExist\n} from \"../../shared/common/Errors.sol\";\nimport {Bytes21DLL, FunctionReference} from \"../common/Structs.sol\";\nimport {FunctionReferenceLib} from \"./FunctionReferenceLib.sol\";\n\n/**\n * @dev Enumerable & ordered doubly linked list built using mapping(bytes21 => bytes21) for function reference.\n * Item is expected to be unique.\n */\nlibrary FunctionReferenceDLLLib {\n using FunctionReferenceLib for FunctionReference;\n using FunctionReferenceLib for bytes21;\n\n modifier validFunctionReference(FunctionReference memory fr) {\n if (fr.pack() <= SENTINEL_BYTES21) {\n revert InvalidFunctionReference();\n }\n _;\n }\n\n /**\n * @dev Check if an item exists or not. O(1).\n */\n function contains(Bytes21DLL storage dll, FunctionReference memory fr) internal view returns (bool) {\n return contains(dll, fr.pack());\n }\n\n function contains(Bytes21DLL storage dll, bytes21 item) internal view returns (bool) {\n if (item == SENTINEL_BYTES21) {\n return false;\n }\n return getHeadWithoutUnpack(dll) == item || dll.next[item] != SENTINEL_BYTES21\n || dll.prev[item] != SENTINEL_BYTES21;\n }\n\n /**\n * @dev Get the count of dll. O(1).\n */\n function size(Bytes21DLL storage dll) internal view returns (uint256) {\n return dll.count;\n }\n\n /**\n * @dev Add an new item which did not exist before. Otherwise the function reverts. O(1).\n */\n function append(Bytes21DLL storage dll, FunctionReference memory fr)\n internal\n validFunctionReference(fr)\n returns (bool)\n {\n bytes21 item = fr.pack();\n if (contains(dll, item)) {\n revert ItemAlreadyExists();\n }\n bytes21 prev = getTailWithoutUnpack(dll);\n bytes21 next = SENTINEL_BYTES21;\n // prev.next = item\n dll.next[prev] = item;\n // item.next = next\n dll.next[item] = next;\n // next.prev = item\n dll.prev[next] = item;\n // item.prev = prev\n dll.prev[item] = prev;\n dll.count++;\n return true;\n }\n\n /**\n * @dev Remove an already existing item. Otherwise the function reverts. O(1).\n */\n function remove(Bytes21DLL storage dll, FunctionReference memory fr)\n internal\n validFunctionReference(fr)\n returns (bool)\n {\n bytes21 item = fr.pack();\n if (!contains(dll, item)) {\n revert ItemDoesNotExist();\n }\n // item.prev.next = item.next\n dll.next[dll.prev[item]] = dll.next[item];\n // item.next.prev = item.prev\n dll.prev[dll.next[item]] = dll.prev[item];\n delete dll.next[item];\n delete dll.prev[item];\n dll.count--;\n return true;\n }\n\n /**\n * @dev Return paginated bytes21s and next pointer bytes21. O(n).\n * @param startFR Starting bytes21, inclusive, if start == bytes21(0), this method searches from the head.\n */\n function getPaginated(Bytes21DLL storage dll, FunctionReference memory startFR, uint256 limit)\n internal\n view\n returns (FunctionReference[] memory, FunctionReference memory)\n {\n if (limit == 0) {\n revert InvalidLimit();\n }\n bytes21 start = startFR.pack();\n FunctionReference[] memory results = new FunctionReference[](limit);\n bytes21 current = start;\n if (start == SENTINEL_BYTES21) {\n current = getHeadWithoutUnpack(dll);\n }\n uint256 count = 0;\n for (; count < limit && current > SENTINEL_BYTES21; ++count) {\n results[count] = current.unpack();\n current = dll.next[current];\n }\n // solhint-disable-next-line no-inline-assembly\n assembly (\"memory-safe\") {\n mstore(results, count)\n }\n return (results, current.unpack());\n }\n\n /**\n * @dev Return all the data. O(n).\n */\n function getAll(Bytes21DLL storage dll) internal view returns (FunctionReference[] memory results) {\n uint256 totalCount = size(dll);\n results = new FunctionReference[](totalCount);\n bytes21 current = getHeadWithoutUnpack(dll);\n uint256 count = 0;\n for (; count < totalCount && current > SENTINEL_BYTES21; ++count) {\n results[count] = current.unpack();\n current = dll.next[current];\n }\n return results;\n }\n\n function getHead(Bytes21DLL storage dll) internal view returns (FunctionReference memory) {\n return dll.next[SENTINEL_BYTES21].unpack();\n }\n\n function getTail(Bytes21DLL storage dll) internal view returns (FunctionReference memory) {\n return dll.prev[SENTINEL_BYTES21].unpack();\n }\n\n function getHeadWithoutUnpack(Bytes21DLL storage dll) private view returns (bytes21) {\n return dll.next[SENTINEL_BYTES21];\n }\n\n function getTailWithoutUnpack(Bytes21DLL storage dll) private view returns (bytes21) {\n return dll.prev[SENTINEL_BYTES21];\n }\n}\n"},"src/msca/6900/v0.7/libs/SelectorRegistryLib.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {IAccountLoupe} from \"../interfaces/IAccountLoupe.sol\";\n\nimport {IPlugin} from \"../interfaces/IPlugin.sol\";\nimport {IPluginExecutor} from \"../interfaces/IPluginExecutor.sol\";\nimport {IPluginManager} from \"../interfaces/IPluginManager.sol\";\nimport {IStandardExecutor} from \"../interfaces/IStandardExecutor.sol\";\n\nimport {IAccount} from \"@account-abstraction/contracts/interfaces/IAccount.sol\";\nimport {IAggregator} from \"@account-abstraction/contracts/interfaces/IAggregator.sol\";\nimport {IPaymaster} from \"@account-abstraction/contracts/interfaces/IPaymaster.sol\";\nimport {UUPSUpgradeable} from \"@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol\";\n\nimport {IERC777Recipient} from \"@openzeppelin/contracts/interfaces/IERC777Recipient.sol\";\nimport {IERC1155Receiver} from \"@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol\";\nimport {IERC721Receiver} from \"@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol\";\nimport {IERC165} from \"@openzeppelin/contracts/utils/introspection/IERC165.sol\";\n\nlibrary SelectorRegistryLib {\n bytes4 internal constant INITIALIZE_UPGRADABLE_MSCA =\n bytes4(keccak256(\"initializeUpgradableMSCA(address[],bytes32[],bytes[])\"));\n bytes4 internal constant INITIALIZE_SINGLE_OWNER_MSCA = bytes4(keccak256(\"initializeSingleOwnerMSCA(address)\"));\n bytes4 internal constant TRANSFER_NATIVE_OWNERSHIP = bytes4(keccak256(\"transferNativeOwnership(address)\"));\n bytes4 internal constant RENOUNCE_NATIVE_OWNERSHIP = bytes4(keccak256(\"renounceNativeOwnership()\"));\n bytes4 internal constant GET_NATIVE_OWNER = bytes4(keccak256(\"getNativeOwner()\"));\n bytes4 internal constant GET_ENTRYPOINT = bytes4(keccak256(\"getEntryPoint()\"));\n bytes4 internal constant GET_NONCE = bytes4(keccak256(\"getNonce()\"));\n\n /**\n * @dev Check if the selector is for native function.\n * @param selector the function selector.\n */\n function _isNativeFunctionSelector(bytes4 selector) internal pure returns (bool) {\n return selector == IStandardExecutor.execute.selector || selector == IStandardExecutor.executeBatch.selector\n || selector == IPluginManager.installPlugin.selector || selector == IPluginManager.uninstallPlugin.selector\n || selector == UUPSUpgradeable.upgradeTo.selector || selector == UUPSUpgradeable.upgradeToAndCall.selector\n || selector == UUPSUpgradeable.proxiableUUID.selector\n // check against IERC165 methods\n || selector == IERC165.supportsInterface.selector\n // check against IPluginExecutor methods\n || selector == IPluginExecutor.executeFromPlugin.selector\n || selector == IPluginExecutor.executeFromPluginExternal.selector\n // check against IAccountLoupe methods\n || selector == IAccountLoupe.getExecutionFunctionConfig.selector\n || selector == IAccountLoupe.getExecutionHooks.selector\n || selector == IAccountLoupe.getPreValidationHooks.selector\n || selector == IAccountLoupe.getInstalledPlugins.selector || selector == IAccount.validateUserOp.selector\n || selector == GET_ENTRYPOINT || selector == GET_NONCE || selector == INITIALIZE_UPGRADABLE_MSCA\n || selector == INITIALIZE_SINGLE_OWNER_MSCA || selector == TRANSFER_NATIVE_OWNERSHIP\n || selector == RENOUNCE_NATIVE_OWNERSHIP || selector == GET_NATIVE_OWNER\n || selector == IERC1155Receiver.onERC1155Received.selector\n || selector == IERC1155Receiver.onERC1155BatchReceived.selector\n || selector == IERC721Receiver.onERC721Received.selector || selector == IERC777Recipient.tokensReceived.selector;\n }\n\n function _isErc4337FunctionSelector(bytes4 selector) internal pure returns (bool) {\n return selector == IAggregator.validateSignatures.selector\n || selector == IAggregator.validateUserOpSignature.selector\n || selector == IAggregator.aggregateSignatures.selector\n || selector == IPaymaster.validatePaymasterUserOp.selector || selector == IPaymaster.postOp.selector;\n }\n\n function _isIPluginFunctionSelector(bytes4 selector) internal pure returns (bool) {\n return selector == IPlugin.onInstall.selector || selector == IPlugin.onUninstall.selector\n || selector == IPlugin.preUserOpValidationHook.selector || selector == IPlugin.userOpValidationFunction.selector\n || selector == IPlugin.preRuntimeValidationHook.selector\n || selector == IPlugin.runtimeValidationFunction.selector || selector == IPlugin.preExecutionHook.selector\n || selector == IPlugin.postExecutionHook.selector || selector == IPlugin.pluginManifest.selector\n || selector == IPlugin.pluginMetadata.selector;\n }\n}\n"},"node_modules/@openzeppelin/contracts/utils/introspection/ERC165Checker.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/introspection/ERC165Checker.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165.sol\";\n\n/**\n * @dev Library used to query support of an interface declared via {IERC165}.\n *\n * Note that these functions return the actual result of the query: they do not\n * `revert` if an interface is not supported. It is up to the caller to decide\n * what to do in these cases.\n */\nlibrary ERC165Checker {\n // As per the EIP-165 spec, no interface should ever match 0xffffffff\n bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;\n\n /**\n * @dev Returns true if `account` supports the {IERC165} interface.\n */\n function supportsERC165(address account) internal view returns (bool) {\n // Any contract that implements ERC165 must explicitly indicate support of\n // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid\n return\n supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) &&\n !supportsERC165InterfaceUnchecked(account, _INTERFACE_ID_INVALID);\n }\n\n /**\n * @dev Returns true if `account` supports the interface defined by\n * `interfaceId`. Support for {IERC165} itself is queried automatically.\n *\n * See {IERC165-supportsInterface}.\n */\n function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {\n // query support of both ERC165 as per the spec and support of _interfaceId\n return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId);\n }\n\n /**\n * @dev Returns a boolean array where each value corresponds to the\n * interfaces passed in and whether they're supported or not. This allows\n * you to batch check interfaces for a contract where your expectation\n * is that some interfaces may not be supported.\n *\n * See {IERC165-supportsInterface}.\n *\n * _Available since v3.4._\n */\n function getSupportedInterfaces(\n address account,\n bytes4[] memory interfaceIds\n ) internal view returns (bool[] memory) {\n // an array of booleans corresponding to interfaceIds and whether they're supported or not\n bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);\n\n // query support of ERC165 itself\n if (supportsERC165(account)) {\n // query support of each interface in interfaceIds\n for (uint256 i = 0; i < interfaceIds.length; i++) {\n interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]);\n }\n }\n\n return interfaceIdsSupported;\n }\n\n /**\n * @dev Returns true if `account` supports all the interfaces defined in\n * `interfaceIds`. Support for {IERC165} itself is queried automatically.\n *\n * Batch-querying can lead to gas savings by skipping repeated checks for\n * {IERC165} support.\n *\n * See {IERC165-supportsInterface}.\n */\n function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {\n // query support of ERC165 itself\n if (!supportsERC165(account)) {\n return false;\n }\n\n // query support of each interface in interfaceIds\n for (uint256 i = 0; i < interfaceIds.length; i++) {\n if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) {\n return false;\n }\n }\n\n // all interfaces supported\n return true;\n }\n\n /**\n * @notice Query if a contract implements an interface, does not check ERC165 support\n * @param account The address of the contract to query for support of an interface\n * @param interfaceId The interface identifier, as specified in ERC-165\n * @return true if the contract at account indicates support of the interface with\n * identifier interfaceId, false otherwise\n * @dev Assumes that account contains a contract that supports ERC165, otherwise\n * the behavior of this method is undefined. This precondition can be checked\n * with {supportsERC165}.\n *\n * Some precompiled contracts will falsely indicate support for a given interface, so caution\n * should be exercised when using this function.\n *\n * Interface identification is specified in ERC-165.\n */\n function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) {\n // prepare call\n bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);\n\n // perform static call\n bool success;\n uint256 returnSize;\n uint256 returnValue;\n assembly {\n success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20)\n returnSize := returndatasize()\n returnValue := mload(0x00)\n }\n\n return success && returnSize >= 0x20 && returnValue > 0;\n }\n}\n"},"lib/account-abstraction/contracts/interfaces/IStakeManager.sol":{"content":"// SPDX-License-Identifier: GPL-3.0-only\npragma solidity ^0.8.12;\n\n/**\n * manage deposits and stakes.\n * deposit is just a balance used to pay for UserOperations (either by a paymaster or an account)\n * stake is value locked for at least \"unstakeDelay\" by the staked entity.\n */\ninterface IStakeManager {\n\n event Deposited(\n address indexed account,\n uint256 totalDeposit\n );\n\n event Withdrawn(\n address indexed account,\n address withdrawAddress,\n uint256 amount\n );\n\n /// Emitted when stake or unstake delay are modified\n event StakeLocked(\n address indexed account,\n uint256 totalStaked,\n uint256 unstakeDelaySec\n );\n\n /// Emitted once a stake is scheduled for withdrawal\n event StakeUnlocked(\n address indexed account,\n uint256 withdrawTime\n );\n\n event StakeWithdrawn(\n address indexed account,\n address withdrawAddress,\n uint256 amount\n );\n\n /**\n * @param deposit the entity's deposit\n * @param staked true if this entity is staked.\n * @param stake actual amount of ether staked for this entity.\n * @param unstakeDelaySec minimum delay to withdraw the stake.\n * @param withdrawTime - first block timestamp where 'withdrawStake' will be callable, or zero if already locked\n * @dev sizes were chosen so that (deposit,staked, stake) fit into one cell (used during handleOps)\n * and the rest fit into a 2nd cell.\n * 112 bit allows for 10^15 eth\n * 48 bit for full timestamp\n * 32 bit allows 150 years for unstake delay\n */\n struct DepositInfo {\n uint112 deposit;\n bool staked;\n uint112 stake;\n uint32 unstakeDelaySec;\n uint48 withdrawTime;\n }\n\n //API struct used by getStakeInfo and simulateValidation\n struct StakeInfo {\n uint256 stake;\n uint256 unstakeDelaySec;\n }\n\n /// @return info - full deposit information of given account\n function getDepositInfo(address account) external view returns (DepositInfo memory info);\n\n /// @return the deposit (for gas payment) of the account\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * add to the deposit of the given account\n */\n function depositTo(address account) external payable;\n\n /**\n * add to the account's stake - amount and delay\n * any pending unstake is first cancelled.\n * @param _unstakeDelaySec the new lock duration before the deposit can be withdrawn.\n */\n function addStake(uint32 _unstakeDelaySec) external payable;\n\n /**\n * attempt to unlock the stake.\n * the value can be withdrawn (using withdrawStake) after the unstake delay.\n */\n function unlockStake() external;\n\n /**\n * withdraw from the (unlocked) stake.\n * must first call unlockStake and wait for the unstakeDelay to pass\n * @param withdrawAddress the address to send withdrawn value.\n */\n function withdrawStake(address payable withdrawAddress) external;\n\n /**\n * withdraw from the deposit.\n * @param withdrawAddress the address to send withdrawn value.\n * @param withdrawAmount the amount to withdraw.\n */\n function withdrawTo(address payable withdrawAddress, uint256 withdrawAmount) external;\n}\n"},"lib/account-abstraction/contracts/interfaces/IAggregator.sol":{"content":"// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\nimport \"./UserOperation.sol\";\n\n/**\n * Aggregated Signatures validator.\n */\ninterface IAggregator {\n\n /**\n * validate aggregated signature.\n * revert if the aggregated signature does not match the given list of operations.\n */\n function validateSignatures(UserOperation[] calldata userOps, bytes calldata signature) external view;\n\n /**\n * validate signature of a single userOp\n * This method is should be called by bundler after EntryPoint.simulateValidation() returns (reverts) with ValidationResultWithAggregation\n * First it validates the signature over the userOp. Then it returns data to be used when creating the handleOps.\n * @param userOp the userOperation received from the user.\n * @return sigForUserOp the value to put into the signature field of the userOp when calling handleOps.\n * (usually empty, unless account and aggregator support some kind of \"multisig\"\n */\n function validateUserOpSignature(UserOperation calldata userOp)\n external view returns (bytes memory sigForUserOp);\n\n /**\n * aggregate multiple signatures into a single value.\n * This method is called off-chain to calculate the signature to pass with handleOps()\n * bundler MAY use optimized custom code perform this aggregation\n * @param userOps array of UserOperations to collect the signatures from.\n * @return aggregatedSignature the aggregated signature\n */\n function aggregateSignatures(UserOperation[] calldata userOps) external view returns (bytes memory aggregatedSignature);\n}\n"},"lib/account-abstraction/contracts/interfaces/INonceManager.sol":{"content":"// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\ninterface INonceManager {\n\n /**\n * Return the next nonce for this sender.\n * Within a given key, the nonce values are sequenced (starting with zero, and incremented by one on each userop)\n * But UserOp with different keys can come with arbitrary order.\n *\n * @param sender the account address\n * @param key the high 192 bit of the nonce\n * @return nonce a full nonce to pass for next UserOp with this sender.\n */\n function getNonce(address sender, uint192 key)\n external view returns (uint256 nonce);\n\n /**\n * Manually increment the nonce of the sender.\n * This method is exposed just for completeness..\n * Account does NOT need to call it, neither during validation, nor elsewhere,\n * as the EntryPoint will update the nonce regardless.\n * Possible use-case is call it with various keys to \"initialize\" their nonces to one, so that future\n * UserOperations will not pay extra for the first transaction with a given key.\n */\n function incrementNonce(uint192 key) external;\n}\n"},"node_modules/@openzeppelin/contracts/proxy/Proxy.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (proxy/Proxy.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n *\n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n *\n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal virtual {\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 {\n revert(0, returndatasize())\n }\n default {\n return(0, returndatasize())\n }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overridden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal view virtual returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n *\n * This function does not return to its internal call site, it will return directly to the external caller.\n */\n function _fallback() internal virtual {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive() external payable virtual {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n *\n * If overridden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {}\n}\n"},"node_modules/@openzeppelin/contracts/proxy/ERC1967/ERC1967Upgrade.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeacon.sol\";\nimport \"../../interfaces/IERC1967.sol\";\nimport \"../../interfaces/draft-IERC1822.sol\";\nimport \"../../utils/Address.sol\";\nimport \"../../utils/StorageSlot.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n */\nabstract contract ERC1967Upgrade is IERC1967 {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(Address.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlot.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(Address.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n Address.isContract(IBeacon(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);\n }\n }\n}\n"},"node_modules/@openzeppelin/contracts/interfaces/IERC777Recipient.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (interfaces/IERC777Recipient.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../token/ERC777/IERC777Recipient.sol\";\n"},"node_modules/@openzeppelin/contracts/utils/introspection/IERC165.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165 {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"},"src/msca/6900/v0.7/interfaces/IAccountLoupe.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {ExecutionFunctionConfig, ExecutionHooks, FunctionReference} from \"../common/Structs.sol\";\n\n/**\n * @dev Implements https://eips.ethereum.org/EIPS/eip-6900. MSCAs may implement this interface to support visibility in\n * plugin configurations on-chain.\n */\ninterface IAccountLoupe {\n /// @notice Get the validation functions and plugin address for a selector.\n /// @dev If the selector is a native function, the plugin address will be the address of the account.\n /// @param selector The selector to get the configuration for.\n /// @return The configuration for this selector.\n function getExecutionFunctionConfig(bytes4 selector) external view returns (ExecutionFunctionConfig memory);\n\n /// @notice Get the pre and post execution hooks for a selector.\n /// @param selector The selector to get the hooks for.\n /// @return The pre and post execution hooks for this selector.\n function getExecutionHooks(bytes4 selector) external view returns (ExecutionHooks[] memory);\n\n /// @notice Get the pre user op and runtime validation hooks associated with a selector.\n /// @param selector The selector to get the hooks for.\n /// @return preUserOpValidationHooks The pre user op validation hooks for this selector.\n /// @return preRuntimeValidationHooks The pre runtime validation hooks for this selector.\n function getPreValidationHooks(bytes4 selector)\n external\n view\n returns (FunctionReference[] memory, FunctionReference[] memory);\n\n /// @notice Get an array of all installed plugins.\n /// @return pluginAddresses The addresses of all installed plugins.\n function getInstalledPlugins() external view returns (address[] memory);\n}\n"},"src/msca/6900/v0.7/interfaces/IPluginExecutor.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\n/**\n * @dev Implements https://eips.ethereum.org/EIPS/eip-6900. MSCAs must implement this interface to support execution\n * from plugins.\n */\ninterface IPluginExecutor {\n /// @notice Execute a call from a plugin through the account.\n /// @dev Permissions must be granted to the calling plugin for the call to go through.\n /// @param data The calldata to send to the account.\n function executeFromPlugin(bytes calldata data) external payable returns (bytes memory);\n\n /// @notice Execute a call from a plugin to a non-plugin address.\n /// @dev If the target is a plugin, the call SHOULD revert. Permissions must be granted to the calling plugin\n /// for the call to go through.\n /// @param target The address to be called.\n /// @param value The value to send with the call.\n /// @param data The calldata to send to the target.\n /// @return The return data from the call.\n function executeFromPluginExternal(address target, uint256 value, bytes calldata data)\n external\n payable\n returns (bytes memory);\n}\n"},"src/msca/6900/v0.7/interfaces/IPluginManager.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {FunctionReference} from \"../common/Structs.sol\";\n\n/**\n * @dev Implements https://eips.ethereum.org/EIPS/eip-6900. MSCAs must implement this interface to support installing\n * and uninstalling plugins.\n */\ninterface IPluginManager {\n event PluginInstalled(address indexed plugin, bytes32 manifestHash, FunctionReference[] dependencies);\n event PluginUninstalled(address indexed plugin, bool indexed onUninstallSucceeded);\n\n /// @notice Install a plugin to the modular account.\n /// @param plugin The plugin to install.\n /// @param manifestHash The hash of the plugin manifest.\n /// @param pluginInstallData Optional data to be decoded and used by the plugin to setup initial plugin data\n /// for the modular account.\n /// @param dependencies The dependencies of the plugin, as described in the manifest. Each FunctionReference\n /// MUST be composed of an installed plugin's address and a function ID of its validation function.\n function installPlugin(\n address plugin,\n bytes32 manifestHash,\n bytes calldata pluginInstallData,\n FunctionReference[] calldata dependencies\n ) external;\n\n /// @notice Uninstall a plugin from the modular account.\n /// @param plugin The plugin to uninstall.\n /// @param config An optional, implementation-specific field that accounts may use to ensure consistency\n /// guarantees.\n /// @param pluginUninstallData Optional data to be decoded and used by the plugin to clear plugin data for the\n /// modular account.\n function uninstallPlugin(address plugin, bytes calldata config, bytes calldata pluginUninstallData) external;\n}\n"},"src/msca/6900/v0.7/interfaces/IStandardExecutor.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {Call} from \"../common/Structs.sol\";\n\n/**\n * @dev Implements https://eips.ethereum.org/EIPS/eip-6900. MSCAs must implement this interface to support open-ended\n * execution.\n */\ninterface IStandardExecutor {\n /// @notice Standard execute method.\n /// @dev If the target is a plugin, the call SHOULD revert.\n /// @param target The target address for the account to call.\n /// @param value The value to send with the call.\n /// @param data The calldata for the call.\n /// @return The return data from the call.\n function execute(address target, uint256 value, bytes calldata data) external payable returns (bytes memory);\n\n /// @notice Standard executeBatch method.\n /// @dev If the target is a plugin, the call SHOULD revert. If any of the calls revert, the entire batch MUST\n /// revert.\n /// @param calls The array of calls.\n /// @return An array containing the return data from the calls.\n function executeBatch(Call[] calldata calls) external payable returns (bytes[] memory);\n}\n"},"src/msca/6900/v0.7/libs/ExecutionHookLib.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {EMPTY_FUNCTION_REFERENCE, SENTINEL_BYTES21} from \"../../../../common/Constants.sol\";\nimport {InvalidValidationFunctionId} from \"../../shared/common/Errors.sol\";\nimport {\n PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE,\n RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n} from \"../common/Constants.sol\";\nimport {\n ExecutionHooks,\n FunctionReference,\n HookGroup,\n PostExecHookToRun,\n RepeatableBytes21DLL\n} from \"../common/Structs.sol\";\nimport {IPlugin} from \"../interfaces/IPlugin.sol\";\nimport {FunctionReferenceLib} from \"./FunctionReferenceLib.sol\";\nimport {RepeatableFunctionReferenceDLLLib} from \"./RepeatableFunctionReferenceDLLLib.sol\";\n\n/**\n * @dev Process pre or post execution hooks.\n */\nlibrary ExecutionHookLib {\n using RepeatableFunctionReferenceDLLLib for RepeatableBytes21DLL;\n using FunctionReferenceLib for FunctionReference;\n using FunctionReferenceLib for bytes21;\n\n error PreExecHookFailed(address plugin, uint8 functionId, bytes revertReason);\n error PostExecHookFailed(address plugin, uint8 functionId, bytes revertReason);\n\n // avoid stack too deep\n struct SetPostExecHooksFromPreHooksParam {\n uint256 totalPostExecHooksToRunCount;\n PostExecHookToRun[] postExecHooksToRun;\n }\n\n function _processPreExecHooks(HookGroup storage hookGroup, bytes calldata data)\n internal\n returns (PostExecHookToRun[] memory postExecHooksToRun)\n {\n uint256 postOnlyHooksCount = hookGroup.postOnlyHooks.getUniqueItems();\n // hooks have three categories a. preOnlyHook b. preToPostHook c. postOnlyHook\n // 1. add repeated preHook into postHook 2. add postOnlyHooks\n uint256 maxPostHooksCount = postOnlyHooksCount + hookGroup.preHooks.getTotalItems();\n uint256 totalPostExecHooksToRunCount = 0;\n postExecHooksToRun = new PostExecHookToRun[](maxPostHooksCount);\n // copy postOnlyHooks into result first\n FunctionReference memory startHook = EMPTY_FUNCTION_REFERENCE.unpack();\n for (uint256 i = 0; i < postOnlyHooksCount; ++i) {\n (FunctionReference[] memory resultPostOnlyHooks, FunctionReference memory nextHook) =\n hookGroup.postOnlyHooks.getPaginated(startHook, 10);\n for (uint256 j = 0; j < resultPostOnlyHooks.length; ++j) {\n postExecHooksToRun[totalPostExecHooksToRunCount++].postExecHook = resultPostOnlyHooks[j];\n }\n if (nextHook.pack() == SENTINEL_BYTES21) {\n break;\n }\n startHook = nextHook;\n }\n // then run the preHooks and copy associated postHooks\n SetPostExecHooksFromPreHooksParam memory input;\n input.totalPostExecHooksToRunCount = totalPostExecHooksToRunCount;\n input.postExecHooksToRun = postExecHooksToRun;\n (totalPostExecHooksToRunCount, postExecHooksToRun) = _setPostExecHooksFromPreHooks(hookGroup, data, input);\n // solhint-disable-next-line no-inline-assembly\n assembly (\"memory-safe\") {\n mstore(postExecHooksToRun, totalPostExecHooksToRunCount)\n }\n }\n\n function _processPreExecHook(FunctionReference memory preExecHook, bytes calldata data)\n internal\n returns (bytes memory preExecHookReturnData)\n {\n try IPlugin(preExecHook.plugin).preExecutionHook(preExecHook.functionId, msg.sender, msg.value, data) returns (\n bytes memory returnData\n ) {\n preExecHookReturnData = returnData;\n } catch (bytes memory revertReason) {\n revert PreExecHookFailed(preExecHook.plugin, preExecHook.functionId, revertReason);\n }\n return preExecHookReturnData;\n }\n\n function _processPostExecHooks(PostExecHookToRun[] memory postExecHooksToRun) internal {\n uint256 length = postExecHooksToRun.length;\n for (uint256 i = 0; i < length; ++i) {\n FunctionReference memory postExecHook = postExecHooksToRun[i].postExecHook;\n // solhint-disable no-empty-blocks\n try IPlugin(postExecHook.plugin).postExecutionHook(\n postExecHook.functionId, postExecHooksToRun[i].preExecHookReturnData\n ) {} catch (bytes memory revertReason) {\n revert PostExecHookFailed(postExecHook.plugin, postExecHook.functionId, revertReason);\n }\n // solhint-enable no-empty-blocks\n }\n }\n\n function _getExecutionHooks(HookGroup storage hookGroup) internal view returns (ExecutionHooks[] memory hooks) {\n uint256 preHooksCount = hookGroup.preHooks.getUniqueItems();\n uint256 postOnlyHooksCount = hookGroup.postOnlyHooks.getUniqueItems();\n // hooks have three categories a. preOnlyHook b. preToPostHook c. postOnlyHook\n // 1. add repeated preHook into postHook 2. add postOnlyHooks\n uint256 maxExecHooksCount = postOnlyHooksCount + hookGroup.preHooks.getTotalItems();\n uint256 totalExecHooksCount = 0;\n hooks = new ExecutionHooks[](maxExecHooksCount);\n // copy postOnlyHooks into result first\n FunctionReference memory startHook = EMPTY_FUNCTION_REFERENCE.unpack();\n for (uint256 i = 0; i < postOnlyHooksCount; ++i) {\n (FunctionReference[] memory resultPostOnlyHooks, FunctionReference memory nextHook) =\n hookGroup.postOnlyHooks.getPaginated(startHook, 10);\n for (uint256 j = 0; j < resultPostOnlyHooks.length; ++j) {\n hooks[totalExecHooksCount++].postExecHook = resultPostOnlyHooks[j];\n }\n if (nextHook.pack() == SENTINEL_BYTES21) {\n break;\n }\n startHook = nextHook;\n }\n // then copy preOnlyHooks or preToPostHooks\n startHook = EMPTY_FUNCTION_REFERENCE.unpack();\n for (uint256 i = 0; i < preHooksCount; ++i) {\n (FunctionReference[] memory resultPreExecHooks, FunctionReference memory nextHook) =\n hookGroup.preHooks.getPaginated(startHook, 10);\n for (uint256 j = 0; j < resultPreExecHooks.length; ++j) {\n // if any revert, the outer call MUST revert\n bytes21 packedPreExecHook = resultPreExecHooks[j].pack();\n // getAll can handle 1000+ hooks\n FunctionReference[] memory preToPostHooks = hookGroup.preToPostHooks[packedPreExecHook].getAll();\n if (preToPostHooks.length > 0) {\n for (uint256 k = 0; k < preToPostHooks.length; ++k) {\n hooks[totalExecHooksCount].preExecHook = resultPreExecHooks[j];\n hooks[totalExecHooksCount].postExecHook = preToPostHooks[k];\n totalExecHooksCount++;\n }\n } else {\n // no associated postHook\n hooks[totalExecHooksCount++].preExecHook = resultPreExecHooks[j];\n }\n }\n if (nextHook.pack() == SENTINEL_BYTES21) {\n break;\n }\n startHook = nextHook;\n }\n // solhint-disable-next-line no-inline-assembly\n assembly (\"memory-safe\") {\n mstore(hooks, totalExecHooksCount)\n }\n return hooks;\n }\n\n /// @dev The caller would expect both input.totalPostExecHooksToRunCount and input.postExecHooksToRun to be assigned\n /// back to original values.\n function _setPostExecHooksFromPreHooks(\n HookGroup storage hookGroup,\n bytes calldata data,\n SetPostExecHooksFromPreHooksParam memory input\n ) internal returns (uint256, PostExecHookToRun[] memory) {\n FunctionReference memory startHook = EMPTY_FUNCTION_REFERENCE.unpack();\n uint256 preHooksCount = hookGroup.preHooks.getUniqueItems();\n for (uint256 i = 0; i < preHooksCount; ++i) {\n (FunctionReference[] memory resultPreExecHooks, FunctionReference memory nextHook) =\n hookGroup.preHooks.getPaginated(startHook, 10);\n for (uint256 j = 0; j < resultPreExecHooks.length; ++j) {\n // if any revert, the outer call MUST revert\n bytes21 packedPreExecHook = resultPreExecHooks[j].pack();\n if (\n packedPreExecHook == EMPTY_FUNCTION_REFERENCE\n || packedPreExecHook == RUNTIME_VALIDATION_ALWAYS_ALLOW_FUNCTION_REFERENCE\n || packedPreExecHook == PRE_HOOK_ALWAYS_DENY_FUNCTION_REFERENCE\n ) {\n revert InvalidValidationFunctionId(resultPreExecHooks[j].functionId);\n }\n // getAll can handle 1000+ hooks\n // run duplicated (if any) preHooks only once\n bytes memory preExecHookReturnData = _processPreExecHook(resultPreExecHooks[j], data);\n FunctionReference[] memory preToPostHooks = hookGroup.preToPostHooks[packedPreExecHook].getAll();\n if (preToPostHooks.length > 0) {\n for (uint256 k = 0; k < preToPostHooks.length; ++k) {\n input.postExecHooksToRun[input.totalPostExecHooksToRunCount].postExecHook = preToPostHooks[k];\n input.postExecHooksToRun[input.totalPostExecHooksToRunCount].preExecHookReturnData =\n preExecHookReturnData;\n input.totalPostExecHooksToRunCount++;\n }\n }\n }\n if (nextHook.pack() == SENTINEL_BYTES21) {\n break;\n }\n startHook = nextHook;\n }\n return (input.totalPostExecHooksToRunCount, input.postExecHooksToRun);\n }\n}\n"},"src/msca/6900/v0.7/managers/PluginExecutor.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {ExecutionUtils} from \"../../../../utils/ExecutionUtils.sol\";\nimport {InvalidExecutionFunction, NotFoundSelector} from \"../../shared/common/Errors.sol\";\nimport {ExecutionDetail, HookGroup, PermittedExternalCall, PostExecHookToRun} from \"../common/Structs.sol\";\nimport {IPlugin} from \"../interfaces/IPlugin.sol\";\nimport {IPluginExecutor} from \"../interfaces/IPluginExecutor.sol\";\nimport {ExecutionHookLib} from \"../libs/ExecutionHookLib.sol\";\nimport {WalletStorageV1Lib} from \"../libs/WalletStorageV1Lib.sol\";\nimport {ERC165Checker} from \"@openzeppelin/contracts/utils/introspection/ERC165Checker.sol\";\n\n/**\n * @dev Default implementation of https://eips.ethereum.org/EIPS/eip-6900. MSCAs must implement this interface to\n * support execution from plugins.\n * https://eips.ethereum.org/assets/eip-6900/Plugin_Execution_Flow.svg\n */\nlibrary PluginExecutor {\n using ExecutionHookLib for HookGroup;\n using ExecutionHookLib for PostExecHookToRun[];\n using ExecutionUtils for address;\n\n error ExecuteFromPluginToExternalNotPermitted();\n error ExecFromPluginToSelectorNotPermitted(address plugin, bytes4 selector);\n error NativeTokenSpendingNotPermitted(address plugin);\n\n /// @dev Refer to IPluginExecutor\n function executeFromPlugin(bytes calldata data) internal returns (bytes memory) {\n if (data.length < 4) {\n revert NotFoundSelector();\n }\n bytes4 selector = bytes4(data[0:4]);\n if (selector == bytes4(0)) {\n revert NotFoundSelector();\n }\n address callingPlugin = msg.sender;\n WalletStorageV1Lib.Layout storage walletStorage = WalletStorageV1Lib.getLayout();\n // permission check\n if (!walletStorage.permittedPluginCalls[callingPlugin][selector]) {\n revert ExecFromPluginToSelectorNotPermitted(callingPlugin, selector);\n }\n // this function call emulates a call to the fallback that routes calls into another plugin;\n // we use inner data here instead of the entire msg.data that includes the complete calldata of\n // executeFromPlugin\n ExecutionDetail storage executionDetail = walletStorage.executionDetails[selector];\n if (executionDetail.plugin == address(0)) {\n revert InvalidExecutionFunction(selector);\n }\n // pre execution hooks\n PostExecHookToRun[] memory postExecHooks = executionDetail.executionHooks._processPreExecHooks(data);\n // permitted to call the other plugin\n bytes memory returnData = executionDetail.plugin.callWithReturnDataOrRevert(0, data);\n // post execution hooks\n postExecHooks._processPostExecHooks();\n return returnData;\n }\n\n /// @dev Refer to IPluginExecutor\n function executeFromPluginToExternal(bytes calldata data, address target, uint256 value)\n internal\n returns (bytes memory)\n {\n if (target == address(this) || ERC165Checker.supportsInterface(target, type(IPlugin).interfaceId)) {\n revert ExecuteFromPluginToExternalNotPermitted();\n }\n WalletStorageV1Lib.Layout storage walletStorage = WalletStorageV1Lib.getLayout();\n address callingPlugin = msg.sender;\n // revert if the plugin can't cover the value and is not permitted to spend MSCA's native token\n if (value > 0 && value > msg.value && !walletStorage.pluginDetails[callingPlugin].canSpendNativeToken) {\n revert NativeTokenSpendingNotPermitted(callingPlugin);\n }\n PermittedExternalCall storage permittedExternalCall =\n walletStorage.permittedExternalCalls[callingPlugin][target];\n // permission check\n // addressPermitted can only be true if anyExternalAddressPermitted is false\n bool targetContractCallPermitted;\n // external call might not have function selector\n bytes4 selector = bytes4(data);\n if (permittedExternalCall.addressPermitted) {\n targetContractCallPermitted =\n permittedExternalCall.anySelector || permittedExternalCall.selectors[selector] || data.length == 0;\n } else {\n // also need to check the default permission in plugin detail\n targetContractCallPermitted = walletStorage.pluginDetails[callingPlugin].anyExternalAddressPermitted;\n }\n if (!targetContractCallPermitted) {\n revert ExecFromPluginToSelectorNotPermitted(callingPlugin, selector);\n }\n // we use msg.data here so the complete calldata of current function call executeFromPluginToExternalContract\n // can be passed\n // pre executeFromPluginToExternalContract hooks\n // process any pre exec hooks for IPluginExecutor.executeFromPluginExternal.selector during runtime\n PostExecHookToRun[] memory postExecHooks = walletStorage.executionDetails[IPluginExecutor\n .executeFromPluginExternal\n .selector].executionHooks._processPreExecHooks(msg.data);\n // call externally\n bytes memory returnData = target.callWithReturnDataOrRevert(value, data);\n // post executeFromPluginToExternalContract hooks\n postExecHooks._processPostExecHooks();\n return returnData;\n }\n}\n"},"src/msca/6900/v0.7/managers/StandardExecutor.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {ExecutionUtils} from \"../../../../utils/ExecutionUtils.sol\";\nimport {Call} from \"../common/Structs.sol\";\nimport {IPlugin} from \"../interfaces/IPlugin.sol\";\nimport {ERC165Checker} from \"@openzeppelin/contracts/utils/introspection/ERC165Checker.sol\";\n\n/**\n * @dev Default implementation of https://eips.ethereum.org/EIPS/eip-6900. MSCAs must implement this interface to\n * support open-ended execution.\n */\nlibrary StandardExecutor {\n using ExecutionUtils for address;\n\n error TargetIsPlugin(address plugin);\n\n /// @dev Refer to IStandardExecutor\n function execute(address target, uint256 value, bytes calldata data) internal returns (bytes memory returnData) {\n // reverts if the target is a plugin because modular account should be calling plugin via execution functions\n // defined in IPluginExecutor\n if (ERC165Checker.supportsInterface(target, type(IPlugin).interfaceId)) {\n revert TargetIsPlugin(target);\n }\n return target.callWithReturnDataOrRevert(value, data);\n }\n\n /// @dev Refer to IStandardExecutor\n function executeBatch(Call[] calldata calls) internal returns (bytes[] memory returnData) {\n returnData = new bytes[](calls.length);\n for (uint256 i = 0; i < calls.length; ++i) {\n if (ERC165Checker.supportsInterface(calls[i].target, type(IPlugin).interfaceId)) {\n revert TargetIsPlugin(calls[i].target);\n }\n returnData[i] = calls[i].target.callWithReturnDataOrRevert(calls[i].value, calls[i].data);\n }\n return returnData;\n }\n}\n"},"src/msca/6900/v0.7/account/WalletStorageInitializable.sol":{"content":"/*\n * Copyright 2024 Circle Internet Group, Inc. All rights reserved.\n\n * SPDX-License-Identifier: GPL-3.0-or-later\n\n * This program is free software: you can redistribute it and/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see <http://www.gnu.org/licenses/>.\n */\npragma solidity 0.8.24;\n\nimport {WalletStorageV1Lib} from \"../libs/WalletStorageV1Lib.sol\";\n\n/// @notice Forked from OpenZeppelin (proxy/utils/Initializable.sol) with wallet storage access.\n/// Reinitialization is removed.\n/// For V1 MSCA.\nabstract contract WalletStorageInitializable {\n /**\n * @dev Triggered when the contract has been initialized.\n */\n event WalletStorageInitialized();\n\n error WalletStorageIsInitializing();\n error WalletStorageIsNotInitializing();\n error WalletStorageIsInitialized();\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyWalletStorageInitializing` functions can be used to initialize parent contracts.\n *\n * Functions marked with `walletStorageInitializer` can be nested in the context of a\n * constructor.\n *\n * Emits an {WalletStorageInitialized} event.\n */\n modifier walletStorageInitializer() {\n bool isTopLevelCall = !WalletStorageV1Lib.getLayout().initializing;\n uint8 initialized = WalletStorageV1Lib.getLayout().initialized;\n\n // Allowed calls:\n // - initialSetup: the contract is not in the initializing state and no previous version was\n // initialized\n // - deploying: the contract is initialized at version 1 (no reininitialization) and the\n // current contract is just being deployed\n bool initialSetup = initialized == 0 && isTopLevelCall;\n bool deploying = initialized == 1 && address(this).code.length == 0;\n if (!initialSetup && !deploying) {\n revert WalletStorageIsInitialized();\n }\n WalletStorageV1Lib.getLayout().initialized = 1;\n if (isTopLevelCall) {\n WalletStorageV1Lib.getLayout().initializing = true;\n }\n _;\n if (isTopLevelCall) {\n WalletStorageV1Lib.getLayout().initializing = false;\n emit WalletStorageInitialized();\n }\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {walletStorageInitializer} modifier, directly or indirectly.\n */\n modifier onlyWalletStorageInitializing() {\n if (!WalletStorageV1Lib.getLayout().initializing) {\n revert WalletStorageIsNotInitializing();\n }\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n *\n * Emits an {WalletStorageInitialized} event the first time it is successfully executed.\n */\n function _disableWalletStorageInitializers() internal virtual {\n if (WalletStorageV1Lib.getLayout().initializing) {\n revert WalletStorageIsInitializing();\n }\n if (WalletStorageV1Lib.getLayout().initialized != type(uint8).max) {\n WalletStorageV1Lib.getLayout().initialized = type(uint8).max;\n emit WalletStorageInitialized();\n }\n }\n}\n"},"lib/account-abstraction/contracts/core/Helpers.sol":{"content":"// SPDX-License-Identifier: GPL-3.0\npragma solidity ^0.8.12;\n\n/* solhint-disable no-inline-assembly */\n\n/**\n * returned data from validateUserOp.\n * validateUserOp returns a uint256, with is created by `_packedValidationData` and parsed by `_parseValidationData`\n * @param aggregator - address(0) - the account validated the signature by itself.\n * address(1) - the account failed to validate the signature.\n * otherwise - this is an address of a signature aggregator that must be used to validate the signature.\n * @param validAfter - this UserOp is valid only after this timestamp.\n * @param validaUntil - this UserOp is valid only up to this timestamp.\n */\n struct ValidationData {\n address aggregator;\n uint48 validAfter;\n uint48 validUntil;\n }\n\n//extract sigFailed, validAfter, validUntil.\n// also convert zero validUntil to type(uint48).max\n function _parseValidationData(uint validationData) pure returns (ValidationData memory data) {\n address aggregator = address(uint160(validationData));\n uint48 validUntil = uint48(validationData >> 160);\n if (validUntil == 0) {\n validUntil = type(uint48).max;\n }\n uint48 validAfter = uint48(validationData >> (48 + 160));\n return ValidationData(aggregator, validAfter, validUntil);\n }\n\n// intersect account and paymaster ranges.\n function _intersectTimeRange(uint256 validationData, uint256 paymasterValidationData) pure returns (ValidationData memory) {\n ValidationData memory accountValidationData = _parseValidationData(validationData);\n ValidationData memory pmValidationData = _parseValidationData(paymasterValidationData);\n address aggregator = accountValidationData.aggregator;\n if (aggregator == address(0)) {\n aggregator = pmValidationData.aggregator;\n }\n uint48 validAfter = accountValidationData.validAfter;\n uint48 validUntil = accountValidationData.validUntil;\n uint48 pmValidAfter = pmValidationData.validAfter;\n uint48 pmValidUntil = pmValidationData.validUntil;\n\n if (validAfter < pmValidAfter) validAfter = pmValidAfter;\n if (validUntil > pmValidUntil) validUntil = pmValidUntil;\n return ValidationData(aggregator, validAfter, validUntil);\n }\n\n/**\n * helper to pack the return value for validateUserOp\n * @param data - the ValidationData to pack\n */\n function _packValidationData(ValidationData memory data) pure returns (uint256) {\n return uint160(data.aggregator) | (uint256(data.validUntil) << 160) | (uint256(data.validAfter) << (160 + 48));\n }\n\n/**\n * helper to pack the return value for validateUserOp, when not using an aggregator\n * @param sigFailed - true for signature failure, false for success\n * @param validUntil last timestamp this UserOperation is valid (or zero for infinite)\n * @param validAfter first timestamp this UserOperation is valid\n */\n function _packValidationData(bool sigFailed, uint48 validUntil, uint48 validAfter) pure returns (uint256) {\n return (sigFailed ? 1 : 0) | (uint256(validUntil) << 160) | (uint256(validAfter) << (160 + 48));\n }\n\n/**\n * keccak function over calldata.\n * @dev copy calldata into memory, do keccak and drop allocated memory. Strangely, this is more efficient than letting solidity do it.\n */\n function calldataKeccak(bytes calldata data) pure returns (bytes32 ret) {\n assembly {\n let mem := mload(0x40)\n let len := data.length\n calldatacopy(mem, data.offset, len)\n ret := keccak256(mem, len)\n }\n }\n\n"},"node_modules/@openzeppelin/contracts-upgradeable/interfaces/draft-IERC1822Upgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified\n * proxy whose upgrades are fully controlled by the current implementation.\n */\ninterface IERC1822ProxiableUpgradeable {\n /**\n * @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation\n * address.\n *\n * IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks\n * bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this\n * function revert if invoked through a proxy.\n */\n function proxiableUUID() external view returns (bytes32);\n}\n"},"node_modules/@openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../beacon/IBeaconUpgradeable.sol\";\nimport \"../../interfaces/IERC1967Upgradeable.sol\";\nimport \"../../interfaces/draft-IERC1822Upgradeable.sol\";\nimport \"../../utils/AddressUpgradeable.sol\";\nimport \"../../utils/StorageSlotUpgradeable.sol\";\nimport {Initializable} from \"../utils/Initializable.sol\";\n\n/**\n * @dev This abstract contract provides getters and event emitting update functions for\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.\n *\n * _Available since v4.1._\n */\nabstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {\n // This is the keccak-256 hash of \"eip1967.proxy.rollback\" subtracted by 1\n bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n function __ERC1967Upgrade_init() internal onlyInitializing {\n }\n\n function __ERC1967Upgrade_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev Returns the current implementation address.\n */\n function _getImplementation() internal view returns (address) {\n return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) private {\n require(AddressUpgradeable.isContract(newImplementation), \"ERC1967: new implementation is not a contract\");\n StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;\n }\n\n /**\n * @dev Perform implementation upgrade\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Perform implementation upgrade with additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {\n _upgradeTo(newImplementation);\n if (data.length > 0 || forceCall) {\n AddressUpgradeable.functionDelegateCall(newImplementation, data);\n }\n }\n\n /**\n * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.\n *\n * Emits an {Upgraded} event.\n */\n function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {\n // Upgrades from old implementations will perform a rollback test. This test requires the new\n // implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing\n // this special case will break upgrade paths from old UUPS implementation to new ones.\n if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {\n _setImplementation(newImplementation);\n } else {\n try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {\n require(slot == _IMPLEMENTATION_SLOT, \"ERC1967Upgrade: unsupported proxiableUUID\");\n } catch {\n revert(\"ERC1967Upgrade: new implementation is not UUPS\");\n }\n _upgradeToAndCall(newImplementation, data, forceCall);\n }\n }\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Returns the current admin.\n */\n function _getAdmin() internal view returns (address) {\n return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;\n }\n\n /**\n * @dev Stores a new address in the EIP1967 admin slot.\n */\n function _setAdmin(address newAdmin) private {\n require(newAdmin != address(0), \"ERC1967: new admin is the zero address\");\n StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;\n }\n\n /**\n * @dev Changes the admin of the proxy.\n *\n * Emits an {AdminChanged} event.\n */\n function _changeAdmin(address newAdmin) internal {\n emit AdminChanged(_getAdmin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.\n * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.\n */\n bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;\n\n /**\n * @dev Returns the current beacon.\n */\n function _getBeacon() internal view returns (address) {\n return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;\n }\n\n /**\n * @dev Stores a new beacon in the EIP1967 beacon slot.\n */\n function _setBeacon(address newBeacon) private {\n require(AddressUpgradeable.isContract(newBeacon), \"ERC1967: new beacon is not a contract\");\n require(\n AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),\n \"ERC1967: beacon implementation is not a contract\"\n );\n StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;\n }\n\n /**\n * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does\n * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).\n *\n * Emits a {BeaconUpgraded} event.\n */\n function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {\n _setBeacon(newBeacon);\n emit BeaconUpgraded(newBeacon);\n if (data.length > 0 || forceCall) {\n AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);\n }\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n"},"node_modules/@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol":{"content":"// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```solidity\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n *\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract co |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Is this from forge build
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is from forge verify-contract --show-standard-json-input
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could we please also document the contract verification under this directory (can be a follow up)? https://github.com/circlefin/buidl-wallet-contracts/tree/master/script/verify
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Signed-off-by: Daniel Lim <[email protected]>
0b48e5c
Summary
This is for epv0.6 branch and on commit af55d55
This pull request includes the addition of deployment logs for the
SingleOwnerMSCAFactory
across multiple blockchain networks. Each log entry includes a note that the deployment was performed using thecast send
command and provides the transaction hash for reference.Detail
Deployment logs added for the following networks:
broadcast/003_DeploySingleOwnerMSCAFactory.s.sol/1/run-1737572400.md
: Added deployment log with transaction hash0xbe9d1311397eac006c444a1d2f9a1ffc2f9d77607eeaf97562a93c738675d386
.broadcast/003_DeploySingleOwnerMSCAFactory.s.sol/11155111/run-1737572400.md
: Added deployment log with transaction hash0xd28546c12461e5c8c80f9419efa4362693c39052a518baaf7828cbd46896c14f
.broadcast/003_DeploySingleOwnerMSCAFactory.s.sol/130/run-1737572400.md
: Added deployment log with transaction hash0xc86a1c2408bcba2f5c323bb2cbdb0267488f5ef9ce5ca6794d0d2917b75c783e
.broadcast/003_DeploySingleOwnerMSCAFactory.s.sol/1301/run-1737572400.md
: Added deployment log with transaction hash0x450424cb9fc06040f9b1b7dd1d8b31058f77bdd090773066f757043d6375736c
.broadcast/003_DeploySingleOwnerMSCAFactory.s.sol/137/run-1737572400.md
: Added deployment log with transaction hash0x686ee24b2a91374e2e86ae29927d2935f1ff2abe7ad05d72b58a79d53f8dc095
.broadcast/003_DeploySingleOwnerMSCAFactory.s.sol/42161/run-1737572400.md
: Added deployment log with transaction hash0x7722d4a8e52034d81dc27e66518a0d2a3ab89b42dc622f553eec445d0a1b3957
.broadcast/003_DeploySingleOwnerMSCAFactory.s.sol/421614/run-1737572400.md
: Added deployment log with transaction hash0x65d1439ec8b7fc967c28f15c05b063167a90ded5f65207e24376e680b465aa4c
.broadcast/003_DeploySingleOwnerMSCAFactory.s.sol/80002/run-1737572400.md
: Added deployment log with transaction hash0x0f42a1c9d4b73629def32ced0d96aa01ae7f0f48fdce372fe1da1125e9af5611
.Checklist
yarn test
)docs
folder)feat!: breaking change
)yarn lint
) and fix any issues?yarn format:check
) and fix any issues (yarn format:write
)?Testing
Deployed and verified the contracts.
Documentation
Optional section.
Link to the doc.