Verified contractPartialMIT
StartaleSmartAccount
Address0x000000b8f5f723a680d3d7ee624fe0bc84a6e05a
- Balance
0 ETH
- Transactions
0
- Compiler
solc 0.8.30
- Same code
Only this contract
Details
- Compiler
- solc 0.8.30+commit.73712a01
- Language
- solidity
- Optimization
- Yes, 499 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 25,079,636
- Creation transaction
- 0x1258a879e4…8f6a549739
40 files
- src/StartaleSmartAccount.solmain25.41 KB
- lib/ExcessivelySafeCall/src/ExcessivelySafeCall.sol5.61 KB
- lib/account-abstraction/contracts/interfaces/IAggregator.sol1.87 KB
- lib/account-abstraction/contracts/interfaces/IEntryPoint.sol9.19 KB
- lib/account-abstraction/contracts/interfaces/INonceManager.sol1.11 KB
- lib/account-abstraction/contracts/interfaces/IStakeManager.sol3.62 KB
- lib/account-abstraction/contracts/interfaces/PackedUserOperation.sol1.47 KB
- lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol654 B
- lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol2.6 KB
- lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol997 B
- lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol870 B
- lib/sentinellist/src/SentinelList.sol6.13 KB
- lib/solady/src/utils/CallContextChecker.sol4.49 KB
- lib/solady/src/utils/ECDSA.sol20.2 KB
- lib/solady/src/utils/EIP712.sol10.9 KB
- lib/solady/src/utils/UUPSUpgradeable.sol5.21 KB
- src/core/AllStorage.sol1.51 KB
- src/core/BaseAccount.sol5.26 KB
- src/core/ERC7779Adapter.sol2.9 KB
- src/core/ExecutionHelper.sol13.56 KB
- src/core/ModuleManager.sol43.2 KB
- src/interfaces/IAccountEventsAndErrors.sol1.73 KB
- src/interfaces/IERC4337Account.sol3.97 KB
- src/interfaces/IERC7579Account.sol1.17 KB
- src/interfaces/IERC7579Module.sol3.54 KB
- src/interfaces/IERC7779.sol1.6 KB
- src/interfaces/IStartaleSmartAccount.sol1.48 KB
- src/interfaces/core/IAccountConfig.sol1.26 KB
- src/interfaces/core/IAllStorage.sol2.13 KB
- src/interfaces/core/IBaseAccount.sol1.44 KB
- src/interfaces/core/IExecutionHelper.sol1.87 KB
- src/interfaces/core/IModuleManager.sol1.73 KB
- src/interfaces/core/IModuleManagerEventsAndErrors.sol5.86 KB
- src/lib/DataParserLib.sol4.32 KB
- src/lib/ExecutionLib.sol3.91 KB
- src/lib/Initializable.sol1.32 KB
- src/lib/ModeLib.sol6.42 KB
- src/lib/NonceLib.sol1.58 KB
- src/types/Constants.sol1.96 KB
- src/types/Structs.sol777 B
src/StartaleSmartAccount.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {BaseAccount} from './core/BaseAccount.sol';
import {ERC7779Adapter} from './core/ERC7779Adapter.sol';
import {ExecutionHelper} from './core/ExecutionHelper.sol';
import {ModuleManager} from './core/ModuleManager.sol';
import {IERC7579Account} from './interfaces/IERC7579Account.sol';
import {IValidator} from './interfaces/IERC7579Module.sol';
import {IStartaleSmartAccount} from './interfaces/IStartaleSmartAccount.sol';
import {IAccountConfig} from './interfaces/core/IAccountConfig.sol';
import {ExecutionLib} from './lib/ExecutionLib.sol';
import {Initializable} from './lib/Initializable.sol';
import {
CALLTYPE_BATCH,
CALLTYPE_DELEGATECALL,
CALLTYPE_SINGLE,
CallType,
EXECTYPE_DEFAULT,
EXECTYPE_TRY,
ExecType,
ExecutionMode,
ModeLib
} from './lib/ModeLib.sol';
import {NonceLib} from './lib/NonceLib.sol';
import {ACCOUNT_STORAGE_LOCATION} from './types/Constants.sol';
import {
MODULE_TYPE_EXECUTOR,
MODULE_TYPE_FALLBACK,
MODULE_TYPE_HOOK,
MODULE_TYPE_MULTI,
MODULE_TYPE_PREVALIDATION_HOOK_ERC1271,
MODULE_TYPE_PREVALIDATION_HOOK_ERC4337,
MODULE_TYPE_VALIDATOR,
SUPPORTS_ERC7739,
VALIDATION_FAILED,
VALIDATION_SUCCESS
} from './types/Constants.sol';
import {EmergencyUninstall} from './types/Structs.sol';
import {PackedUserOperation} from '@account-abstraction/interfaces/PackedUserOperation.sol';
import {IERC1271} from '@openzeppelin/contracts/interfaces/IERC1271.sol';
import {IERC1155Receiver} from '@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol';
import {IERC721Receiver} from '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import {IERC165} from '@openzeppelin/contracts/utils/introspection/IERC165.sol';
import {SENTINEL, SentinelListLib, ZERO_ADDRESS} from 'sentinellist/SentinelList.sol';
import {UUPSUpgradeable} from 'solady/utils/UUPSUpgradeable.sol';
/// @title Startale Smart Account
/// @notice This contract integrates various functionalities to handle modular smart accounts compliant with ERC-7579 and ERC-4337 standards.
/// @dev Comprehensive suite of methods for managing smart accounts, integrating module management, execution management, and upgradability via UUPS.
/// @author Startale Labs
/// Special thanks to the Biconomy team for https://github.com/bcnmy/nexus/ on which this implementation is highly based on.
contract StartaleSmartAccount is
IStartaleSmartAccount,
IERC165,
BaseAccount,
ExecutionHelper,
ModuleManager,
ERC7779Adapter,
UUPSUpgradeable
{
using ModeLib for ExecutionMode;
using ExecutionLib for bytes;
using NonceLib for uint256;
using SentinelListLib for SentinelListLib.SentinelList;
/// @dev The timelock period for emergency hook uninstallation.
uint256 internal constant _EMERGENCY_TIMELOCK = 1 days;
/// @dev The event emitted when an emergency hook uninstallation is initiated.
event EmergencyHookUninstallRequest(address hook, uint256 timestamp);
/// @dev The event emitted when an emergency hook uninstallation request is reset.
event EmergencyHookUninstallRequestReset(address hook, uint256 timestamp);
/// @notice Initializes the smart account with the specified entry point.
constructor(
address anEntryPoint,
address defaultValidator,
bytes memory initData
) ModuleManager(defaultValidator, initData) {
require(address(anEntryPoint) != address(0), EntryPointCanNotBeZero());
_ENTRYPOINT = anEntryPoint;
}
/// @notice Validates a user operation against a specified validator, extracted from the operation's nonce.
/// @param op The user operation to validate, encapsulating all transaction details.
/// @param userOpHash Hash of the user operation data, used for signature validation.
/// @param missingAccountFunds Funds missing from the account's deposit necessary for transaction execution.
/// This can be zero if covered by a paymaster or if sufficient deposit exists.
/// @return validationData Encoded validation result or failure, propagated from the validator module.
/// - Encoded format in validationData:
/// - First 20 bytes: Address of the Validator module, to which the validation task is forwarded.
/// The validator module returns:
/// - `SIG_VALIDATION_SUCCESS` (0) indicates successful validation.
/// - `SIG_VALIDATION_FAILED` (1) indicates signature validation failure.
/// @dev Expects the validator's address to be encoded in the upper 96 bits of the user operation's nonce.
/// This method forwards the validation task to the extracted validator module address.
/// @dev The entryPoint calls this function. If validation fails, it returns `VALIDATION_FAILED` (1) otherwise `0`.
/// @dev Features Module Enable Mode.
/// This Module Enable Mode flow is intended for the module acting as the validator
/// for the user operation that triggers the Module Enable Flow. Otherwise, a call to
/// `IERC7579Account.installModule` should be included in `userOp.callData`.
function validateUserOp(
PackedUserOperation calldata op,
bytes32 userOpHash,
uint256 missingAccountFunds
) external virtual payPrefund(missingAccountFunds) onlyEntryPoint returns (uint256 validationData) {
address validator;
PackedUserOperation memory userOp = op;
if (op.nonce.isModuleEnableMode()) {
// if it is module enable mode, we need to enable the module first
// and get the cleaned signature
userOp.signature = _enableMode(userOpHash, op.signature);
}
validator = _handleValidator(op.nonce.getValidator());
(userOpHash, userOp.signature) = _withPreValidationHook(userOpHash, userOp, missingAccountFunds);
validationData = IValidator(validator).validateUserOp(userOp, userOpHash);
}
/// @notice Executes transactions in single or batch modes as specified g by the execution mode.
/// @param mode The execution mode detailing how transactions should be handled (single, batch, default, try/catch).
/// @param executionCalldata The encoded transaction data to execute.
/// @dev This function handles transaction execution flexibility and is protected by the `onlyEntryPoint` modifier.
/// @dev This function also goes through hook checks via withHook modifier.
function execute(ExecutionMode mode, bytes calldata executionCalldata) external payable onlyEntryPoint withHook {
(CallType callType, ExecType execType) = mode.decodeBasic();
if (callType == CALLTYPE_SINGLE) {
_handleSingleExecution(executionCalldata, execType);
} else if (callType == CALLTYPE_BATCH) {
_handleBatchExecution(executionCalldata, execType);
} else if (callType == CALLTYPE_DELEGATECALL) {
_handleDelegateCallExecution(executionCalldata, execType);
} else {
revert UnsupportedCallType(callType);
}
}
/// @notice Executes transactions from an executor module, supporting both single and batch transactions.
/// @param mode The execution mode (single or batch, default or try).
/// @param executionCalldata The transaction data to execute.
/// @return returnData The results of the transaction executions, which may include errors in try mode.
/// @dev This function is callable only by an executor module and goes through hook checks.
function executeFromExecutor(
ExecutionMode mode,
bytes calldata executionCalldata
) external payable onlyExecutorModule withHook returns (bytes[] memory returnData) {
(CallType callType, ExecType execType) = mode.decodeBasic();
// check if calltype is batch or single or delegate call
if (callType == CALLTYPE_SINGLE) {
returnData = _handleSingleExecutionAndReturnData(executionCalldata, execType);
} else if (callType == CALLTYPE_BATCH) {
returnData = _handleBatchExecutionAndReturnData(executionCalldata, execType);
} else if (callType == CALLTYPE_DELEGATECALL) {
returnData = _handleDelegateCallExecutionAndReturnData(executionCalldata, execType);
} else {
revert UnsupportedCallType(callType);
}
}
/// @notice Executes a user operation via a call using the contract's context.
/// @param userOp The user operation to execute, containing transaction details.
/// @param - Hash of the user operation.
/// @dev Only callable by the EntryPoint. Decodes the user operation calldata, skipping the first four bytes, and executes the inner call.
function executeUserOp(PackedUserOperation calldata userOp, bytes32) external payable virtual onlyEntryPoint withHook {
bytes calldata callData = userOp.callData[4:];
(bool success,) = address(this).delegatecall(callData);
if (!success) {
revert ExecutionFailed();
}
}
/// @notice Installs a new module to the smart account.
/// @param moduleTypeId The type identifier of the module being installed, which determines its role:
/// - 1 for Validator
/// - 2 for Executor
/// - 3 for Fallback
/// - 4 for Hook
/// - 8 for 1271 Prevalidation Hook
/// - 9 for 4337 Prevalidation Hook
/// @param module The address of the module to install.
/// @param initData Initialization data for the module.
/// @dev This function can only be called by the EntryPoint or the account itself for security reasons.
/// @dev This function goes through hook checks via withHook modifier through internal function _installModule.
function installModule(
uint256 moduleTypeId,
address module,
bytes calldata initData
) external payable onlyEntryPointOrSelf {
_installModule(moduleTypeId, module, initData);
emit ModuleInstalled(moduleTypeId, module);
}
/// @notice Installs an interface to the smart account.
/// @param interfaceId The id of the interface to install.
/// @dev This function can only be called by the EntryPoint or the account itself for security reasons.
function installInterface(bytes4 interfaceId) external payable onlyEntryPointOrSelf {
_installInterface(interfaceId);
}
/// @notice Installs multiple interfaces to the smart account.
/// @param interfaceIds The ids of the interfaces to install.
/// @dev This function can only be called by the EntryPoint or the account itself for security reasons.
function installInterfaces(bytes4[] calldata interfaceIds) external payable onlyEntryPointOrSelf {
_installInterfaces(interfaceIds);
}
/// @notice Uninstalls an interface from the smart account.
/// @param interfaceId The id of the interface to uninstall.
/// @dev This function can only be called by the EntryPoint or the account itself for security reasons.
function uninstallInterface(bytes4 interfaceId) external payable onlyEntryPointOrSelf {
_uninstallInterface(interfaceId);
}
/// @notice Uninstalls a module from the smart account.
/// @param moduleTypeId The type ID of the module to be uninstalled, matching the installation type:
/// - 1 for Validator
/// - 2 for Executor
/// - 3 for Fallback
/// - 4 for Hook
/// - 8 for 1271 Prevalidation Hook
/// - 9 for 4337 Prevalidation Hook
/// @notice
/// If the module is malicious, it can prevent itself from being uninstalled by spending all gas in the onUninstall() method.
/// @param module The address of the module to uninstall.
/// @param deInitData De-initialization data for the module.
/// @dev Ensures that the operation is authorized and valid before proceeding with the uninstallation.
function uninstallModule(
uint256 moduleTypeId,
address module,
bytes calldata deInitData
) external payable onlyEntryPointOrSelf withHook {
require(_isModuleInstalled(moduleTypeId, module, deInitData), ModuleNotInstalled(moduleTypeId, module));
if (moduleTypeId == MODULE_TYPE_VALIDATOR) {
_uninstallValidator(module, deInitData);
_checkInitializedValidators();
} else if (moduleTypeId == MODULE_TYPE_EXECUTOR) {
_uninstallExecutor(module, deInitData);
} else if (moduleTypeId == MODULE_TYPE_FALLBACK) {
_uninstallFallbackHandler(module, deInitData);
} else if (
moduleTypeId == MODULE_TYPE_HOOK || moduleTypeId == MODULE_TYPE_PREVALIDATION_HOOK_ERC1271
|| moduleTypeId == MODULE_TYPE_PREVALIDATION_HOOK_ERC4337
) {
_uninstallHook(module, moduleTypeId, deInitData);
}
emit ModuleUninstalled(moduleTypeId, module);
}
function emergencyUninstallHook(EmergencyUninstall calldata data, bytes calldata signature) external payable {
// Validate the signature
_checkEmergencyUninstallSignature(data, signature);
// Parse uninstall data
(uint256 hookType, address hook, bytes calldata deInitData) = (data.hookType, data.hook, data.deInitData);
// Validate the hook is of a supported type and is installed
require(
hookType == MODULE_TYPE_HOOK || hookType == MODULE_TYPE_PREVALIDATION_HOOK_ERC1271
|| hookType == MODULE_TYPE_PREVALIDATION_HOOK_ERC4337,
UnsupportedModuleType(hookType)
);
require(_isModuleInstalled(hookType, hook, deInitData), ModuleNotInstalled(hookType, hook));
// Get the account storage
AccountStorage storage accountStorage = _getAccountStorage();
uint256 hookTimelock = accountStorage.emergencyUninstallTimelock[hook];
if (hookTimelock == 0) {
// if the timelock hasnt been initiated, initiate it
accountStorage.emergencyUninstallTimelock[hook] = block.timestamp;
emit EmergencyHookUninstallRequest(hook, block.timestamp);
} else if (block.timestamp >= hookTimelock + 3 * _EMERGENCY_TIMELOCK) {
// if the timelock has been left for too long, reset it
accountStorage.emergencyUninstallTimelock[hook] = block.timestamp;
emit EmergencyHookUninstallRequestReset(hook, block.timestamp);
} else if (block.timestamp >= hookTimelock + _EMERGENCY_TIMELOCK) {
// if the timelock expired, clear it and uninstall the hook
accountStorage.emergencyUninstallTimelock[hook] = 0;
_uninstallHook(hook, hookType, deInitData);
emit ModuleUninstalled(hookType, hook);
} else {
// if the timelock is initiated but not expired, revert
revert EmergencyTimeLockNotExpired();
}
}
/// @notice Initializes the smart account with the specified initialization data.
/// @param initData The initialization data for the smart account.
/// @dev This function can only be called by the account itself or the proxy factory.
/// When a 7702 account is created, the first userOp should contain self-call to initialize the account.
function initializeAccount(bytes calldata initData) external payable virtual {
// Protect this function to only be callable when used with the proxy factory or when
// account calls itself
if (msg.sender != address(this)) {
Initializable.requireInitializable();
}
_initializeAccount(initData);
}
function _initializeAccount(bytes calldata initData) internal {
require(initData.length >= 24, InvalidInitData());
if (_amIERC7702()) {
_addStorageBase(ACCOUNT_STORAGE_LOCATION);
}
address bootstrap;
bytes calldata bootstrapCall;
assembly {
bootstrap := calldataload(initData.offset)
let s := calldataload(add(initData.offset, 0x20))
let u := add(initData.offset, s)
bootstrapCall.offset := add(u, 0x20)
bootstrapCall.length := calldataload(u)
}
(bool success,) = bootstrap.delegatecall(bootstrapCall);
require(success, AccountInitializationFailed());
if (!_amIERC7702()) {
require(isInitialized(), AccountNotInitialized());
}
}
/// @dev Uninstalls all validators, executors, hooks, fallbacks, and pre-validation hooks.
/// @notice It is worth noting that, onRedelegation() does not obligate the account to completely wipe out it’s storage.
/// @notice It is an optional action for the account where it could uninitialize the storage variables as much as it can to provide clean storage for new wallet.
function _onRedelegation() internal override {
_uninstallAllValidators();
_uninstallAllExecutors();
_uninstallHook(_getHook());
_uninstallPreValidationHook(
_getPreValidationHook(MODULE_TYPE_PREVALIDATION_HOOK_ERC1271), MODULE_TYPE_PREVALIDATION_HOOK_ERC1271
);
_uninstallPreValidationHook(
_getPreValidationHook(MODULE_TYPE_PREVALIDATION_HOOK_ERC4337), MODULE_TYPE_PREVALIDATION_HOOK_ERC4337
);
_uninstallAllFallbacks();
_uninstallAllInterfaces();
_initSentinelLists();
}
/// @notice Validates a signature according to ERC-1271 standards.
/// @param hash The hash of the data being validated.
/// @param signature Signature data that needs to be validated.
/// @return The status code of the signature validation (`0x1626ba7e` if valid).
/// bytes4(keccak256("isValidSignature(bytes32,bytes)") = 0x1626ba7e
/// @dev Delegates the validation to a validator module specified within the signature data.
function isValidSignature(bytes32 hash, bytes calldata signature) external view virtual override returns (bytes4) {
// Handle potential ERC7739 support detection request
if (signature.length == 0) {
// Forces the compiler to optimize for smaller bytecode size.
// checking if the hash equals to 0x7739773977397739773977397739773977397739773977397739773977397739
if (uint256(hash) == (~signature.length / 0xffff) * 0x7739) {
return checkERC7739Support(hash, signature);
}
}
// else proceed with normal signature verification
// First 20 bytes of data will be validator address and rest of the bytes is complete signature.
address validator = _handleValidator(address(bytes20(signature[0:20])));
bytes memory signature_;
(hash, signature_) = _withPreValidationHook(hash, signature[20:]);
try IValidator(validator).isValidSignatureWithSender(msg.sender, hash, signature_) returns (bytes4 res) {
return res;
} catch {
return bytes4(0xffffffff);
}
}
/// @notice Retrieves the address of the current implementation from the EIP-1967 slot.
/// @notice Checks the 1967 implementation slot
/// @return implementation The address of the current contract implementation.
function getImplementation() external view returns (address implementation) {
assembly {
implementation := sload(_ERC1967_IMPLEMENTATION_SLOT)
}
}
/// @notice Checks if a specific module type is supported by this smart account.
/// @param moduleTypeId The identifier of the module type to check.
/// @return True if the module type is supported, false otherwise.
function supportsModule(uint256 moduleTypeId) external view virtual returns (bool) {
if (
moduleTypeId == MODULE_TYPE_VALIDATOR || moduleTypeId == MODULE_TYPE_EXECUTOR
|| moduleTypeId == MODULE_TYPE_FALLBACK || moduleTypeId == MODULE_TYPE_HOOK
|| moduleTypeId == MODULE_TYPE_PREVALIDATION_HOOK_ERC1271
|| moduleTypeId == MODULE_TYPE_PREVALIDATION_HOOK_ERC4337 || moduleTypeId == MODULE_TYPE_MULTI
) {
return true;
}
return false;
}
/// @notice Determines if a specific execution mode is supported.
/// @param mode The execution mode to evaluate.
/// @return isSupported True if the execution mode is supported, false otherwise.
function supportsExecutionMode(ExecutionMode mode) external view virtual returns (bool isSupported) {
(CallType callType, ExecType execType) = mode.decodeBasic();
// Return true if both the call type and execution type are supported.
return (callType == CALLTYPE_SINGLE || callType == CALLTYPE_BATCH || callType == CALLTYPE_DELEGATECALL)
&& (execType == EXECTYPE_DEFAULT || execType == EXECTYPE_TRY);
}
function supportsInterface(bytes4 interfaceId) external view virtual override returns (bool) {
AccountStorage storage ds = _getAccountStorage();
if (
interfaceId == type(IERC721Receiver).interfaceId || interfaceId == type(IERC1155Receiver).interfaceId
|| interfaceId == type(IERC165).interfaceId || interfaceId == type(IERC1271).interfaceId
|| interfaceId == type(IStartaleSmartAccount).interfaceId || interfaceId == type(IERC7579Account).interfaceId
|| interfaceId == type(IAccountConfig).interfaceId
) {
return true;
}
return ds.supportedIfaces[interfaceId];
}
/// @notice Determines whether a module is installed on the smart account.
/// @param moduleTypeId The ID corresponding to the type of module (Validator, Executor, Fallback, Hook).
/// @param module The address of the module to check.
/// @param additionalContext Optional context that may be needed for certain checks.
/// @return True if the module is installed, false otherwise.
function isModuleInstalled(
uint256 moduleTypeId,
address module,
bytes calldata additionalContext
) external view returns (bool) {
return _isModuleInstalled(moduleTypeId, module, additionalContext);
}
/// @notice Checks if the smart account is initialized.
/// @return True if the smart account is initialized, false otherwise.
/// @dev In case default validator is initialized, two other SLOADS from _areSentinelListsInitialized() are not checked,
/// this method should not introduce huge gas overhead.
function isInitialized() public view returns (bool) {
return (IValidator(_DEFAULT_VALIDATOR).isInitialized(address(this)) || _areSentinelListsInitialized());
}
/// Returns the account's implementation ID.
/// @return The unique identifier for this account implementation.
function accountId() external pure virtual returns (string memory) {
return _ACCOUNT_IMPLEMENTATION_ID;
}
/// Upgrades the contract to a new implementation and calls a function on the new contract.
/// @notice Updates the slot ERC1967 slot
/// @param newImplementation The address of the new contract implementation.
/// @param data The calldata to be sent to the new implementation.
function upgradeToAndCall(address newImplementation, bytes calldata data) public payable virtual override withHook {
require(newImplementation != address(0), InvalidImplementationAddress());
bool res;
assembly {
res := gt(extcodesize(newImplementation), 0)
}
if (!res) revert InvalidImplementationAddress();
UUPSUpgradeable.upgradeToAndCall(newImplementation, data);
}
/// @dev For automatic detection that the smart account supports the ERC7739 workflow
/// Iterates over all the validators but only if this is a detection request
/// ERC-7739 spec assumes that if the account doesn't support ERC-7739
/// it will try to handle the detection request as it was normal sig verification
/// request and will return 0xffffffff since it won't be able to verify the 0x signature
/// against 0x7739...7739 hash.
/// So this approach is consistent with the ERC-7739 spec.
/// If no validator supports ERC-7739, this function returns false
/// thus the account will proceed with normal signature verification
/// and return 0xffffffff as a result.
function checkERC7739Support(bytes32 hash, bytes calldata signature) public view virtual returns (bytes4) {
bytes4 result;
unchecked {
SentinelListLib.SentinelList storage validators = _getAccountStorage().validators;
address next = validators.entries[SENTINEL];
while (next != ZERO_ADDRESS && next != SENTINEL) {
result = _get7739Version(next, result, hash, signature);
next = validators.getNext(next);
}
}
result = _get7739Version(_DEFAULT_VALIDATOR, result, hash, signature); // check default validator
return result == bytes4(0) ? bytes4(0xffffffff) : result;
}
function _get7739Version(
address validator,
bytes4 prevResult,
bytes32 hash,
bytes calldata signature
) internal view returns (bytes4) {
bytes4 support = IValidator(validator).isValidSignatureWithSender(msg.sender, hash, signature);
if (bytes2(support) == bytes2(SUPPORTS_ERC7739) && support > prevResult) {
return support;
}
return prevResult;
}
/// @dev Ensures that only authorized callers can upgrade the smart contract implementation.
/// This is part of the UUPS (Universal Upgradeable Proxy Standard) pattern.
/// @param newImplementation The address of the new implementation to upgrade to.
function _authorizeUpgrade(address newImplementation) internal virtual override(UUPSUpgradeable) onlyEntryPointOrSelf {
if (_amIERC7702()) {
revert ERC7702AccountCannotBeUpgradedThisWay();
}
}
// checks if there's at least one validator initialized
function _checkInitializedValidators() internal view {
if (!_amIERC7702() && !IValidator(_DEFAULT_VALIDATOR).isInitialized(address(this))) {
unchecked {
SentinelListLib.SentinelList storage validators = _getAccountStorage().validators;
address next = validators.entries[SENTINEL];
while (next != ZERO_ADDRESS && next != SENTINEL) {
if (IValidator(next).isInitialized(address(this))) {
break;
}
next = validators.getNext(next);
}
if (next == SENTINEL) {
//went through all validators and none was initialized
revert CanNotRemoveLastValidator();
}
}
}
}
/// @dev EIP712 domain name and version.
function _domainNameAndVersion() internal pure override returns (string memory name, string memory version) {
name = 'Startale';
version = '1.0.0';
}
}
lib/ExcessivelySafeCall/src/ExcessivelySafeCall.sol
// SPDX-License-Identifier: MIT OR Apache-2.0
pragma solidity >=0.7.6;
library ExcessivelySafeCall {
uint256 constant LOW_28_MASK =
0x00000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/// @notice Use when you _really_ really _really_ don't trust the called
/// contract. This prevents the called contract from causing reversion of
/// the caller in as many ways as we can.
/// @dev The main difference between this and a solidity low-level call is
/// that we limit the number of bytes that the callee can cause to be
/// copied to caller memory. This prevents stupid things like malicious
/// contracts returning 10,000,000 bytes causing a local OOG when copying
/// to memory.
/// @param _target The address to call
/// @param _gas The amount of gas to forward to the remote contract
/// @param _value The value in wei to send to the remote contract
/// @param _maxCopy The maximum number of bytes of returndata to copy
/// to memory.
/// @param _calldata The data to send to the remote contract
/// @return success and returndata, as `.call()`. Returndata is capped to
/// `_maxCopy` bytes.
function excessivelySafeCall(
address _target,
uint256 _gas,
uint256 _value,
uint16 _maxCopy,
bytes memory _calldata
) internal returns (bool, bytes memory) {
// set up for assembly call
uint256 _toCopy;
bool _success;
bytes memory _returnData = new bytes(_maxCopy);
// dispatch message to recipient
// by assembly calling "handle" function
// we call via assembly to avoid memcopying a very large returndata
// returned by a malicious contract
assembly {
_success := call(
_gas, // gas
_target, // recipient
_value, // ether value
add(_calldata, 0x20), // inloc
mload(_calldata), // inlen
0, // outloc
0 // outlen
)
// limit our copy to 256 bytes
_toCopy := returndatasize()
if gt(_toCopy, _maxCopy) {
_toCopy := _maxCopy
}
// Store the length of the copied bytes
mstore(_returnData, _toCopy)
// copy the bytes from returndata[0:_toCopy]
returndatacopy(add(_returnData, 0x20), 0, _toCopy)
}
return (_success, _returnData);
}
/// @notice Use when you _really_ really _really_ don't trust the called
/// contract. This prevents the called contract from causing reversion of
/// the caller in as many ways as we can.
/// @dev The main difference between this and a solidity low-level call is
/// that we limit the number of bytes that the callee can cause to be
/// copied to caller memory. This prevents stupid things like malicious
/// contracts returning 10,000,000 bytes causing a local OOG when copying
/// to memory.
/// @param _target The address to call
/// @param _gas The amount of gas to forward to the remote contract
/// @param _maxCopy The maximum number of bytes of returndata to copy
/// to memory.
/// @param _calldata The data to send to the remote contract
/// @return success and returndata, as `.call()`. Returndata is capped to
/// `_maxCopy` bytes.
function excessivelySafeStaticCall(
address _target,
uint256 _gas,
uint16 _maxCopy,
bytes memory _calldata
) internal view returns (bool, bytes memory) {
// set up for assembly call
uint256 _toCopy;
bool _success;
bytes memory _returnData = new bytes(_maxCopy);
// dispatch message to recipient
// by assembly calling "handle" function
// we call via assembly to avoid memcopying a very large returndata
// returned by a malicious contract
assembly {
_success := staticcall(
_gas, // gas
_target, // recipient
add(_calldata, 0x20), // inloc
mload(_calldata), // inlen
0, // outloc
0 // outlen
)
// limit our copy to 256 bytes
_toCopy := returndatasize()
if gt(_toCopy, _maxCopy) {
_toCopy := _maxCopy
}
// Store the length of the copied bytes
mstore(_returnData, _toCopy)
// copy the bytes from returndata[0:_toCopy]
returndatacopy(add(_returnData, 0x20), 0, _toCopy)
}
return (_success, _returnData);
}
/**
* @notice Swaps function selectors in encoded contract calls
* @dev Allows reuse of encoded calldata for functions with identical
* argument types but different names. It simply swaps out the first 4 bytes
* for the new selector. This function modifies memory in place, and should
* only be used with caution.
* @param _newSelector The new 4-byte selector
* @param _buf The encoded contract args
*/
function swapSelector(bytes4 _newSelector, bytes memory _buf)
internal
pure
{
require(_buf.length >= 4);
uint256 _mask = LOW_28_MASK;
assembly {
// load the first word of
let _word := mload(add(_buf, 0x20))
// mask out the top 4 bytes
// /x
_word := and(_word, _mask)
_word := or(_newSelector, _word)
mstore(add(_buf, 0x20), _word)
}
}
}
lib/account-abstraction/contracts/interfaces/IAggregator.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.5;
import "./PackedUserOperation.sol";
/**
* Aggregated Signatures validator.
*/
interface IAggregator {
/**
* Validate aggregated signature.
* Revert if the aggregated signature does not match the given list of operations.
* @param userOps - Array of UserOperations to validate the signature for.
* @param signature - The aggregated signature.
*/
function validateSignatures(
PackedUserOperation[] calldata userOps,
bytes calldata signature
) external view;
/**
* Validate signature of a single userOp.
* This method should be called by bundler after EntryPointSimulation.simulateValidation() returns
* the aggregator this account uses.
* First it validates the signature over the userOp. Then it returns data to be used when creating the handleOps.
* @param userOp - The userOperation received from the user.
* @return sigForUserOp - The value to put into the signature field of the userOp when calling handleOps.
* (usually empty, unless account and aggregator support some kind of "multisig".
*/
function validateUserOpSignature(
PackedUserOperation calldata userOp
) external view returns (bytes memory sigForUserOp);
/**
* Aggregate multiple signatures into a single value.
* This method is called off-chain to calculate the signature to pass with handleOps()
* bundler MAY use optimized custom code perform this aggregation.
* @param userOps - Array of UserOperations to collect the signatures from.
* @return aggregatedSignature - The aggregated signature.
*/
function aggregateSignatures(
PackedUserOperation[] calldata userOps
) external view returns (bytes memory aggregatedSignature);
}
lib/account-abstraction/contracts/interfaces/IEntryPoint.sol
/**
** Account-Abstraction (EIP-4337) singleton EntryPoint implementation.
** Only one instance required on each chain.
**/
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.5;
/* solhint-disable avoid-low-level-calls */
/* solhint-disable no-inline-assembly */
/* solhint-disable reason-string */
import "./PackedUserOperation.sol";
import "./IStakeManager.sol";
import "./IAggregator.sol";
import "./INonceManager.sol";
interface IEntryPoint is IStakeManager, INonceManager {
/***
* An event emitted after each successful request.
* @param userOpHash - Unique identifier for the request (hash its entire content, except signature).
* @param sender - The account that generates this request.
* @param paymaster - If non-null, the paymaster that pays for this request.
* @param nonce - The nonce value from the request.
* @param success - True if the sender transaction succeeded, false if reverted.
* @param actualGasCost - Actual amount paid (by account or paymaster) for this UserOperation.
* @param actualGasUsed - Total gas used by this UserOperation (including preVerification, creation,
* validation and execution).
*/
event UserOperationEvent(
bytes32 indexed userOpHash,
address indexed sender,
address indexed paymaster,
uint256 nonce,
bool success,
uint256 actualGasCost,
uint256 actualGasUsed
);
/**
* Account "sender" was deployed.
* @param userOpHash - The userOp that deployed this account. UserOperationEvent will follow.
* @param sender - The account that is deployed
* @param factory - The factory used to deploy this account (in the initCode)
* @param paymaster - The paymaster used by this UserOp
*/
event AccountDeployed(
bytes32 indexed userOpHash,
address indexed sender,
address factory,
address paymaster
);
/**
* An event emitted if the UserOperation "callData" reverted with non-zero length.
* @param userOpHash - The request unique identifier.
* @param sender - The sender of this request.
* @param nonce - The nonce used in the request.
* @param revertReason - The return bytes from the (reverted) call to "callData".
*/
event UserOperationRevertReason(
bytes32 indexed userOpHash,
address indexed sender,
uint256 nonce,
bytes revertReason
);
/**
* An event emitted if the UserOperation Paymaster's "postOp" call reverted with non-zero length.
* @param userOpHash - The request unique identifier.
* @param sender - The sender of this request.
* @param nonce - The nonce used in the request.
* @param revertReason - The return bytes from the (reverted) call to "callData".
*/
event PostOpRevertReason(
bytes32 indexed userOpHash,
address indexed sender,
uint256 nonce,
bytes revertReason
);
/**
* UserOp consumed more than prefund. The UserOperation is reverted, and no refund is made.
* @param userOpHash - The request unique identifier.
* @param sender - The sender of this request.
* @param nonce - The nonce used in the request.
*/
event UserOperationPrefundTooLow(
bytes32 indexed userOpHash,
address indexed sender,
uint256 nonce
);
/**
* An event emitted by handleOps(), before starting the execution loop.
* Any event emitted before this event, is part of the validation.
*/
event BeforeExecution();
/**
* Signature aggregator used by the following UserOperationEvents within this bundle.
* @param aggregator - The aggregator used for the following UserOperationEvents.
*/
event SignatureAggregatorChanged(address indexed aggregator);
/**
* A custom revert error of handleOps, to identify the offending op.
* Should be caught in off-chain handleOps simulation and not happen on-chain.
* Useful for mitigating DoS attempts against batchers or for troubleshooting of factory/account/paymaster reverts.
* NOTE: If simulateValidation passes successfully, there should be no reason for handleOps to fail on it.
* @param opIndex - Index into the array of ops to the failed one (in simulateValidation, this is always zero).
* @param reason - Revert reason. The string starts with a unique code "AAmn",
* where "m" is "1" for factory, "2" for account and "3" for paymaster issues,
* so a failure can be attributed to the correct entity.
*/
error FailedOp(uint256 opIndex, string reason);
/**
* A custom revert error of handleOps, to report a revert by account or paymaster.
* @param opIndex - Index into the array of ops to the failed one (in simulateValidation, this is always zero).
* @param reason - Revert reason. see FailedOp(uint256,string), above
* @param inner - data from inner cought revert reason
* @dev note that inner is truncated to 2048 bytes
*/
error FailedOpWithRevert(uint256 opIndex, string reason, bytes inner);
error PostOpReverted(bytes returnData);
/**
* Error case when a signature aggregator fails to verify the aggregated signature it had created.
* @param aggregator The aggregator that failed to verify the signature
*/
error SignatureValidationFailed(address aggregator);
// Return value of getSenderAddress.
error SenderAddressResult(address sender);
// UserOps handled, per aggregator.
struct UserOpsPerAggregator {
PackedUserOperation[] userOps;
// Aggregator address
IAggregator aggregator;
// Aggregated signature
bytes signature;
}
/**
* Execute a batch of UserOperations.
* No signature aggregator is used.
* If any account requires an aggregator (that is, it returned an aggregator when
* performing simulateValidation), then handleAggregatedOps() must be used instead.
* @param ops - The operations to execute.
* @param beneficiary - The address to receive the fees.
*/
function handleOps(
PackedUserOperation[] calldata ops,
address payable beneficiary
) external;
/**
* Execute a batch of UserOperation with Aggregators
* @param opsPerAggregator - The operations to execute, grouped by aggregator (or address(0) for no-aggregator accounts).
* @param beneficiary - The address to receive the fees.
*/
function handleAggregatedOps(
UserOpsPerAggregator[] calldata opsPerAggregator,
address payable beneficiary
) external;
/**
* Generate a request Id - unique identifier for this request.
* The request ID is a hash over the content of the userOp (except the signature), the entrypoint and the chainid.
* @param userOp - The user operation to generate the request ID for.
* @return hash the hash of this UserOperation
*/
function getUserOpHash(
PackedUserOperation calldata userOp
) external view returns (bytes32);
/**
* Gas and return values during simulation.
* @param preOpGas - The gas used for validation (including preValidationGas)
* @param prefund - The required prefund for this operation
* @param accountValidationData - returned validationData from account.
* @param paymasterValidationData - return validationData from paymaster.
* @param paymasterContext - Returned by validatePaymasterUserOp (to be passed into postOp)
*/
struct ReturnInfo {
uint256 preOpGas;
uint256 prefund;
uint256 accountValidationData;
uint256 paymasterValidationData;
bytes paymasterContext;
}
/**
* Returned aggregated signature info:
* The aggregator returned by the account, and its current stake.
*/
struct AggregatorStakeInfo {
address aggregator;
StakeInfo stakeInfo;
}
/**
* Get counterfactual sender address.
* Calculate the sender contract address that will be generated by the initCode and salt in the UserOperation.
* This method always revert, and returns the address in SenderAddressResult error
* @param initCode - The constructor code to be passed into the UserOperation.
*/
function getSenderAddress(bytes memory initCode) external;
error DelegateAndRevert(bool success, bytes ret);
/**
* Helper method for dry-run testing.
* @dev calling this method, the EntryPoint will make a delegatecall to the given data, and report (via revert) the result.
* The method always revert, so is only useful off-chain for dry run calls, in cases where state-override to replace
* actual EntryPoint code is less convenient.
* @param target a target contract to make a delegatecall from entrypoint
* @param data data to pass to target in a delegatecall
*/
function delegateAndRevert(address target, bytes calldata data) external;
}
lib/account-abstraction/contracts/interfaces/INonceManager.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.5;
interface INonceManager {
/**
* Return the next nonce for this sender.
* Within a given key, the nonce values are sequenced (starting with zero, and incremented by one on each userop)
* But UserOp with different keys can come with arbitrary order.
*
* @param sender the account address
* @param key the high 192 bit of the nonce
* @return nonce a full nonce to pass for next UserOp with this sender.
*/
function getNonce(address sender, uint192 key)
external view returns (uint256 nonce);
/**
* Manually increment the nonce of the sender.
* This method is exposed just for completeness..
* Account does NOT need to call it, neither during validation, nor elsewhere,
* as the EntryPoint will update the nonce regardless.
* Possible use-case is call it with various keys to "initialize" their nonces to one, so that future
* UserOperations will not pay extra for the first transaction with a given key.
*/
function incrementNonce(uint192 key) external;
}
lib/account-abstraction/contracts/interfaces/IStakeManager.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity >=0.7.5;
/**
* Manage deposits and stakes.
* Deposit is just a balance used to pay for UserOperations (either by a paymaster or an account).
* Stake is value locked for at least "unstakeDelay" by the staked entity.
*/
interface IStakeManager {
event Deposited(address indexed account, uint256 totalDeposit);
event Withdrawn(
address indexed account,
address withdrawAddress,
uint256 amount
);
// Emitted when stake or unstake delay are modified.
event StakeLocked(
address indexed account,
uint256 totalStaked,
uint256 unstakeDelaySec
);
// Emitted once a stake is scheduled for withdrawal.
event StakeUnlocked(address indexed account, uint256 withdrawTime);
event StakeWithdrawn(
address indexed account,
address withdrawAddress,
uint256 amount
);
/**
* @param deposit - The entity's deposit.
* @param staked - True if this entity is staked.
* @param stake - Actual amount of ether staked for this entity.
* @param unstakeDelaySec - Minimum delay to withdraw the stake.
* @param withdrawTime - First block timestamp where 'withdrawStake' will be callable, or zero if already locked.
* @dev Sizes were chosen so that deposit fits into one cell (used during handleOp)
* and the rest fit into a 2nd cell (used during stake/unstake)
* - 112 bit allows for 10^15 eth
* - 48 bit for full timestamp
* - 32 bit allows 150 years for unstake delay
*/
struct DepositInfo {
uint256 deposit;
bool staked;
uint112 stake;
uint32 unstakeDelaySec;
uint48 withdrawTime;
}
// API struct used by getStakeInfo and simulateValidation.
struct StakeInfo {
uint256 stake;
uint256 unstakeDelaySec;
}
/**
* Get deposit info.
* @param account - The account to query.
* @return info - Full deposit information of given account.
*/
function getDepositInfo(
address account
) external view returns (DepositInfo memory info);
/**
* Get account balance.
* @param account - The account to query.
* @return - The deposit (for gas payment) of the account.
*/
function balanceOf(address account) external view returns (uint256);
/**
* Add to the deposit of the given account.
* @param account - The account to add to.
*/
function depositTo(address account) external payable;
/**
* Add to the account's stake - amount and delay
* any pending unstake is first cancelled.
* @param _unstakeDelaySec - The new lock duration before the deposit can be withdrawn.
*/
function addStake(uint32 _unstakeDelaySec) external payable;
/**
* Attempt to unlock the stake.
* The value can be withdrawn (using withdrawStake) after the unstake delay.
*/
function unlockStake() external;
/**
* Withdraw from the (unlocked) stake.
* Must first call unlockStake and wait for the unstakeDelay to pass.
* @param withdrawAddress - The address to send withdrawn value.
*/
function withdrawStake(address payable withdrawAddress) external;
/**
* Withdraw from the deposit.
* @param withdrawAddress - The address to send withdrawn value.
* @param withdrawAmount - The amount to withdraw.
*/
function withdrawTo(
address payable withdrawAddress,
uint256 withdrawAmount
) external;
}
lib/account-abstraction/contracts/interfaces/PackedUserOperation.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.5;
/**
* User Operation struct
* @param sender - The sender account of this request.
* @param nonce - Unique value the sender uses to verify it is not a replay.
* @param initCode - If set, the account contract will be created by this constructor/
* @param callData - The method call to execute on this account.
* @param accountGasLimits - Packed gas limits for validateUserOp and gas limit passed to the callData method call.
* @param preVerificationGas - Gas not calculated by the handleOps method, but added to the gas paid.
* Covers batch overhead.
* @param gasFees - packed gas fields maxPriorityFeePerGas and maxFeePerGas - Same as EIP-1559 gas parameters.
* @param paymasterAndData - If set, this field holds the paymaster address, verification gas limit, postOp gas limit and paymaster-specific extra data
* The paymaster will pay for the transaction instead of the sender.
* @param signature - Sender-verified signature over the entire request, the EntryPoint address and the chain ID.
*/
struct PackedUserOperation {
address sender;
uint256 nonce;
bytes initCode;
bytes callData;
bytes32 accountGasLimits;
uint256 preVerificationGas;
bytes32 gasFees;
bytes paymasterAndData;
bytes signature;
}
lib/openzeppelin-contracts/contracts/interfaces/IERC1271.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1271.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with `hash`
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}
lib/openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Interface that must be implemented by smart contracts in order to receive
* ERC-1155 token transfers.
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC-1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC-1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
lib/openzeppelin-contracts/contracts/token/ERC721/IERC721Receiver.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
lib/openzeppelin-contracts/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
lib/sentinellist/src/SentinelList.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Sentinel address
address constant SENTINEL = address(0x1);
// Zero address
address constant ZERO_ADDRESS = address(0x0);
/**
* @title SentinelListLib
* @dev Library for managing a linked list of addresses
* @author Rhinestone
*/
library SentinelListLib {
// Struct to hold the linked list
struct SentinelList {
mapping(address => address) entries;
}
error LinkedList_AlreadyInitialized();
error LinkedList_InvalidPage();
error LinkedList_InvalidEntry(address entry);
error LinkedList_EntryAlreadyInList(address entry);
/**
* Initialize the linked list
*
* @param self The linked list
*/
function init(SentinelList storage self) internal {
if (alreadyInitialized(self)) revert LinkedList_AlreadyInitialized();
self.entries[SENTINEL] = SENTINEL;
}
/**
* Check if the linked list is already initialized
*
* @param self The linked list
*
* @return bool True if the linked list is already initialized
*/
function alreadyInitialized(SentinelList storage self) internal view returns (bool) {
return self.entries[SENTINEL] != ZERO_ADDRESS;
}
/**
* Get the next entry in the linked list
*
* @param self The linked list
* @param entry The current entry
*
* @return address The next entry
*/
function getNext(SentinelList storage self, address entry) internal view returns (address) {
if (entry == ZERO_ADDRESS) {
revert LinkedList_InvalidEntry(entry);
}
return self.entries[entry];
}
/**
* Push a new entry to the linked list
*
* @param self The linked list
* @param newEntry The new entry
*/
function push(SentinelList storage self, address newEntry) internal {
if (newEntry == ZERO_ADDRESS || newEntry == SENTINEL) {
revert LinkedList_InvalidEntry(newEntry);
}
if (self.entries[newEntry] != ZERO_ADDRESS) revert LinkedList_EntryAlreadyInList(newEntry);
self.entries[newEntry] = self.entries[SENTINEL];
self.entries[SENTINEL] = newEntry;
}
/**
* Safe push a new entry to the linked list
* @dev This ensures that the linked list is initialized and initializes it if it is not
*
* @param self The linked list
* @param newEntry The new entry
*/
function safePush(SentinelList storage self, address newEntry) internal {
if (!alreadyInitialized({ self: self })) {
init({ self: self });
}
push({ self: self, newEntry: newEntry });
}
/**
* Pop an entry from the linked list
*
* @param self The linked list
* @param prevEntry The entry before the entry to pop
* @param popEntry The entry to pop
*/
function pop(SentinelList storage self, address prevEntry, address popEntry) internal {
if (popEntry == ZERO_ADDRESS || popEntry == SENTINEL) {
revert LinkedList_InvalidEntry(prevEntry);
}
if (self.entries[prevEntry] != popEntry) revert LinkedList_InvalidEntry(popEntry);
self.entries[prevEntry] = self.entries[popEntry];
self.entries[popEntry] = ZERO_ADDRESS;
}
/**
* Pop all entries from the linked list
*
* @param self The linked list
*/
function popAll(SentinelList storage self) internal {
address next = self.entries[SENTINEL];
while (next != ZERO_ADDRESS) {
address current = next;
next = self.entries[next];
self.entries[current] = ZERO_ADDRESS;
}
}
/**
* Check if the linked list contains an entry
*
* @param self The linked list
* @param entry The entry to check
*
* @return bool True if the linked list contains the entry
*/
function contains(SentinelList storage self, address entry) internal view returns (bool) {
return SENTINEL != entry && self.entries[entry] != ZERO_ADDRESS;
}
/**
* Get all entries in the linked list
*
* @param self The linked list
* @param start The start entry
* @param pageSize The page size
*
* @return array All entries in the linked list
* @return next The next entry
*/
function getEntriesPaginated(
SentinelList storage self,
address start,
uint256 pageSize
)
internal
view
returns (address[] memory array, address next)
{
if (start != SENTINEL && !contains(self, start)) revert LinkedList_InvalidEntry(start);
if (pageSize == 0) revert LinkedList_InvalidPage();
// Init array with max page size
array = new address[](pageSize);
// Populate return array
uint256 entryCount = 0;
next = self.entries[start];
while (next != ZERO_ADDRESS && next != SENTINEL && entryCount < pageSize) {
array[entryCount] = next;
next = self.entries[next];
entryCount++;
}
/**
* Because of the argument validation, we can assume that the loop will always iterate over
* the valid entry list values
* and the `next` variable will either be an enabled entry or a sentinel address
* (signalling the end).
*
* If we haven't reached the end inside the loop, we need to set the next pointer to
* the last element of the entry array
* because the `next` variable (which is a entry by itself) acting as a pointer to the
* start of the next page is neither
* incSENTINELrent page, nor will it be included in the next one if you pass it as a
* start.
*/
if (next != SENTINEL && entryCount > 0) {
next = array[entryCount - 1];
}
// Set correct size of returned array
// solhint-disable-next-line no-inline-assembly
/// @solidity memory-safe-assembly
assembly {
mstore(array, entryCount)
}
}
}
lib/solady/src/utils/CallContextChecker.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Call context checker mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/CallContextChecker.sol)
contract CallContextChecker {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The call is from an unauthorized call context.
error UnauthorizedCallContext();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* IMMUTABLES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev For checking if the context is a delegate call.
///
/// Note: To enable use cases with an immutable default implementation in the bytecode,
/// (see: ERC6551Proxy), we don't require that the proxy address must match the
/// value stored in the implementation slot, which may not be initialized.
uint256 private immutable __self = uint256(uint160(address(this)));
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CALL CONTEXT CHECKS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// A proxy call can be either via a `delegatecall` to an implementation,
// or a 7702 call on an authority that points to a delegation.
/// @dev Returns whether the current call context is on a EIP7702 authority
/// (i.e. externally owned account).
function _onEIP7702Authority() internal view virtual returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
extcodecopy(address(), 0x00, 0x00, 0x20)
// Note: Checking that it starts with hex"ef01" is the most general and futureproof.
// 7702 bytecode is `abi.encodePacked(hex"ef01", uint8(version), address(delegation))`.
result := eq(0xef01, shr(240, mload(0x00)))
}
}
/// @dev Returns the implementation of this contract.
function _selfImplementation() internal view virtual returns (address) {
return address(uint160(__self));
}
/// @dev Returns whether the current call context is on the implementation itself.
function _onImplementation() internal view virtual returns (bool) {
return __self == uint160(address(this));
}
/// @dev Requires that the current call context is performed via a EIP7702 authority.
function _checkOnlyEIP7702Authority() internal view virtual {
if (!_onEIP7702Authority()) _revertUnauthorizedCallContext();
}
/// @dev Requires that the current call context is performed via a proxy.
function _checkOnlyProxy() internal view virtual {
if (_onImplementation()) _revertUnauthorizedCallContext();
}
/// @dev Requires that the current call context is NOT performed via a proxy.
/// This is the opposite of `checkOnlyProxy`.
function _checkNotDelegated() internal view virtual {
if (!_onImplementation()) _revertUnauthorizedCallContext();
}
/// @dev Requires that the current call context is performed via a EIP7702 authority.
modifier onlyEIP7702Authority() virtual {
_checkOnlyEIP7702Authority();
_;
}
/// @dev Requires that the current call context is performed via a proxy.
modifier onlyProxy() virtual {
_checkOnlyProxy();
_;
}
/// @dev Requires that the current call context is NOT performed via a proxy.
/// This is the opposite of `onlyProxy`.
modifier notDelegated() virtual {
_checkNotDelegated();
_;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
function _revertUnauthorizedCallContext() private pure {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x9f03a026) // `UnauthorizedCallContext()`.
revert(0x1c, 0x04)
}
}
}
lib/solady/src/utils/ECDSA.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Gas optimized ECDSA wrapper.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ECDSA.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ECDSA.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/ECDSA.sol)
///
/// @dev Note:
/// - The recovery functions use the ecrecover precompile (0x1).
/// - As of Solady version 0.0.68, the `recover` variants will revert upon recovery failure.
/// This is for more safety by default.
/// Use the `tryRecover` variants if you need to get the zero address back
/// upon recovery failure instead.
/// - As of Solady version 0.0.134, all `bytes signature` variants accept both
/// regular 65-byte `(r, s, v)` and EIP-2098 `(r, vs)` short form signatures.
/// See: https://eips.ethereum.org/EIPS/eip-2098
/// This is for calldata efficiency on smart accounts prevalent on L2s.
///
/// WARNING! Do NOT directly use signatures as unique identifiers:
/// - The recovery operations do NOT check if a signature is non-malleable.
/// - Use a nonce in the digest to prevent replay attacks on the same contract.
/// - Use EIP-712 for the digest to prevent replay attacks across different chains and contracts.
/// EIP-712 also enables readable signing of typed data for better user safety.
/// - If you need a unique hash from a signature, please use the `canonicalHash` functions.
library ECDSA {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The order of the secp256k1 elliptic curve.
uint256 internal constant N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141;
/// @dev `N/2 + 1`. Used for checking the malleability of the signature.
uint256 private constant _HALF_N_PLUS_1 =
0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The signature is invalid.
error InvalidSignature();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RECOVERY OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function recover(bytes32 hash, bytes memory signature) internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
} {
switch mload(signature)
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { continue }
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if returndatasize() { break }
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function recoverCalldata(bytes32 hash, bytes calldata signature)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
} {
switch signature.length
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, calldataload(signature.offset)) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`.
calldatacopy(0x40, signature.offset, 0x40) // Copy `r` and `s`.
}
default { continue }
mstore(0x00, hash)
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if returndatasize() { break }
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the EIP-2098 short form signature defined by `r` and `vs`.
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal view returns (address result) {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, r)
mstore(0x60, shr(1, shl(1, vs))) // `s`.
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(returndatasize()) {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
}
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the signature defined by `v`, `r`, `s`.
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, and(v, 0xff))
mstore(0x40, r)
mstore(0x60, s)
result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20))
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
if iszero(returndatasize()) {
mstore(0x00, 0x8baa579f) // `InvalidSignature()`.
revert(0x1c, 0x04)
}
mstore(0x60, 0) // Restore the zero slot.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* TRY-RECOVER OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// WARNING!
// These functions will NOT revert upon recovery failure.
// Instead, they will return the zero address upon recovery failure.
// It is critical that the returned address is NEVER compared against
// a zero address (e.g. an uninitialized address variable).
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function tryRecover(bytes32 hash, bytes memory signature)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {} {
switch mload(signature)
case 64 {
let vs := mload(add(signature, 0x40))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`.
mstore(0x60, mload(add(signature, 0x40))) // `s`.
}
default { break }
mstore(0x00, hash)
mstore(0x40, mload(add(signature, 0x20))) // `r`.
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`, and the `signature`.
function tryRecoverCalldata(bytes32 hash, bytes calldata signature)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
for { let m := mload(0x40) } 1 {} {
switch signature.length
case 64 {
let vs := calldataload(add(signature.offset, 0x20))
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, calldataload(signature.offset)) // `r`.
mstore(0x60, shr(1, shl(1, vs))) // `s`.
}
case 65 {
mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`.
calldatacopy(0x40, signature.offset, 0x40) // Copy `r` and `s`.
}
default { break }
mstore(0x00, hash)
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
break
}
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the EIP-2098 short form signature defined by `r` and `vs`.
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, add(shr(255, vs), 27)) // `v`.
mstore(0x40, r)
mstore(0x60, shr(1, shl(1, vs))) // `s`.
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Recovers the signer's address from a message digest `hash`,
/// and the signature defined by `v`, `r`, `s`.
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s)
internal
view
returns (address result)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x00, hash)
mstore(0x20, and(v, 0xff))
mstore(0x40, r)
mstore(0x60, s)
pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20))
mstore(0x60, 0) // Restore the zero slot.
// `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
result := mload(xor(0x60, returndatasize()))
mstore(0x40, m) // Restore the free memory pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HASHING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an Ethereum Signed Message, created from a `hash`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign)
/// JSON-RPC method as part of EIP-191.
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, hash) // Store into scratch space for keccak256.
mstore(0x00, "\x00\x00\x00\x00\x19Ethereum Signed Message:\n32") // 28 bytes.
result := keccak256(0x04, 0x3c) // `32 * 2 - (32 - 28) = 60 = 0x3c`.
}
}
/// @dev Returns an Ethereum Signed Message, created from `s`.
/// This produces a hash corresponding to the one signed with the
/// [`eth_sign`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign)
/// JSON-RPC method as part of EIP-191.
/// Note: Supports lengths of `s` up to 999999 bytes.
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let sLength := mload(s)
let o := 0x20
mstore(o, "\x19Ethereum Signed Message:\n") // 26 bytes, zero-right-padded.
mstore(0x00, 0x00)
// Convert the `s.length` to ASCII decimal representation: `base10(s.length)`.
for { let temp := sLength } 1 {} {
o := sub(o, 1)
mstore8(o, add(48, mod(temp, 10)))
temp := div(temp, 10)
if iszero(temp) { break }
}
let n := sub(0x3a, o) // Header length: `26 + 32 - o`.
// Throw an out-of-offset error (consumes all gas) if the header exceeds 32 bytes.
returndatacopy(returndatasize(), returndatasize(), gt(n, 0x20))
mstore(s, or(mload(0x00), mload(n))) // Temporarily store the header.
result := keccak256(add(s, sub(0x20, n)), add(n, sLength))
mstore(s, sLength) // Restore the length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CANONICAL HASH FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// The following functions returns the hash of the signature in it's canonicalized format,
// which is the 65-byte `abi.encodePacked(r, s, uint8(v))`, where `v` is either 27 or 28.
// If `s` is greater than `N / 2` then it will be converted to `N - s`
// and the `v` value will be flipped.
// If the signature has an invalid length, or if `v` is invalid,
// a uniquely corrupt hash will be returned.
// These functions are useful for "poor-mans-VRF".
/// @dev Returns the canonical hash of `signature`.
function canonicalHash(bytes memory signature) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let l := mload(signature)
for {} 1 {} {
mstore(0x00, mload(add(signature, 0x20))) // `r`.
let s := mload(add(signature, 0x40))
let v := mload(add(signature, 0x41))
if eq(l, 64) {
v := add(shr(255, s), 27)
s := shr(1, shl(1, s))
}
if iszero(lt(s, _HALF_N_PLUS_1)) {
v := xor(v, 7)
s := sub(N, s)
}
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
break
}
// If the length is neither 64 nor 65, return a uniquely corrupted hash.
if iszero(lt(sub(l, 64), 2)) {
// `bytes4(keccak256("InvalidSignatureLength"))`.
result := xor(keccak256(add(signature, 0x20), l), 0xd62f1ab2)
}
}
}
/// @dev Returns the canonical hash of `signature`.
function canonicalHashCalldata(bytes calldata signature)
internal
pure
returns (bytes32 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
mstore(0x00, calldataload(signature.offset)) // `r`.
let s := calldataload(add(signature.offset, 0x20))
let v := calldataload(add(signature.offset, 0x21))
if eq(signature.length, 64) {
v := add(shr(255, s), 27)
s := shr(1, shl(1, s))
}
if iszero(lt(s, _HALF_N_PLUS_1)) {
v := xor(v, 7)
s := sub(N, s)
}
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
break
}
// If the length is neither 64 nor 65, return a uniquely corrupted hash.
if iszero(lt(sub(signature.length, 64), 2)) {
calldatacopy(mload(0x40), signature.offset, signature.length)
// `bytes4(keccak256("InvalidSignatureLength"))`.
result := xor(keccak256(mload(0x40), signature.length), 0xd62f1ab2)
}
}
}
/// @dev Returns the canonical hash of `signature`.
function canonicalHash(bytes32 r, bytes32 vs) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, r) // `r`.
let v := add(shr(255, vs), 27)
let s := shr(1, shl(1, vs))
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
}
}
/// @dev Returns the canonical hash of `signature`.
function canonicalHash(uint8 v, bytes32 r, bytes32 s) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, r) // `r`.
if iszero(lt(s, _HALF_N_PLUS_1)) {
v := xor(v, 7)
s := sub(N, s)
}
mstore(0x21, v)
mstore(0x20, s)
result := keccak256(0x00, 0x41)
mstore(0x21, 0) // Restore the overwritten part of the free memory pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EMPTY CALLDATA HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns an empty calldata bytes.
function emptySignature() internal pure returns (bytes calldata signature) {
/// @solidity memory-safe-assembly
assembly {
signature.length := 0
}
}
}
lib/solady/src/utils/EIP712.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Contract for EIP-712 typed structured data hashing and signing.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/EIP712.sol)
/// @author Modified from Solbase (https://github.com/Sol-DAO/solbase/blob/main/src/utils/EIP712.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/EIP712.sol)
///
/// @dev Note, this implementation:
/// - Uses `address(this)` for the `verifyingContract` field.
/// - Does NOT use the optional EIP-712 salt.
/// - Does NOT use any EIP-712 extensions.
/// This is for simplicity and to save gas.
/// If you need to customize, please fork / modify accordingly.
abstract contract EIP712 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS AND IMMUTABLES */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev `keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")`.
bytes32 internal constant _DOMAIN_TYPEHASH =
0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev `keccak256("EIP712Domain(string name,string version,address verifyingContract)")`.
/// This is only used in `_hashTypedDataSansChainId`.
bytes32 internal constant _DOMAIN_TYPEHASH_SANS_CHAIN_ID =
0x91ab3d17e3a50a9d89e63fd30b92be7f5336b03b287bb946787a83a9d62a2766;
uint256 private immutable _cachedThis;
uint256 private immutable _cachedChainId;
bytes32 private immutable _cachedNameHash;
bytes32 private immutable _cachedVersionHash;
bytes32 private immutable _cachedDomainSeparator;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTRUCTOR */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Cache the hashes for cheaper runtime gas costs.
/// In the case of upgradeable contracts (i.e. proxies),
/// or if the chain id changes due to a hard fork,
/// the domain separator will be seamlessly calculated on-the-fly.
constructor() {
_cachedThis = uint256(uint160(address(this)));
_cachedChainId = block.chainid;
string memory name;
string memory version;
if (!_domainNameAndVersionMayChange()) (name, version) = _domainNameAndVersion();
bytes32 nameHash = _domainNameAndVersionMayChange() ? bytes32(0) : keccak256(bytes(name));
bytes32 versionHash =
_domainNameAndVersionMayChange() ? bytes32(0) : keccak256(bytes(version));
_cachedNameHash = nameHash;
_cachedVersionHash = versionHash;
bytes32 separator;
if (!_domainNameAndVersionMayChange()) {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), nameHash)
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
separator := keccak256(m, 0xa0)
}
}
_cachedDomainSeparator = separator;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* FUNCTIONS TO OVERRIDE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Please override this function to return the domain name and version.
/// ```
/// function _domainNameAndVersion()
/// internal
/// pure
/// virtual
/// returns (string memory name, string memory version)
/// {
/// name = "Solady";
/// version = "1";
/// }
/// ```
///
/// Note: If the returned result may change after the contract has been deployed,
/// you must override `_domainNameAndVersionMayChange()` to return true.
function _domainNameAndVersion()
internal
view
virtual
returns (string memory name, string memory version);
/// @dev Returns if `_domainNameAndVersion()` may change
/// after the contract has been deployed (i.e. after the constructor).
/// Default: false.
function _domainNameAndVersionMayChange() internal pure virtual returns (bool result) {}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HASHING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the EIP-712 domain separator.
function _domainSeparator() internal view virtual returns (bytes32 separator) {
if (_domainNameAndVersionMayChange()) {
separator = _buildDomainSeparator();
} else {
separator = _cachedDomainSeparator;
if (_cachedDomainSeparatorInvalidated()) separator = _buildDomainSeparator();
}
}
/// @dev Returns the hash of the fully encoded EIP-712 message for this domain,
/// given `structHash`, as defined in
/// https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct.
///
/// The hash can be used together with {ECDSA-recover} to obtain the signer of a message:
/// ```
/// bytes32 digest = _hashTypedData(keccak256(abi.encode(
/// keccak256("Mail(address to,string contents)"),
/// mailTo,
/// keccak256(bytes(mailContents))
/// )));
/// address signer = ECDSA.recover(digest, signature);
/// ```
function _hashTypedData(bytes32 structHash) internal view virtual returns (bytes32 digest) {
// We will use `digest` to store the domain separator to save a bit of gas.
if (_domainNameAndVersionMayChange()) {
digest = _buildDomainSeparator();
} else {
digest = _cachedDomainSeparator;
if (_cachedDomainSeparatorInvalidated()) digest = _buildDomainSeparator();
}
/// @solidity memory-safe-assembly
assembly {
// Compute the digest.
mstore(0x00, 0x1901000000000000) // Store "\x19\x01".
mstore(0x1a, digest) // Store the domain separator.
mstore(0x3a, structHash) // Store the struct hash.
digest := keccak256(0x18, 0x42)
// Restore the part of the free memory slot that was overwritten.
mstore(0x3a, 0)
}
}
/// @dev Variant of `_hashTypedData` that excludes the chain ID.
/// We expect that most contracts will use `_hashTypedData` as the main hash,
/// and `_hashTypedDataSansChainId` only occasionally for cross-chain workflows.
/// Thus this is optimized for smaller bytecode size over runtime gas.
function _hashTypedDataSansChainId(bytes32 structHash)
internal
view
virtual
returns (bytes32 digest)
{
(string memory name, string memory version) = _domainNameAndVersion();
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(0x00, _DOMAIN_TYPEHASH_SANS_CHAIN_ID)
mstore(0x20, keccak256(add(name, 0x20), mload(name)))
mstore(0x40, keccak256(add(version, 0x20), mload(version)))
mstore(0x60, address())
// Compute the digest.
mstore(0x20, keccak256(0x00, 0x80)) // Store the domain separator.
mstore(0x00, 0x1901) // Store "\x19\x01".
mstore(0x40, structHash) // Store the struct hash.
digest := keccak256(0x1e, 0x42)
mstore(0x40, m) // Restore the free memory pointer.
mstore(0x60, 0) // Restore the zero pointer.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EIP-5267 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev See: https://eips.ethereum.org/EIPS/eip-5267
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
fields = hex"0f"; // `0b01111`.
(name, version) = _domainNameAndVersion();
chainId = block.chainid;
verifyingContract = address(this);
salt = salt; // `bytes32(0)`.
extensions = extensions; // `new uint256[](0)`.
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PRIVATE HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the EIP-712 domain separator.
function _buildDomainSeparator() private view returns (bytes32 separator) {
// We will use `separator` to store the name hash to save a bit of gas.
bytes32 versionHash;
if (_domainNameAndVersionMayChange()) {
(string memory name, string memory version) = _domainNameAndVersion();
separator = keccak256(bytes(name));
versionHash = keccak256(bytes(version));
} else {
separator = _cachedNameHash;
versionHash = _cachedVersionHash;
}
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Load the free memory pointer.
mstore(m, _DOMAIN_TYPEHASH)
mstore(add(m, 0x20), separator) // Name hash.
mstore(add(m, 0x40), versionHash)
mstore(add(m, 0x60), chainid())
mstore(add(m, 0x80), address())
separator := keccak256(m, 0xa0)
}
}
/// @dev Returns if the cached domain separator has been invalidated.
function _cachedDomainSeparatorInvalidated() private view returns (bool result) {
uint256 cachedChainId = _cachedChainId;
uint256 cachedThis = _cachedThis;
/// @solidity memory-safe-assembly
assembly {
result := iszero(and(eq(chainid(), cachedChainId), eq(address(), cachedThis)))
}
}
}
lib/solady/src/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {CallContextChecker} from "./CallContextChecker.sol";
/// @notice UUPS proxy mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/UUPSUpgradeable.sol)
/// @author Modified from OpenZeppelin
/// (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/utils/UUPSUpgradeable.sol)
///
/// @dev Note:
/// - This implementation is intended to be used with ERC1967 proxies.
/// See: `LibClone.deployERC1967` and related functions.
/// - This implementation is NOT compatible with legacy OpenZeppelin proxies
/// which do not store the implementation at `_ERC1967_IMPLEMENTATION_SLOT`.
abstract contract UUPSUpgradeable is CallContextChecker {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The upgrade failed.
error UpgradeFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Emitted when the proxy's implementation is upgraded.
event Upgraded(address indexed implementation);
/// @dev `keccak256(bytes("Upgraded(address)"))`.
uint256 private constant _UPGRADED_EVENT_SIGNATURE =
0xbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ERC-1967 storage slot for the implementation in the proxy.
/// `uint256(keccak256("eip1967.proxy.implementation")) - 1`.
bytes32 internal constant _ERC1967_IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* UUPS OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Please override this function to check if `msg.sender` is authorized
/// to upgrade the proxy to `newImplementation`, reverting if not.
/// ```
/// function _authorizeUpgrade(address) internal override onlyOwner {}
/// ```
function _authorizeUpgrade(address newImplementation) internal virtual;
/// @dev Returns the storage slot used by the implementation,
/// as specified in [ERC1822](https://eips.ethereum.org/EIPS/eip-1822).
///
/// Note: The `notDelegated` modifier prevents accidental upgrades to
/// an implementation that is a proxy contract.
function proxiableUUID() public view virtual notDelegated returns (bytes32) {
// This function must always return `_ERC1967_IMPLEMENTATION_SLOT` to comply with ERC1967.
return _ERC1967_IMPLEMENTATION_SLOT;
}
/// @dev Upgrades the proxy's implementation to `newImplementation`.
/// Emits a {Upgraded} event.
///
/// Note: Passing in empty `data` skips the delegatecall to `newImplementation`.
function upgradeToAndCall(address newImplementation, bytes calldata data)
public
payable
virtual
onlyProxy
{
_authorizeUpgrade(newImplementation);
/// @solidity memory-safe-assembly
assembly {
newImplementation := shr(96, shl(96, newImplementation)) // Clears upper 96 bits.
mstore(0x00, returndatasize())
mstore(0x01, 0x52d1902d) // `proxiableUUID()`.
let s := _ERC1967_IMPLEMENTATION_SLOT
// Check if `newImplementation` implements `proxiableUUID` correctly.
if iszero(eq(mload(staticcall(gas(), newImplementation, 0x1d, 0x04, 0x01, 0x20)), s)) {
mstore(0x01, 0x55299b49) // `UpgradeFailed()`.
revert(0x1d, 0x04)
}
// Emit the {Upgraded} event.
log2(codesize(), 0x00, _UPGRADED_EVENT_SIGNATURE, newImplementation)
sstore(s, newImplementation) // Updates the implementation.
// Perform a delegatecall to `newImplementation` if `data` is non-empty.
if data.length {
// Forwards the `data` to `newImplementation` via delegatecall.
let m := mload(0x40)
calldatacopy(m, data.offset, data.length)
if iszero(delegatecall(gas(), newImplementation, m, data.length, codesize(), 0x00))
{
// Bubble up the revert if the call reverts.
returndatacopy(m, 0x00, returndatasize())
revert(m, returndatasize())
}
}
}
}
}
src/core/AllStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IAllStorage} from '../interfaces/core/IAllStorage.sol';
/// @title Startale - Storage
/// @notice Manages isolated storage spaces for Modular Smart Account in compliance with ERC-7201 standard to ensure collision-resistant storage.
/// @dev Implements the ERC-7201 namespaced storage pattern to maintain secure and isolated storage sections for different states within Startale suite.
/// @author Startale Labs
contract AllStorage is IAllStorage {
/// @custom:storage-location erc7201:startale.account.storage
/// ERC-7201 namespaced via `keccak256(abi.encode(uint256(keccak256(bytes("startale.account.storage"))) - 1)) & ~bytes32(uint256(0xff));`
bytes32 private constant _STORAGE_LOCATION = 0x9195d48440658ac27f13a7bd256a2e74da1f2416f468d66228b37e6ac4790c00;
/// @dev Utilizes ERC-7201's namespaced storage pattern for isolated storage access. This method computes
/// the storage slot based on a predetermined location, ensuring collision-resistant storage for contract states.
/// @custom:storage-location ERC-7201 formula applied to "startale.account.storage", facilitating unique
/// namespace identification and storage segregation, as detailed in the specification.
/// @return $ The proxy to the `AccountStorage` struct, providing a reference to the namespaced storage slot.
function _getAccountStorage() internal pure returns (AccountStorage storage $) {
assembly {
$.slot := _STORAGE_LOCATION
}
}
}
src/core/BaseAccount.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IBaseAccount} from '../interfaces/core/IBaseAccount.sol';
import {IEntryPoint} from '@account-abstraction/interfaces/IEntryPoint.sol';
/// @title BaseAccount
/// @notice Implements ERC-4337 and ERC-7579 standards for account management and access control.
/// @dev Manages entry points and configurations as specified in the ERC-4337 and ERC-7579 documentation.
/// @author Startale Labs
/// Special thanks to the Biconomy team for https://github.com/bcnmy/nexus/ and ERC7579 reference implementation on which this implementation is highly based on.
contract BaseAccount is IBaseAccount {
/// @notice Identifier for this implementation on the network
string internal constant _ACCOUNT_IMPLEMENTATION_ID = 'startale.smart-account.1.0.0';
/// @notice The canonical address for the ERC4337 EntryPoint contract, version 0.7.
/// This address is consistent across all supported networks.
address internal immutable _ENTRYPOINT;
/// @dev Ensures the caller is either the EntryPoint or this account itself.
/// Reverts with AccountAccessUnauthorized if the check fails.
modifier onlyEntryPointOrSelf() {
require(msg.sender == _ENTRYPOINT || msg.sender == address(this), AccountAccessUnauthorized());
_;
}
/// @dev Ensures the caller is the EntryPoint.
/// Reverts with AccountAccessUnauthorized if the check fails.
modifier onlyEntryPoint() {
require(msg.sender == _ENTRYPOINT, AccountAccessUnauthorized());
_;
}
/// @dev Sends to the EntryPoint (i.e. `msg.sender`) the missing funds for this transaction.
/// Subclass MAY override this modifier for better funds management.
/// (e.g. send to the EntryPoint more than the minimum required, so that in future transactions
/// it will not be required to send again)
///
/// `missingAccountFunds` is the minimum value this modifier should send the EntryPoint,
/// which MAY be zero, in case there is enough deposit, or the userOp has a paymaster.
modifier payPrefund(uint256 missingAccountFunds) virtual {
_;
/// @solidity memory-safe-assembly
assembly {
if missingAccountFunds {
// Ignore failure (it's EntryPoint's job to verify, not the account's).
pop(call(gas(), caller(), missingAccountFunds, 0, 0, 0, 0))
}
}
}
/// @notice Adds deposit to the EntryPoint to fund transactions.
function addDeposit() external payable virtual {
address entryPointAddress = _ENTRYPOINT;
/// @solidity memory-safe-assembly
assembly {
// The EntryPoint has balance accounting logic in the `receive()` function.
if iszero(call(gas(), entryPointAddress, callvalue(), codesize(), 0x00, codesize(), 0x00)) {
revert(codesize(), 0x00)
} // For gas estimation.
}
}
/// @notice Withdraws ETH from the EntryPoint to a specified address.
/// @param to The address to receive the withdrawn funds.
/// @param amount The amount to withdraw.
function withdrawDepositTo(address to, uint256 amount) external payable virtual onlyEntryPointOrSelf {
address entryPointAddress = _ENTRYPOINT;
assembly {
let freeMemPtr := mload(0x40) // Store the free memory pointer.
mstore(freeMemPtr, shl(224, 0x205c2878)) // `withdrawTo(address,uint256)` selector
mstore(add(freeMemPtr, 0x04), to) // Store the `to` argument.
mstore(add(freeMemPtr, 0x24), amount) // Store the `amount` argument.
if iszero(call(gas(), entryPointAddress, 0, freeMemPtr, 0x44, 0, 0)) {
let rdsize := returndatasize()
returndatacopy(freeMemPtr, 0, rdsize)
revert(freeMemPtr, rdsize)
}
// Update the free memory pointer (ptr + 0x44)
mstore(0x40, add(freeMemPtr, 0x44))
}
}
/// @notice Gets the nonce for a particular key.
/// @param key The nonce key.
/// @return The nonce associated with the key.
function nonce(uint192 key) external view virtual returns (uint256) {
return IEntryPoint(_ENTRYPOINT).getNonce(address(this), key);
}
/// @notice Returns the current deposit balance of this account on the EntryPoint.
/// @return result The current balance held at the EntryPoint.
function getDeposit() external view virtual returns (uint256 result) {
address entryPointAddress = _ENTRYPOINT;
/// @solidity memory-safe-assembly
assembly {
mstore(0x20, address()) // Store the `account` argument.
mstore(0x00, 0x70a08231) // `balanceOf(address)`.
result :=
mul(
// Returns 0 if the EntryPoint does not exist.
mload(0x20),
and(
// The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), entryPointAddress, 0x1c, 0x24, 0x20, 0x20)
)
)
}
}
/// @notice Retrieves the address of the EntryPoint contract, currently using version 0.7.
/// @dev This function returns the address of the canonical ERC4337 EntryPoint contract.
/// It can be overridden to return a different EntryPoint address if needed.
/// @return The address of the EntryPoint contract.
function entryPoint() external view returns (address) {
return _ENTRYPOINT;
}
}
src/core/ERC7779Adapter.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IERC7779} from '../interfaces/IERC7779.sol';
abstract contract ERC7779Adapter is IERC7779 {
error NonAuthorizedOnRedelegationCaller();
// keccak256(abi.encode(uint256(keccak256(bytes("InteroperableDelegatedAccount.ERC.Storage"))) -
// 1)) & ~bytes32(uint256(0xff));
bytes32 internal constant ERC7779_STORAGE_BASE = 0xc473de86d0138e06e4d4918a106463a7cc005258d2e21915272bcb4594c18900;
struct ERC7779Storage {
bytes32[] storageBases;
}
/*
* @dev Externally shares the storage bases that has been used throughout the account.
* Majority of 7702 accounts will have their distinctive storage base to reduce the
chance of storage collision.
* This allows the external entities to know what the storage base is of the account.
* Wallets willing to redelegate already-delegated accounts should call
accountStorageBase() to check if it confirms with the account it plans to redelegate.
*
* The bytes32 array should be stored at the storage slot:
keccak(keccak('InteroperableDelegatedAccount.ERC.Storage')-1) & ~0xff
* This is an append-only array so newly redelegated accounts should not overwrite the
storage at this slot, but just append their base to the array.
* This append operation should be done during the initialization of the account.
*/
function accountStorageBases() external view returns (bytes32[] memory) {
ERC7779Storage storage $;
assembly {
$.slot := ERC7779_STORAGE_BASE
}
return $.storageBases;
}
function _addStorageBase(bytes32 storageBase) internal {
ERC7779Storage storage $;
assembly {
$.slot := ERC7779_STORAGE_BASE
}
// Check if the storageBase already exists to avoid duplication
for (uint256 i = 0; i < $.storageBases.length; i++) {
if ($.storageBases[i] == storageBase) {
return; // Exit if the storageBase is already present
}
}
$.storageBases.push(storageBase);
}
/*
* @dev Function called before redelegation.
* This function should prepare the account for a delegation to a different
implementation.
* This function could be triggered by the new wallet that wants to redelegate an already
delegated EOA.
* It should uninitialize storages if needed and execute wallet-specific logic to prepare
for redelegation.
* msg.sender should be the owner of the account.
*/
function onRedelegation() external returns (bool) {
require(msg.sender == address(this), NonAuthorizedOnRedelegationCaller());
_onRedelegation();
return true;
}
/// @dev This function is called before redelegation.
/// @dev Account should override this function to implement the specific logic.
function _onRedelegation() internal virtual;
}
src/core/ExecutionHelper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IExecutionHelper} from '../interfaces/core/IExecutionHelper.sol';
import {ExecutionLib} from '../lib/ExecutionLib.sol';
import {EXECTYPE_DEFAULT, EXECTYPE_TRY, ExecType} from '../lib/ModeLib.sol';
import {Execution} from '../types/Structs.sol';
/// @title ExecutionHelper
/// @dev This contract executes calls in the context of this contract.
/// @author Startale Labs
abstract contract ExecutionHelper is IExecutionHelper {
using ExecutionLib for bytes;
/// @notice Executes a call to a target address with specified value and data.
/// @notice calls to an EOA should be counted as successful.
/// @param target The address to execute the call on.
/// @param value The amount of wei to send with the call.
/// @param callData The calldata to send.
/// @return result The bytes returned from the execution, which contains the returned data from the target address.
function _execute(
address target,
uint256 value,
bytes calldata callData
) internal virtual returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
calldatacopy(result, callData.offset, callData.length)
if iszero(call(gas(), target, value, result, callData.length, codesize(), 0x00)) {
// Bubble up the revert if the call reverts.
returndatacopy(result, 0x00, returndatasize())
revert(result, returndatasize())
}
mstore(result, returndatasize()) // Store the length.
let o := add(result, 0x20)
returndatacopy(o, 0x00, returndatasize()) // Copy the returndata.
mstore(0x40, add(o, returndatasize())) // Allocate the memory.
}
}
/// @notice Executes a call to a target address with specified value and data.
/// Same as _execute but without return data for gas optimization.
function _executeNoReturndata(address target, uint256 value, bytes calldata callData) internal virtual {
/// @solidity memory-safe-assembly
assembly {
let result := mload(0x40)
calldatacopy(result, callData.offset, callData.length)
if iszero(call(gas(), target, value, result, callData.length, codesize(), 0x00)) {
// Bubble up the revert if the call reverts.
returndatacopy(result, 0x00, returndatasize())
revert(result, returndatasize())
}
mstore(0x40, add(result, callData.length)) //allocate memory
}
}
/// @notice Tries to execute a call and captures if it was successful or not.
/// @dev Similar to _execute but returns a success boolean and catches reverts instead of propagating them.
/// @notice calls to an EOA should be counted as successful.
/// @param target The address to execute the call on.
/// @param value The amount of wei to send with the call.
/// @param callData The calldata to send.
/// @return success True if the execution was successful, false otherwise.
/// @return result The bytes returned from the execution, which contains the returned data from the target address.
function _tryExecute(
address target,
uint256 value,
bytes calldata callData
) internal virtual returns (bool success, bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
calldatacopy(result, callData.offset, callData.length)
success := call(gas(), target, value, result, callData.length, codesize(), 0x00)
mstore(result, returndatasize()) // Store the length.
let o := add(result, 0x20)
returndatacopy(o, 0x00, returndatasize()) // Copy the returndata.
mstore(0x40, add(o, returndatasize())) // Allocate the memory.
}
}
/// @notice Executes a batch of calls.
/// @param executions An array of Execution structs each containing target, value, and calldata.
/// @return result An array of bytes returned from each executed call, corresponding to the returndata from each target address.
function _executeBatch(Execution[] calldata executions) internal returns (bytes[] memory result) {
result = new bytes[](executions.length);
Execution calldata exec;
for (uint256 i; i < executions.length; i++) {
exec = executions[i];
result[i] = _execute(exec.target, exec.value, exec.callData);
}
}
/// @notice Executes a batch of calls without returning the result.
/// @param executions An array of Execution structs each containing target, value, and calldata.
function _executeBatchNoReturndata(Execution[] calldata executions) internal {
Execution calldata exec;
for (uint256 i; i < executions.length; i++) {
exec = executions[i];
_executeNoReturndata(exec.target, exec.value, exec.callData);
}
}
/// @notice Tries to execute a batch of calls and emits an event for each unsuccessful call.
/// @param executions An array of Execution structs.
/// @return result An array of bytes returned from each executed call, with unsuccessful calls marked by events.
function _tryExecuteBatch(Execution[] calldata executions) internal returns (bytes[] memory result) {
result = new bytes[](executions.length);
Execution calldata exec;
for (uint256 i; i < executions.length; i++) {
exec = executions[i];
bool success;
(success, result[i]) = _tryExecute(exec.target, exec.value, exec.callData);
if (!success) emit TryExecuteUnsuccessful(exec.target, exec.callData, result[i]);
}
}
/// @dev Execute a delegatecall with `delegate` on this account.
/// @return result The bytes returned from the delegatecall, which contains the returned data from the delegate contract.
function _executeDelegatecall(address delegate, bytes calldata callData) internal returns (bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
calldatacopy(result, callData.offset, callData.length)
// Forwards the `data` to `delegate` via delegatecall.
if iszero(delegatecall(gas(), delegate, result, callData.length, codesize(), 0x00)) {
// Bubble up the revert if the call reverts.
returndatacopy(result, 0x00, returndatasize())
revert(result, returndatasize())
}
mstore(result, returndatasize()) // Store the length.
let o := add(result, 0x20)
returndatacopy(o, 0x00, returndatasize()) // Copy the returndata.
mstore(0x40, add(o, returndatasize())) // Allocate the memory.
}
}
/// @dev Execute a delegatecall with `delegate` on this account.
/// Same as _executeDelegatecall but without return data for gas optimization.
function _executeDelegatecallNoReturndata(address delegate, bytes calldata callData) internal {
/// @solidity memory-safe-assembly
assembly {
let result := mload(0x40)
calldatacopy(result, callData.offset, callData.length)
if iszero(delegatecall(gas(), delegate, result, callData.length, codesize(), 0x00)) {
// Bubble up the revert if the call reverts.
returndatacopy(result, 0x00, returndatasize())
revert(result, returndatasize())
}
mstore(0x40, add(result, callData.length)) //allocate memory
}
}
/// @dev Execute a delegatecall with `delegate` on this account and catch reverts.
/// @return success True if the delegatecall was successful, false otherwise.
/// @return result The bytes returned from the delegatecall, which contains the returned data from the delegate contract.
function _tryExecuteDelegatecall(
address delegate,
bytes calldata callData
) internal returns (bool success, bytes memory result) {
/// @solidity memory-safe-assembly
assembly {
result := mload(0x40)
calldatacopy(result, callData.offset, callData.length)
// Forwards the `data` to `delegate` via delegatecall.
success := delegatecall(gas(), delegate, result, callData.length, codesize(), 0x00)
mstore(result, returndatasize()) // Store the length.
let o := add(result, 0x20)
returndatacopy(o, 0x00, returndatasize()) // Copy the returndata.
mstore(0x40, add(o, returndatasize())) // Allocate the memory.
}
}
/// @dev Executes a single transaction based on the specified execution type.
/// @param executionCalldata The calldata containing the transaction details (target address, value, and data).
/// @param execType The execution type, which can be DEFAULT (revert on failure) or TRY (return on failure).
function _handleSingleExecution(bytes calldata executionCalldata, ExecType execType) internal {
(address target, uint256 value, bytes calldata callData) = executionCalldata.decodeSingle();
if (execType == EXECTYPE_DEFAULT) {
_executeNoReturndata(target, value, callData);
} else if (execType == EXECTYPE_TRY) {
(bool success, bytes memory result) = _tryExecute(target, value, callData);
if (!success) emit TryExecuteUnsuccessful(target, callData, result);
} else {
revert UnsupportedExecType(execType);
}
}
/// @dev Executes a batch of transactions based on the specified execution type.
/// @param executionCalldata The calldata for a batch of transactions.
/// @param execType The execution type, which can be DEFAULT (revert on failure) or TRY (return on failure).
function _handleBatchExecution(bytes calldata executionCalldata, ExecType execType) internal {
Execution[] calldata executions = executionCalldata.decodeBatch();
if (execType == EXECTYPE_DEFAULT) _executeBatchNoReturndata(executions);
else if (execType == EXECTYPE_TRY) _tryExecuteBatch(executions);
else revert UnsupportedExecType(execType);
}
/// @dev Executes a single transaction based on the specified execution type.
/// @param executionCalldata The calldata containing the transaction details (target address, value, and data).
/// @param execType The execution type, which can be DEFAULT (revert on failure) or TRY (return on failure).
function _handleDelegateCallExecution(bytes calldata executionCalldata, ExecType execType) internal {
(address delegate, bytes calldata callData) = executionCalldata.decodeDelegateCall();
if (execType == EXECTYPE_DEFAULT) {
_executeDelegatecallNoReturndata(delegate, callData);
} else if (execType == EXECTYPE_TRY) {
(bool success, bytes memory result) = _tryExecuteDelegatecall(delegate, callData);
if (!success) emit TryDelegateCallUnsuccessful(callData, result);
} else {
revert UnsupportedExecType(execType);
}
}
/// @dev Executes a single transaction based on the specified execution type.
/// @param executionCalldata The calldata containing the transaction details (target address, value, and data).
/// @param execType The execution type, which can be DEFAULT (revert on failure) or TRY (return on failure).
/// @return returnData An array containing the execution result. In the case of a single transaction, the array contains one element.
function _handleSingleExecutionAndReturnData(
bytes calldata executionCalldata,
ExecType execType
) internal returns (bytes[] memory returnData) {
(address target, uint256 value, bytes calldata callData) = executionCalldata.decodeSingle();
returnData = new bytes[](1);
bool success;
// check if execType is revert(default) or try
if (execType == EXECTYPE_DEFAULT) {
returnData[0] = _execute(target, value, callData);
} else if (execType == EXECTYPE_TRY) {
(success, returnData[0]) = _tryExecute(target, value, callData);
if (!success) emit TryExecuteUnsuccessful(target, callData, returnData[0]);
} else {
revert UnsupportedExecType(execType);
}
}
/// @dev Executes a batch of transactions based on the specified execution type.
/// @param executionCalldata The calldata for a batch of transactions.
/// @param execType The execution type, which can be DEFAULT (revert on failure) or TRY (return on failure).
/// @return returnData An array containing the execution results for each transaction in the batch.
function _handleBatchExecutionAndReturnData(
bytes calldata executionCalldata,
ExecType execType
) internal returns (bytes[] memory returnData) {
Execution[] calldata executions = executionCalldata.decodeBatch();
if (execType == EXECTYPE_DEFAULT) returnData = _executeBatch(executions);
else if (execType == EXECTYPE_TRY) returnData = _tryExecuteBatch(executions);
else revert UnsupportedExecType(execType);
}
/// @dev Executes a single transaction based on the specified execution type.
/// @param executionCalldata The calldata containing the transaction details (target address, value, and data).
/// @param execType The execution type, which can be DEFAULT (revert on failure) or TRY (return on failure).
/// @return returnData An array containing the result of the delegatecall execution.
function _handleDelegateCallExecutionAndReturnData(
bytes calldata executionCalldata,
ExecType execType
) internal returns (bytes[] memory returnData) {
(address delegate, bytes calldata callData) = executionCalldata.decodeDelegateCall();
returnData = new bytes[](1);
bool success;
if (execType == EXECTYPE_DEFAULT) {
returnData[0] = _executeDelegatecall(delegate, callData);
} else if (execType == EXECTYPE_TRY) {
(success, returnData[0]) = _tryExecuteDelegatecall(delegate, callData);
if (!success) emit TryDelegateCallUnsuccessful(callData, returnData[0]);
} else {
revert UnsupportedExecType(execType);
}
}
}
src/core/ModuleManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {
IExecutor,
IFallback,
IHook,
IModule,
IPreValidationHookERC1271,
IPreValidationHookERC4337,
IValidator
} from '../interfaces/IERC7579Module.sol';
import {IModuleManager} from '../interfaces/core/IModuleManager.sol';
import {DataParserLib} from '../lib/DataParserLib.sol';
import {ExecutionLib} from '../lib/ExecutionLib.sol';
import {CALLTYPE_SINGLE, CALLTYPE_STATIC, CallType} from '../lib/ModeLib.sol';
import {
EMERGENCY_UNINSTALL_TYPE_HASH,
ERC1271_MAGICVALUE,
MODULE_ENABLE_MODE_TYPE_HASH,
MODULE_TYPE_EXECUTOR,
MODULE_TYPE_FALLBACK,
MODULE_TYPE_HOOK,
MODULE_TYPE_MULTI,
MODULE_TYPE_PREVALIDATION_HOOK_ERC1271,
MODULE_TYPE_PREVALIDATION_HOOK_ERC4337,
MODULE_TYPE_VALIDATOR
} from '../types/Constants.sol';
import {EmergencyUninstall} from '../types/Structs.sol';
import {SENTINEL} from 'sentinellist/SentinelList.sol';
import {AllStorage} from './AllStorage.sol';
import {PackedUserOperation} from '@account-abstraction/interfaces/PackedUserOperation.sol';
import {ExcessivelySafeCall} from 'excessively-safe-call/ExcessivelySafeCall.sol';
import {SentinelListLib} from 'sentinellist/SentinelList.sol';
import {ECDSA} from 'solady/utils/ECDSA.sol';
import {EIP712} from 'solady/utils/EIP712.sol';
/// @title ModuleManager
/// @notice Manages Validator, Executor, Hook, and Fallback modules
/// @dev Implements SentinelList for managing modules via a linked list structure, adhering to ERC-7579.
/// Special thanks to the Biconomy team for https://github.com/bcnmy/nexus/ and ERC7579 reference implementation on which this implementation is highly based on.
/// Special thanks to the Solady team for foundational contributions: https://github.com/Vectorized/solady
abstract contract ModuleManager is AllStorage, EIP712, IModuleManager {
using SentinelListLib for SentinelListLib.SentinelList;
using DataParserLib for bytes;
using ExecutionLib for address;
using ExcessivelySafeCall for address;
using ECDSA for bytes32;
/// @dev The default validator address.
/// @notice To explicitly initialize the default validator, StartaleSmartAccount.execute(_DEFAULT_VALIDATOR.onInstall(...)) should be called.
address internal immutable _DEFAULT_VALIDATOR;
/// @dev initData should block the implementation from being used as a Smart Account
constructor(address _defaultValidator, bytes memory _initData) {
if (!IValidator(_defaultValidator).isModuleType(MODULE_TYPE_VALIDATOR)) {
revert MismatchModuleTypeId();
}
IValidator(_defaultValidator).onInstall(_initData);
_DEFAULT_VALIDATOR = _defaultValidator;
}
/// @notice Ensures the message sender is a registered executor module.
modifier onlyExecutorModule() virtual {
require(_getAccountStorage().executors.contains(msg.sender), InvalidModule(msg.sender));
_;
}
/// @notice Does pre-checks and post-checks using an installed hook on the account.
/// @dev sender, msg.data and msg.value is passed to the hook to implement custom flows.
modifier withHook() {
address hook = _getHook();
if (hook == address(0)) {
_;
} else {
bytes memory hookData = IHook(hook).preCheck(msg.sender, msg.value, msg.data);
_;
IHook(hook).postCheck(hookData);
}
}
receive() external payable {}
/// @dev Fallback function to manage incoming calls using designated handlers based on the call type.
/// Hooked manually in the _fallback function
fallback() external payable {
_fallback(msg.data);
}
/// @dev Retrieves a paginated list of validator addresses from the linked list.
/// This utility function is not defined by the ERC-7579 standard and is implemented to facilitate
/// easier management and retrieval of large sets of validator modules.
/// @param cursor The address to start pagination from, or zero to start from the first entry.
/// @param size The number of validator addresses to return.
/// @return array An array of validator addresses.
/// @return next The address to use as a cursor for the next page of results.
function getValidatorsPaginated(
address cursor,
uint256 size
) external view returns (address[] memory array, address next) {
(array, next) = _paginate(_getAccountStorage().validators, cursor, size);
}
/// @dev Retrieves a paginated list of executor addresses from the linked list.
/// This utility function is not defined by the ERC-7579 standard and is implemented to facilitate
/// easier management and retrieval of large sets of executor modules.
/// @param cursor The address to start pagination from, or zero to start from the first entry.
/// @param size The number of executor addresses to return.
/// @return array An array of executor addresses.
/// @return next The address to use as a cursor for the next page of results.
function getExecutorsPaginated(
address cursor,
uint256 size
) external view returns (address[] memory array, address next) {
(array, next) = _paginate(_getAccountStorage().executors, cursor, size);
}
/// @notice Retrieves the currently active hook address.
/// @return hook The address of the active hook module.
function getActiveHook() external view returns (address hook) {
return _getHook();
}
/// @notice Fetches the fallback handler for a specific selector.
/// @param selector The function selector to query.
/// @return calltype The type of call that the handler manages.
/// @return handler The address of the fallback handler.
function getFallbackHandlerBySelector(bytes4 selector) external view returns (CallType, address) {
FallbackHandler memory handler = _getAccountStorage().fallbacks[selector];
return (handler.calltype, handler.handler);
}
/// @dev Initializes the module manager by setting up default states for validators and executors.
function _initSentinelLists() internal virtual {
// account module storage
AccountStorage storage ams = _getAccountStorage();
ams.executors.init();
ams.validators.init();
}
/// @dev Implements Module Enable Mode flow.
/// @param packedData Data source to parse data required to perform Module Enable mode from.
/// @return userOpSignature the clean signature which can be further used for userOp validation
function _enableMode(bytes32 userOpHash, bytes calldata packedData) internal returns (bytes calldata userOpSignature) {
address module;
uint256 moduleType;
bytes calldata moduleInitData;
bytes calldata enableModeSignature;
(module, moduleType, moduleInitData, enableModeSignature, userOpSignature) = packedData.parseEnableModeData();
address enableModeSigValidator = _handleValidator(address(bytes20(enableModeSignature[0:20])));
enableModeSignature = enableModeSignature[20:];
if (
!_checkEnableModeSignature({
structHash: _getEnableModeDataHash(module, moduleType, userOpHash, moduleInitData),
sig: enableModeSignature,
validator: enableModeSigValidator
})
) {
revert EnableModeSigError();
}
this.installModule{value: msg.value}(moduleType, module, moduleInitData);
}
/// @notice Installs a new module to the smart account.
/// @param moduleTypeId The type identifier of the module being installed, which determines its role:
/// - 0 for MultiType
/// - 1 for Validator
/// - 2 for Executor
/// - 3 for Fallback
/// - 4 for Hook
/// - 8 for PreValidationHookERC1271
/// - 9 for PreValidationHookERC4337
/// @param module The address of the module to install.
/// @param initData Initialization data for the module.
/// @dev This function goes through hook checks via withHook modifier.
/// @dev No need to check that the module is already installed, as this check is done
/// when trying to sstore the module in an appropriate SentinelList
function _installModule(uint256 moduleTypeId, address module, bytes calldata initData) internal {
if (!_areSentinelListsInitialized()) {
_initSentinelLists();
}
if (module == address(0)) revert ModuleAddressCanNotBeZero();
if (moduleTypeId == MODULE_TYPE_VALIDATOR) {
_installValidator(module, initData);
} else if (moduleTypeId == MODULE_TYPE_EXECUTOR) {
_installExecutor(module, initData);
} else if (moduleTypeId == MODULE_TYPE_FALLBACK) {
_installFallbackHandler(module, initData);
} else if (moduleTypeId == MODULE_TYPE_HOOK) {
_installHook(module, initData);
} else if (
moduleTypeId == MODULE_TYPE_PREVALIDATION_HOOK_ERC1271 || moduleTypeId == MODULE_TYPE_PREVALIDATION_HOOK_ERC4337
) {
_installPreValidationHook(moduleTypeId, module, initData);
} else if (moduleTypeId == MODULE_TYPE_MULTI) {
_multiTypeInstall(module, initData);
} else {
revert InvalidModuleTypeId(moduleTypeId);
}
}
/// @dev Installs a new validator module after checking if it matches the required module type.
/// @param validator The address of the validator module to be installed.
/// @param data Initialization data to configure the validator upon installation.
function _installValidator(address validator, bytes calldata data) internal virtual withHook {
if (!IValidator(validator).isModuleType(MODULE_TYPE_VALIDATOR)) revert MismatchModuleTypeId();
if (validator == _DEFAULT_VALIDATOR) {
revert DefaultValidatorAlreadyInstalled();
}
_getAccountStorage().validators.push(validator);
if (data.length > 0) {
IValidator(validator).onInstall(data);
}
}
/// @dev Uninstalls a validator module
/// @param validator The address of the validator to be uninstalled.
/// @param data De-initialization data to configure the validator upon uninstallation.
function _uninstallValidator(address validator, bytes calldata data) internal virtual {
SentinelListLib.SentinelList storage validators = _getAccountStorage().validators;
(address prev, bytes memory disableModuleData) = abi.decode(data, (address, bytes));
// Perform the removal first
validators.pop(prev, validator);
(bool success, bytes memory returnData) = validator.excessivelySafeCall(
gasleft(), 0, 0, abi.encodeWithSelector(IModule.onUninstall.selector, disableModuleData)
);
if (!success) {
emit ExternalCallFailed(
validator, abi.encodeWithSelector(IModule.onUninstall.selector, disableModuleData), returnData
);
}
}
/// @dev Uninstalls all validators from the smart account.
/// @dev This function is called in the _onRedelegation function in StartaleSmartAccount.sol
function _uninstallAllValidators() internal {
SentinelListLib.SentinelList storage $valdiators = _getAccountStorage().validators;
$valdiators.popAll();
}
/// @dev Installs a new executor module after checking if it matches the required module type.
/// @param executor The address of the executor module to be installed.
/// @param data Initialization data to configure the executor upon installation.
function _installExecutor(address executor, bytes calldata data) internal virtual withHook {
if (!IExecutor(executor).isModuleType(MODULE_TYPE_EXECUTOR)) revert MismatchModuleTypeId();
_getAccountStorage().executors.push(executor);
if (data.length > 0) {
IExecutor(executor).onInstall(data);
}
}
/// @dev Uninstalls an executor module by removing it from the executors list.
/// @param executor The address of the executor to be uninstalled.
/// @param data De-initialization data to configure the executor upon uninstallation.
function _uninstallExecutor(address executor, bytes calldata data) internal virtual {
(address prev, bytes memory disableModuleData) = abi.decode(data, (address, bytes));
_getAccountStorage().executors.pop(prev, executor);
(bool success, bytes memory returnData) = executor.excessivelySafeCall(
gasleft(), 0, 0, abi.encodeWithSelector(IModule.onUninstall.selector, disableModuleData)
);
if (!success) {
emit ExternalCallFailed(
executor, abi.encodeWithSelector(IModule.onUninstall.selector, disableModuleData), returnData
);
}
}
/// @dev Uninstalls all executors from the smart account.
/// @dev This function is called in the _onRedelegation function in StartaleSmartAccount.sol
function _uninstallAllExecutors() internal {
SentinelListLib.SentinelList storage $executors = _getAccountStorage().executors;
$executors.popAll();
}
/// @dev Installs a hook module, ensuring no other hooks are installed before proceeding.
/// @param hook The address of the hook to be installed.
/// @param data Initialization data to configure the hook upon installation.
function _installHook(address hook, bytes calldata data) internal virtual withHook {
if (!IHook(hook).isModuleType(MODULE_TYPE_HOOK)) revert MismatchModuleTypeId();
address currentHook = _getHook();
require(currentHook == address(0), HookAlreadyInstalled(currentHook));
_setHook(hook);
if (data.length > 0) {
IHook(hook).onInstall(data);
}
}
/// @dev Uninstalls a hook module, ensuring the current hook matches the one intended for uninstallation.
/// @param hook The address of the hook to be uninstalled.
/// @param hookType The type of the hook to be uninstalled.
/// @param data De-initialization data to configure the hook upon uninstallation.
function _uninstallHook(address hook, uint256 hookType, bytes calldata data) internal virtual {
if (hookType == MODULE_TYPE_HOOK) {
_setHook(address(0));
} else if (hookType == MODULE_TYPE_PREVALIDATION_HOOK_ERC1271 || hookType == MODULE_TYPE_PREVALIDATION_HOOK_ERC4337)
{
_uninstallPreValidationHook(hook, hookType, data);
}
(bool success, bytes memory returnData) =
hook.excessivelySafeCall(gasleft(), 0, 0, abi.encodeWithSelector(IModule.onUninstall.selector, data));
if (!success) {
emit ExternalCallFailed(hook, abi.encodeWithSelector(IModule.onUninstall.selector, data), returnData);
}
}
/// @dev Uninstalls a hook module.
/// @param hook The address of the hook to be uninstalled.
function _uninstallHook(address hook) internal virtual {
if (hook != address(0)) {
_setHook(address(0));
}
}
function _uninstallAllFallbacks() internal {
AccountStorage storage ds = _getAccountStorage();
uint256 len = ds.fallbackSelectors.length;
for (uint256 i = 0; i < len; i++) {
bytes4 selector = ds.fallbackSelectors[i];
ds.fallbacks[selector] = FallbackHandler(address(0), CallType.wrap(0x00));
}
delete ds.fallbackSelectors;
}
/// @dev Uninstalls all interfaces from the smart account.
/// @dev This function is called in the _onRedelegation function in StartaleSmartAccount.sol
/// @notice clears all the storage variables related to interfaces.
function _uninstallAllInterfaces() internal {
AccountStorage storage ds = _getAccountStorage();
uint256 len = ds.installedIfaces.length;
for (uint256 i = 0; i < len; i++) {
bytes4 interfaceId = ds.installedIfaces[i];
_uninstallInterface(interfaceId);
}
delete ds.installedIfaces;
}
/// @dev Sets the current hook in the storage to the specified address.
/// @param hook The new hook address.
function _setHook(address hook) internal virtual {
_getAccountStorage().hook = IHook(hook);
}
/// @dev Installs a fallback handler for a given selector with initialization data.
/// @param handler The address of the fallback handler to install.
/// @param params The initialization parameters including the selector and call type.
function _installFallbackHandler(address handler, bytes calldata params) internal virtual withHook {
if (!IFallback(handler).isModuleType(MODULE_TYPE_FALLBACK)) revert MismatchModuleTypeId();
// Extract the function selector from the provided parameters.
bytes4 selector = bytes4(params[0:4]);
// Extract the call type from the provided parameters.
CallType calltype = CallType.wrap(bytes1(params[4]));
require(calltype == CALLTYPE_SINGLE || calltype == CALLTYPE_STATIC, FallbackCallTypeInvalid());
// Extract the initialization data from the provided parameters.
bytes memory initData = params[5:];
// Revert if the selector is one of the banned selectors
// `onInstall(bytes)` (0x6d61fe70) or `onUninstall(bytes)` (0x8a91b0e3) or explicit bytes(0).
// Major selectors from ERC-7579, ERC-721, ERC-1155, ERC-1271 and ERC-4337
// Majority of startale account native selectors
// These selectors are explicitly forbidden to prevent security vulnerabilities.
// Allowing these selectors would enable unauthorized users to uninstall and reinstall critical modules.
// If a validator module is uninstalled and reinstalled without proper authorization, it can compromise
// the account's security and integrity. By restricting these selectors, we ensure that the fallback handler
// cannot be manipulated to disrupt the expected behavior and security of the account.
// List of selectors
// IERC7579Module
// bytes4(0x6d61fe70) - onInstall(bytes)
// bytes4(0x8a91b0e3) - onUninstall(bytes)
// bytes4(0xecd05961) - isModuleType(uint256)
// bytes4(0xd60b347f) - isInitialized()
// bytes4(0x7a0468b7) - preValidationHookERC1271()
// bytes4(0xe24f8f93) - preValidationHookERC4337()
// bytes4(0x97003203) - validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash)
// bytes4(0xf551e2ee) - isValidSignatureWithSender(address sender, bytes32 hash, bytes calldata data)
// IHook
// bytes4(0xd68f6025) - preCheck()
// bytes4(0x173bf7da) - postCheck()
// IValidator
// bytes4(0x97003203) - validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash)
// bytes4(0xf551e2ee) - isValidSignatureWithSender(address sender, bytes32 hash, bytes calldata data)
// bytes4(0) - empty bytes
// ERC-4337
// bytes4(0xee219423) - simulateValidation(PackedUserOperation calldata userOp, bytes32 userOpHash)
// bytes4(0x570e1a36) - createSender(address)
// bytes4(0x19822f7c) - validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash, uint256 missingAccountFunds)
// bytes4(0x52b7512c) - validatePaymasterUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash, uint256 missingAccountFunds)
// bytes4(0xb760faf9) - depositTo(address to, uint256 amount)
// bytes4(0x8dd7712f) - executeUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash)
// Startale IERC7579Account
// bytes4(0x1626ba7e) - isValidSignature(bytes32 hash, bytes calldata signature)
// bytes4(0x4b6a1419) - initializeAccount(bytes calldata initData)
// bytes4(0xf2dc691d) - supportsModule(uint256 moduleTypeId)
// bytes4(0xd03c7914) - supportsExecutionMode(ExecutionMode mode)
// bytes4(0x9cfd7cff) - accountId()
// bytes4(0xe9ae5c53) - execute(ExecutionMode mode, bytes calldata executionCalldata)
// bytes4(0xd691c964) - executeFromExecutor(ExecutionMode mode, bytes calldata executionCalldata)
// bytes4(0x9517e29f) - installModule(uint256 moduleTypeId, address module, bytes calldata initData)
// bytes4(0xa71763a8) - uninstallModule(uint256 moduleTypeId, address module, bytes calldata deInitData)
// bytes4(0x112d3a7d) - isModuleInstalled(uint256 moduleTypeId, address module, bytes calldata additionalContext)
require(
// BAN ALL ABOVE SELECTORS
!(
selector == bytes4(0x6d61fe70) || selector == bytes4(0x8a91b0e3) || selector == bytes4(0xecd05961)
|| selector == bytes4(0xd60b347f) || selector == bytes4(0x7a0468b7) || selector == bytes4(0xe24f8f93)
|| selector == bytes4(0x97003203) || selector == bytes4(0xf551e2ee) || selector == bytes4(0xd68f6025)
|| selector == bytes4(0x173bf7da) || selector == bytes4(0x97003203) || selector == bytes4(0xf551e2ee)
|| selector == bytes4(0xee219423) || selector == bytes4(0x570e1a36) || selector == bytes4(0x19822f7c)
|| selector == bytes4(0x52b7512c) || selector == bytes4(0xb760faf9) || selector == bytes4(0x8dd7712f)
|| selector == bytes4(0x1626ba7e) || selector == bytes4(0x4b6a1419) || selector == bytes4(0xf2dc691d)
|| selector == bytes4(0xd03c7914) || selector == bytes4(0x9cfd7cff) || selector == bytes4(0xe9ae5c53)
|| selector == bytes4(0xd691c964) || selector == bytes4(0x9517e29f) || selector == bytes4(0xa71763a8)
|| selector == bytes4(0x112d3a7d)
),
FallbackSelectorForbidden()
);
// Revert if a fallback handler is already installed for the given selector.
// This check ensures that we do not overwrite an existing fallback handler, which could lead to unexpected behavior.
require(!_isFallbackHandlerInstalled(selector), FallbackAlreadyInstalledForSelector(selector));
AccountStorage storage ds = _getAccountStorage();
// Store the fallback handler and its call type in the account storage.
// This maps the function selector to the specified fallback handler and call type.
ds.fallbacks[selector] = FallbackHandler(handler, calltype);
// Add the selector to the maintained list of fallback selectors
ds.fallbackSelectors.push(selector);
// Invoke the `onInstall` function of the fallback handler with the provided initialization data.
// This step allows the fallback handler to perform any necessary setup or initialization.
if (initData.length > 0) {
IFallback(handler).onInstall(initData);
}
}
/// @dev Uninstalls a fallback handler for a given selector.
/// @param fallbackHandler The address of the fallback handler to uninstall.
/// @param data The de-initialization data containing the selector.
function _uninstallFallbackHandler(address fallbackHandler, bytes calldata data) internal virtual {
AccountStorage storage ds = _getAccountStorage();
bytes4 selector = bytes4(data[0:4]);
ds.fallbacks[selector] = FallbackHandler(address(0), CallType.wrap(0x00));
// Remove selector from fallbackSelectors via swap-and-pop
uint256 len = ds.fallbackSelectors.length;
for (uint256 i = 0; i < len; i++) {
if (ds.fallbackSelectors[i] == selector) {
ds.fallbackSelectors[i] = ds.fallbackSelectors[len - 1];
ds.fallbackSelectors.pop();
break;
}
}
(bool success, bytes memory returnData) = fallbackHandler.excessivelySafeCall(
gasleft(), 0, 0, abi.encodeWithSelector(IModule.onUninstall.selector, data[4:])
);
if (!success) {
emit ExternalCallFailed(
fallbackHandler, abi.encodeWithSelector(IModule.onUninstall.selector, data[4:]), returnData
);
}
}
/// @dev Installs a pre-validation hook module, ensuring no other pre-validation hooks are installed before proceeding.
/// @param preValidationHookType The type of the pre-validation hook.
/// @param preValidationHook The address of the pre-validation hook to be installed.
/// @param data Initialization data to configure the hook upon installation.
function _installPreValidationHook(
uint256 preValidationHookType,
address preValidationHook,
bytes calldata data
) internal virtual withHook {
if (!IModule(preValidationHook).isModuleType(preValidationHookType)) revert MismatchModuleTypeId();
address currentPreValidationHook = _getPreValidationHook(preValidationHookType);
if (currentPreValidationHook != address(0)) revert PrevalidationHookAlreadyInstalled(currentPreValidationHook);
_setPreValidationHook(preValidationHookType, preValidationHook);
if (data.length > 0) {
IModule(preValidationHook).onInstall(data);
}
}
/// @dev Uninstalls a pre-validation hook module
/// @param preValidationHook The address of the pre-validation hook to be uninstalled.
/// @param hookType The type of the pre-validation hook.
/// @param data De-initialization data to configure the hook upon uninstallation.
function _uninstallPreValidationHook(
address preValidationHook,
uint256 hookType,
bytes calldata data
) internal virtual {
_setPreValidationHook(hookType, address(0));
try IModule(preValidationHook).onUninstall(data) {}
catch {
emit PreValidationHookUninstallFailed(preValidationHook, data);
}
}
function _uninstallPreValidationHook(address hook, uint256 hookType) internal virtual {
if (hook == address(0)) return;
if (hookType == MODULE_TYPE_PREVALIDATION_HOOK_ERC1271) {
_setPreValidationHook(hookType, address(0));
emit ModuleUninstalled(hookType, hook);
} else if (hookType == MODULE_TYPE_PREVALIDATION_HOOK_ERC4337) {
_setPreValidationHook(hookType, address(0));
emit ModuleUninstalled(hookType, hook);
} else {
revert InvalidHookType(hookType);
}
}
/// @dev Sets the current pre-validation hook in the storage to the specified address, based on the hook type.
/// @param hookType The type of the pre-validation hook.
/// @param hook The new hook address.
function _setPreValidationHook(uint256 hookType, address hook) internal virtual {
if (hookType == MODULE_TYPE_PREVALIDATION_HOOK_ERC1271) {
_getAccountStorage().preValidationHookERC1271 = IPreValidationHookERC1271(hook);
} else if (hookType == MODULE_TYPE_PREVALIDATION_HOOK_ERC4337) {
_getAccountStorage().preValidationHookERC4337 = IPreValidationHookERC4337(hook);
} else {
revert InvalidHookType(hookType);
}
}
/// @notice Installs a module with multiple types in a single operation.
/// @dev This function handles installing a multi-type module by iterating through each type and initializing it.
/// The initData should include an ABI-encoded tuple of (uint[] types, bytes[] initDatas).
/// @param module The address of the multi-type module.
/// @param initData Initialization data for each type within the module.
function _multiTypeInstall(address module, bytes calldata initData) internal virtual {
(uint256[] calldata types, bytes[] calldata initDatas) = initData.parseMultiTypeInitData();
uint256 length = types.length;
if (initDatas.length != length) revert InvalidInput();
// iterate over all module types and install the module as a type accordingly
for (uint256 i; i < length; i++) {
uint256 theType = types[i];
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INSTALL VALIDATORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
if (theType == MODULE_TYPE_VALIDATOR) {
_installValidator(module, initDatas[i]);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INSTALL EXECUTORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
else if (theType == MODULE_TYPE_EXECUTOR) {
_installExecutor(module, initDatas[i]);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INSTALL FALLBACK */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
else if (theType == MODULE_TYPE_FALLBACK) {
_installFallbackHandler(module, initDatas[i]);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INSTALL HOOK (global only, not sig-specific) */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
else if (theType == MODULE_TYPE_HOOK) {
_installHook(module, initDatas[i]);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INSTALL PRE-VALIDATION HOOK */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
else if (theType == MODULE_TYPE_PREVALIDATION_HOOK_ERC1271 || theType == MODULE_TYPE_PREVALIDATION_HOOK_ERC4337) {
_installPreValidationHook(theType, module, initDatas[i]);
}
}
}
/// @notice Installs an interface to the smart account.
/// @param interfaceId The id of the interface to install.
function _installInterface(bytes4 interfaceId) internal virtual {
AccountStorage storage ds = _getAccountStorage();
ds.supportedIfaces[interfaceId] = true;
ds.installedIfaces.push(interfaceId);
emit InterfaceInstalled(interfaceId);
}
/// @notice Uninstalls an interface from the smart account.
/// @param interfaceId The id of the interface to uninstall.
function _uninstallInterface(bytes4 interfaceId) internal virtual {
AccountStorage storage ds = _getAccountStorage();
ds.supportedIfaces[interfaceId] = false;
// Remove interfaceId from installedIfaces via swap-and-pop
uint256 len = ds.installedIfaces.length;
for (uint256 i = 0; i < len; i++) {
if (ds.installedIfaces[i] == interfaceId) {
ds.installedIfaces[i] = ds.installedIfaces[len - 1];
ds.installedIfaces.pop();
break;
}
}
emit InterfaceUninstalled(interfaceId);
}
/// @notice Installs multiple interfaces to the smart account.
/// @param interfaceIds The ids of the interfaces to install.
function _installInterfaces(bytes4[] calldata interfaceIds) internal virtual {
for (uint256 i = 0; i < interfaceIds.length; i++) {
_installInterface(interfaceIds[i]);
}
}
/// @notice Checks if an emergency uninstall signature is valid.
/// @param data The emergency uninstall data.
/// @param signature The signature to validate.
function _checkEmergencyUninstallSignature(EmergencyUninstall calldata data, bytes calldata signature) internal {
address validator = _handleValidator(address(bytes20(signature[0:20])));
// Hash the data
bytes32 hash = _getEmergencyUninstallDataHash(data.hook, data.hookType, data.deInitData, data.nonce);
// Check if nonce is valid
require(!_getAccountStorage().nonces[data.nonce], InvalidNonce());
// Mark nonce as used
_getAccountStorage().nonces[data.nonce] = true;
// Check if the signature is valid
require(
(IValidator(validator).isValidSignatureWithSender(address(this), hash, signature[20:]) == ERC1271_MAGICVALUE),
EmergencyUninstallSigError()
);
}
/// @dev Retrieves the pre-validation hook from the storage based on the hook type.
/// @param preValidationHookType The type of the pre-validation hook.
/// @return preValidationHook The address of the pre-validation hook.
function _getPreValidationHook(uint256 preValidationHookType) internal view returns (address preValidationHook) {
if (preValidationHookType == MODULE_TYPE_PREVALIDATION_HOOK_ERC1271) {
preValidationHook = address(_getAccountStorage().preValidationHookERC1271);
} else if (preValidationHookType == MODULE_TYPE_PREVALIDATION_HOOK_ERC4337) {
preValidationHook = address(_getAccountStorage().preValidationHookERC4337);
} else {
revert InvalidHookType(preValidationHookType);
}
}
/// @dev Calls the pre-validation hook for ERC-1271.
/// @param hash The hash of the user operation.
/// @param signature The signature to validate.
/// @return postHash The updated hash after the pre-validation hook.
/// @return postSig The updated signature after the pre-validation hook.
function _withPreValidationHook(
bytes32 hash,
bytes calldata signature
) internal view virtual returns (bytes32 postHash, bytes memory postSig) {
// Get the pre-validation hook for ERC-1271
address preValidationHook = _getPreValidationHook(MODULE_TYPE_PREVALIDATION_HOOK_ERC1271);
// If no pre-validation hook is installed, return the original hash and signature
if (preValidationHook == address(0)) return (hash, signature);
// Otherwise, call the pre-validation hook and return the updated hash and signature
else return IPreValidationHookERC1271(preValidationHook).preValidationHookERC1271(msg.sender, hash, signature);
}
/// @dev Calls the pre-validation hook for ERC-4337.
/// @param hash The hash of the user operation.
/// @param userOp The user operation data.
/// @param missingAccountFunds The amount of missing account funds.
/// @return postHash The updated hash after the pre-validation hook.
/// @return postSig The updated signature after the pre-validation hook.
function _withPreValidationHook(
bytes32 hash,
PackedUserOperation memory userOp,
uint256 missingAccountFunds
) internal virtual returns (bytes32 postHash, bytes memory postSig) {
// Get the pre-validation hook for ERC-4337
address preValidationHook = _getPreValidationHook(MODULE_TYPE_PREVALIDATION_HOOK_ERC4337);
// If no pre-validation hook is installed, return the original hash and signature
if (preValidationHook == address(0)) {
return (hash, userOp.signature);
}
// Otherwise, call the pre-validation hook and return the updated hash and signature
else {
return IPreValidationHookERC4337(preValidationHook).preValidationHookERC4337(userOp, missingAccountFunds, hash);
}
}
/// @notice Checks if an enable mode signature is valid.
/// @param structHash data hash.
/// @param sig Signature.
/// @param validator Validator address.
function _checkEnableModeSignature(
bytes32 structHash,
bytes calldata sig,
address validator
) internal view returns (bool) {
bytes32 eip712Digest = _hashTypedData(structHash);
// Use standard IERC-1271/ERC-7739 interface.
// Even if the validator doesn't support 7739 under the hood, it is still secure,
// as eip712digest is already built based on 712Domain of this Smart Account
// This interface should always be exposed by validators as per ERC-7579
try IValidator(validator).isValidSignatureWithSender(address(this), eip712Digest, sig) returns (bytes4 res) {
return res == ERC1271_MAGICVALUE;
} catch {
return false;
}
}
/// @notice Builds the enable mode data hash as per eip712
/// @param module Module being enabled
/// @param moduleType Type of the module as per EIP-7579
/// @param userOpHash Hash of the User Operation
/// @param initData Module init data.
/// @return structHash data hash
function _getEnableModeDataHash(
address module,
uint256 moduleType,
bytes32 userOpHash,
bytes calldata initData
) internal view returns (bytes32) {
return keccak256(abi.encode(MODULE_ENABLE_MODE_TYPE_HASH, module, moduleType, userOpHash, keccak256(initData)));
}
/// @notice Builds the emergency uninstall data hash as per eip712
/// @param hookType Type of the hook (4 for Hook, 8 for ERC-1271 Prevalidation Hook, 9 for ERC-4337 Prevalidation Hook)
/// @param hook address of the hook being uninstalled
/// @param data De-initialization data to configure the hook upon uninstallation.
/// @param nonce Unique nonce for the operation
/// @return structHash data hash
function _getEmergencyUninstallDataHash(
address hook,
uint256 hookType,
bytes calldata data,
uint256 nonce
) internal view returns (bytes32) {
return _hashTypedData(keccak256(abi.encode(EMERGENCY_UNINSTALL_TYPE_HASH, hook, hookType, keccak256(data), nonce)));
}
/// @notice Checks if a module is installed on the smart account.
/// @param moduleTypeId The module type ID.
/// @param module The module address.
/// @param additionalContext Additional context for checking installation.
/// @return True if the module is installed, false otherwise.
function _isModuleInstalled(
uint256 moduleTypeId,
address module,
bytes calldata additionalContext
) internal view returns (bool) {
additionalContext;
if (moduleTypeId == MODULE_TYPE_VALIDATOR) {
return _isValidatorInstalled(module);
} else if (moduleTypeId == MODULE_TYPE_EXECUTOR) {
return _isExecutorInstalled(module);
} else if (moduleTypeId == MODULE_TYPE_FALLBACK) {
bytes4 selector;
if (additionalContext.length >= 4) {
selector = bytes4(additionalContext[0:4]);
} else {
selector = bytes4(0x00000000);
}
return _isFallbackHandlerInstalled(selector, module);
} else if (moduleTypeId == MODULE_TYPE_HOOK) {
return _isHookInstalled(module);
} else if (
moduleTypeId == MODULE_TYPE_PREVALIDATION_HOOK_ERC1271 || moduleTypeId == MODULE_TYPE_PREVALIDATION_HOOK_ERC4337
) {
return _getPreValidationHook(moduleTypeId) == module;
} else {
return false;
}
}
/// @dev Checks if the validator list is already initialized.
/// In theory it doesn't 100% mean there is a validator or executor installed.
/// Use below functions to check for validators and executors.
function _areSentinelListsInitialized() internal view virtual returns (bool) {
// account module storage
AccountStorage storage ams = _getAccountStorage();
return ams.validators.alreadyInitialized() && ams.executors.alreadyInitialized();
}
/// @dev Checks if a fallback handler is set for a given selector.
/// @param selector The function selector to check.
/// @return True if a fallback handler is set, otherwise false.
function _isFallbackHandlerInstalled(bytes4 selector) internal view virtual returns (bool) {
FallbackHandler storage handler = _getAccountStorage().fallbacks[selector];
return handler.handler != address(0);
}
/// @dev Checks if the expected fallback handler is installed for a given selector.
/// @param selector The function selector to check.
/// @param expectedHandler The address of the handler expected to be installed.
/// @return True if the installed handler matches the expected handler, otherwise false.
function _isFallbackHandlerInstalled(bytes4 selector, address expectedHandler) internal view returns (bool) {
FallbackHandler storage handler = _getAccountStorage().fallbacks[selector];
return handler.handler == expectedHandler;
}
/// @dev Checks if a validator is currently installed.
/// @param validator The address of the validator to check.
/// @return True if the validator is installed, otherwise false.
function _isValidatorInstalled(address validator) internal view virtual returns (bool) {
return _getAccountStorage().validators.contains(validator);
}
/// @dev Checks if an executor is currently installed.
/// @param executor The address of the executor to check.
/// @return True if the executor is installed, otherwise false.
function _isExecutorInstalled(address executor) internal view virtual returns (bool) {
return _getAccountStorage().executors.contains(executor);
}
/// @dev Checks if a hook is currently installed.
/// @param hook The address of the hook to check.
/// @return True if the hook is installed, otherwise false.
function _isHookInstalled(address hook) internal view returns (bool) {
return _getHook() == hook;
}
/// @dev Retrieves the current hook from the storage.
/// @return hook The address of the current hook.
function _getHook() internal view returns (address hook) {
hook = address(_getAccountStorage().hook);
}
/// @dev Checks if the account is an ERC7702 account
function _amIERC7702() internal view returns (bool res) {
assembly {
// use extcodesize as the first cheapest check
if eq(extcodesize(address()), 23) {
// use extcodecopy to copy first 3 bytes of this contract and compare with 0xef0100
extcodecopy(address(), 0, 0, 3)
res := eq(0xef0100, shr(232, mload(0x00)))
}
// if it is not 23, we do not even check the first 3 bytes
}
}
/// @dev Returns the validator address to use
function _handleValidator(address validator) internal view returns (address) {
if (validator == address(0)) {
return _DEFAULT_VALIDATOR;
} else {
require(_isValidatorInstalled(validator), ValidatorNotInstalled(validator));
return validator;
}
}
function _fallback(bytes calldata callData) private {
bool success;
bytes memory result;
FallbackHandler storage $fallbackHandler = _getAccountStorage().fallbacks[msg.sig];
address handler = $fallbackHandler.handler;
CallType calltype = $fallbackHandler.calltype;
if (handler != address(0)) {
// hook manually
address hook = _getHook();
bytes memory hookData;
if (hook != address(0)) {
hookData = IHook(hook).preCheck(msg.sender, msg.value, msg.data);
}
//if there's a fallback handler, call it
if (calltype == CALLTYPE_STATIC) {
(success, result) = handler.staticcall(ExecutionLib.get2771CallData(callData));
} else if (calltype == CALLTYPE_SINGLE) {
(success, result) = handler.call{value: msg.value}(ExecutionLib.get2771CallData(callData));
} else {
revert UnsupportedCallType(calltype);
}
// Use revert message from fallback handler if the call was not successful
assembly {
if iszero(success) { revert(add(result, 0x20), mload(result)) }
}
// hook post check
if (hook != address(0)) {
IHook(hook).postCheck(hookData);
}
// return the result
assembly {
return(add(result, 0x20), mload(result))
}
}
// If there's no handler, the call can be one of onERCXXXReceived()
// No need to hook this as no execution is done here
bytes32 s;
/// @solidity memory-safe-assembly
assembly {
s := shr(224, calldataload(0))
// 0x150b7a02: `onERC721Received(address,address,uint256,bytes)`.
// 0xf23a6e61: `onERC1155Received(address,address,uint256,uint256,bytes)`.
// 0xbc197c81: `onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)`.
if or(eq(s, 0x150b7a02), or(eq(s, 0xf23a6e61), eq(s, 0xbc197c81))) {
mstore(0x00, shl(224, s)) // Store msg.sig left-aligned in scratch space memory[0:32]
return(0x00, 0x20) // Return clean 32-byte value for msg.sig
}
}
// if there was no handler and it is not the onERCXXXReceived call, revert
revert MissingFallbackHandler(msg.sig);
}
/// @dev Helper function to paginate entries in a SentinelList.
/// @param list The SentinelList to paginate.
/// @param cursor The cursor to start paginating from.
/// @param size The number of entries to return.
/// @return array The array of addresses in the list.
/// @return nextCursor The cursor for the next page of entries.
function _paginate(
SentinelListLib.SentinelList storage list,
address cursor,
uint256 size
) private view returns (address[] memory array, address nextCursor) {
(array, nextCursor) = list.getEntriesPaginated(cursor, size);
}
}
src/interfaces/IAccountEventsAndErrors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {PackedUserOperation} from '@account-abstraction/interfaces/PackedUserOperation.sol';
/// @title Events and Errors
/// @notice Defines common errors for the the smart account.
interface IAccountEventsAndErrors {
/// @notice Error thrown when an unsupported ModuleType is requested.
/// @param moduleTypeId The ID of the unsupported module type.
error UnsupportedModuleType(uint256 moduleTypeId);
/// @notice Error thrown on failed execution.
error ExecutionFailed();
/// @notice Error thrown when the Factory fails to initialize the account with posted bootstrap data.
error AccountInitializationFailed();
/// @notice Error thrown when a zero address is provided as the Entry Point address.
error EntryPointCanNotBeZero();
/// @notice Error thrown when the provided implementation address is invalid.
error InvalidImplementationAddress();
/// @notice Error thrown when the provided implementation address is not a contract.
error ImplementationIsNotAContract();
/// @notice Error thrown when an inner call fails.
error InnerCallFailed();
/// @notice Error thrown when attempted to emergency-uninstall a hook
error EmergencyTimeLockNotExpired();
/// @notice Error thrown when attempted to upgrade an ERC7702 account via UUPS proxy upgrade mechanism
error ERC7702AccountCannotBeUpgradedThisWay();
/// @notice Error thrown when the provided initData is invalid.
error InvalidInitData();
/// @notice Error thrown when the account is already initialized.
error AccountAlreadyInitialized();
/// @notice Error thrown when the account is not initialized but expected to be.
error AccountNotInitialized();
}
src/interfaces/IERC4337Account.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {PackedUserOperation} from '@account-abstraction/interfaces/PackedUserOperation.sol';
/// @title IERC4337Account
/// @notice This interface defines the necessary validation and execution methods for smart accounts under the ERC-4337 standard.
/// @dev Provides a structure for implementing custom validation logic and execution methods that comply with ERC-4337 "account abstraction" specs.
/// The validation method ensures proper signature and nonce verification before proceeding with transaction execution, critical for securing userOps.
/// Also allows for the optional definition of an execution method to handle transactions post-validation, enhancing flexibility.
/// @author Startale
/// Special thanks to the Solady team for foundational contributions: https://github.com/Vectorized/solady
interface IERC4337Account {
/// Validate user's signature and nonce
/// the entryPoint will make the call to the recipient only if this validation call returns successfully.
/// signature failure should be reported by returning SIG_VALIDATION_FAILED (1).
/// This allows making a "simulation call" without a valid signature
/// Other failures (e.g. nonce mismatch, or invalid signature format) should still revert to signal failure.
///
/// @dev ERC-4337-v-0.7 validation stage
/// @dev Must validate caller is the entryPoint.
/// Must validate the signature and nonce
/// @param userOp - The user operation that is about to be executed.
/// @param userOpHash - Hash of the user's request data. can be used as the basis for signature.
/// @param missingAccountFunds - Missing funds on the account's deposit in the entrypoint.
/// This is the minimum amount to transfer to the sender(entryPoint) to be
/// able to make the call. The excess is left as a deposit in the entrypoint
/// for future calls. Can be withdrawn anytime using "entryPoint.withdrawTo()".
/// In case there is a paymaster in the request (or the current deposit is high
/// enough), this value will be zero.
/// @return validationData - Packaged ValidationData structure. use `_packValidationData` and
/// `_unpackValidationData` to encode and decode.
/// <20-byte> sigAuthorizer - 0 for valid signature, 1 to mark signature failure,
/// otherwise, an address of an "authorizer" contract.
/// <6-byte> validUntil - Last timestamp this operation is valid. 0 for "indefinite"
/// <6-byte> validAfter - First timestamp this operation is valid
/// If an account doesn't use time-range, it is enough to
/// return SIG_VALIDATION_FAILED value (1) for signature failure.
/// Note that the validation code cannot use block.timestamp (or block.number) directly.
function validateUserOp(
PackedUserOperation calldata userOp,
bytes32 userOpHash,
uint256 missingAccountFunds
) external returns (uint256 validationData);
/// Account may implement this execute method.
/// passing this methodSig at the beginning of callData will cause the entryPoint to pass the
/// full UserOp (and hash)
/// to the account.
/// The account should skip the methodSig, and use the callData (and optionally, other UserOp
/// fields)
/// @dev ERC-4337-v-0.7 optional execution path
/// @param userOp - The operation that was just validated.
/// @param userOpHash - Hash of the user's request data.
function executeUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external payable;
}
src/interfaces/IERC7579Account.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IAccountConfig} from './core/IAccountConfig.sol';
import {IExecutionHelper} from './core/IExecutionHelper.sol';
import {IModuleManager} from './core/IModuleManager.sol';
/// @title IERC7579Account
/// @notice This interface integrates the functionalities required for a modular smart account compliant with ERC-7579 and ERC-4337 standards.
/// @dev Combines configurations and operational management for smart accounts, bridging IAccountConfig, IExecutionHelper, and IModuleManager.
/// Interfaces designed to support the comprehensive management of smart account operations including execution management and modular configurations.
/// @author Startale
interface IERC7579Account is IAccountConfig, IExecutionHelper, IModuleManager {
/// @dev Validates a smart account signature according to ERC-1271 standards.
/// This method may delegate the call to a validator module to check the signature.
/// @param hash The hash of the data being validated.
/// @param data The signed data to validate.
function isValidSignature(bytes32 hash, bytes calldata data) external view returns (bytes4);
}
src/interfaces/IERC7579Module.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {PackedUserOperation} from '@account-abstraction/interfaces/PackedUserOperation.sol';
uint256 constant VALIDATION_SUCCESS = 0;
uint256 constant VALIDATION_FAILED = 1;
uint256 constant MODULE_TYPE_VALIDATOR = 1;
uint256 constant MODULE_TYPE_EXECUTOR = 2;
uint256 constant MODULE_TYPE_FALLBACK = 3;
uint256 constant MODULE_TYPE_HOOK = 4;
uint256 constant MODULE_TYPE_PREVALIDATION_HOOK_ERC1271 = 8;
uint256 constant MODULE_TYPE_PREVALIDATION_HOOK_ERC4337 = 9;
interface IModule {
error AlreadyInitialized(address smartAccount);
error NotInitialized(address smartAccount);
/**
* @dev This function is called by the smart account during installation of the module
* @param data arbitrary data that may be required on the module during `onInstall`
* initialization
*
* MUST revert on error (i.e. if module is already enabled)
*/
function onInstall(bytes calldata data) external;
/**
* @dev This function is called by the smart account during uninstallation of the module
* @param data arbitrary data that may be required on the module during `onUninstall`
* de-initialization
*
* MUST revert on error
*/
function onUninstall(bytes calldata data) external;
/**
* @dev Returns boolean value if module is a certain type
* @param moduleTypeId the module type ID according the ERC-7579 spec
*
* MUST return true if the module is of the given type and false otherwise
*/
function isModuleType(uint256 moduleTypeId) external view returns (bool);
/**
* @dev Returns if the module was already initialized for a provided smartaccount
*/
function isInitialized(address smartAccount) external view returns (bool);
}
interface IValidator is IModule {
error InvalidTargetAddress(address target);
/**
* @dev Validates a transaction on behalf of the account.
* This function is intended to be called by the MSA during the ERC-4337 validaton phase
* Note: solely relying on bytes32 hash and signature is not suffcient for some
* validation implementations (i.e. SessionKeys often need access to userOp.calldata)
* @param userOp The user operation to be validated. The userOp MUST NOT contain any metadata.
* The MSA MUST clean up the userOp before sending it to the validator.
* @param userOpHash The hash of the user operation to be validated
* @return return value according to ERC-4337
*/
function validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external returns (uint256);
/**
* Validator can be used for ERC-1271 validation
*/
function isValidSignatureWithSender(address sender, bytes32 hash, bytes calldata data) external view returns (bytes4);
}
interface IExecutor is IModule {}
interface IHook is IModule {
function preCheck(
address msgSender,
uint256 msgValue,
bytes calldata msgData
) external returns (bytes memory hookData);
function postCheck(bytes calldata hookData) external;
}
interface IFallback is IModule {}
interface IPreValidationHookERC1271 is IModule {
function preValidationHookERC1271(
address sender,
bytes32 hash,
bytes calldata data
) external view returns (bytes32 hookHash, bytes memory hookSignature);
}
interface IPreValidationHookERC4337 is IModule {
function preValidationHookERC4337(
PackedUserOperation calldata userOp,
uint256 missingAccountFunds,
bytes32 userOpHash
) external returns (bytes32 hookHash, bytes memory hookSignature);
}
src/interfaces/IERC7779.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
interface IERC7779 {
/*
* @dev Externally shares the storage bases that has been used throughout the account.
* Majority of 7702 accounts will have their distinctive storage base to reduce the
chance of storage collision.
* This allows the external entities to know what the storage base is of the account.
* Wallets willing to redelegate already-delegated accounts should call
accountStorageBase() to check if it confirms with the account it plans to redelegate.
*
* The bytes32 array should be stored at the storage slot:
keccak(keccak('InteroperableDelegatedAccount.ERC.Storage')-1) & ~0xff
* This is an append-only array so newly redelegated accounts should not overwrite the
storage at this slot, but just append their base to the array.
* This append operation should be done during the initialization of the account.
*/
function accountStorageBases() external view returns (bytes32[] memory);
/*
* @dev Function called before redelegation.
* This function should prepare the account for a delegation to a different
implementation.
* This function could be triggered by the new wallet that wants to redelegate an already
delegated EOA.
* It should uninitialize storages if needed and execute wallet-specific logic to prepare
for redelegation.
* msg.sender should be the owner of the account.
*/
function onRedelegation() external returns (bool);
}
src/interfaces/IStartaleSmartAccount.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IAccountEventsAndErrors} from './IAccountEventsAndErrors.sol';
import {IERC4337Account} from './IERC4337Account.sol';
import {IERC7579Account} from './IERC7579Account.sol';
import {IERC7779} from './IERC7779.sol';
/// @title Startale Smart Account Interface
/// @notice Integrates ERC-4337 and ERC-7579 standards to manage smart accounts within the Startale suite.
/// @dev Consolidates ERC-4337 user operations and ERC-7579 configurations into a unified interface for smart account management.
/// It extends both IERC4337Account and IERC7579Account, enhancing modular capabilities and supporting advanced contract architectures.
/// Includes error definitions for robust handling of common issues such as unsupported module types and execution failures.
/// The initialize function sets up the account with validators and configurations, ensuring readiness for use.
/// @author Startale
interface IStartaleSmartAccount is IERC4337Account, IERC7579Account, IERC7779, IAccountEventsAndErrors {
/// @notice Initializes the smart account with a validator and custom data.
/// @dev This method sets up the account for operation, linking it with a validator and initializing it with specific data.
/// Can be called directly or via a factory.
/// @param initData Encoded data used for the account's configuration during initialization.
function initializeAccount(bytes calldata initData) external payable;
}
src/interfaces/core/IAccountConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {ExecutionMode} from '../../lib/ModeLib.sol';
/// @title ERC-7579 Account Configuration Interface
/// @notice Interface for querying and verifying configurations of Smart Accounts compliant with ERC-7579.
/// @dev Provides methods to check supported execution modes and module types for Smart Accounts.
interface IAccountConfig {
/// @notice Returns the account ID in a structured format: "vendorname.accountname.semver"
/// @return accountImplementationId The account ID of the smart account
function accountId() external view returns (string memory accountImplementationId);
/// @notice Checks if the account supports a certain execution mode.
/// @param encodedMode The encoded mode to verify.
/// @return supported True if the account supports the mode, false otherwise.
function supportsExecutionMode(ExecutionMode encodedMode) external view returns (bool supported);
/// @notice Checks if the account supports a specific module type.
/// @param moduleTypeId The module type ID to verify.
/// @return supported True if the account supports the module type, false otherwise.
function supportsModule(uint256 moduleTypeId) external view returns (bool supported);
}
src/interfaces/core/IAllStorage.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {CallType} from '../../lib/ModeLib.sol';
import {IHook, IPreValidationHookERC1271, IPreValidationHookERC4337} from '../IERC7579Module.sol';
import {SentinelListLib} from 'sentinellist/SentinelList.sol';
/// @title IStorage Interface
/// @dev This interface utilizes ERC-7201 storage location practices to ensure isolated and collision-resistant storage spaces within smart contracts.
/// @custom:storage-location erc7201:startale.account.storage
/// @author Startale Labs
interface IAllStorage {
/// @notice Struct storing validators and executors using Sentinel lists, and fallback handlers via mapping.
struct AccountStorage {
///< List of validators, initialized upon contract deployment.
SentinelListLib.SentinelList validators;
///< List of executors, similarly initialized.
SentinelListLib.SentinelList executors;
///< Mapping of selectors to their respective fallback handlers.
mapping(bytes4 => FallbackHandler) fallbacks;
///< List of fallback selectors, initialized upon contract deployment.
bytes4[] fallbackSelectors;
///< ERC-165 interfaces installed on the account.
mapping(bytes4 => bool) supportedIfaces;
///< List of installed interfaces, initialized upon contract deployment.
bytes4[] installedIfaces;
///< Current hook module associated with this account.
IHook hook;
///< Mapping of hooks to requested timelocks.
mapping(address hook => uint256) emergencyUninstallTimelock;
///< PreValidation hook for validateUserOp
IPreValidationHookERC4337 preValidationHookERC4337;
///< PreValidation hook for isValidSignature
IPreValidationHookERC1271 preValidationHookERC1271;
///< Mapping of used nonces for replay protection.
mapping(uint256 => bool) nonces;
}
/// @notice Defines a fallback handler with an associated handler address and a call type.
struct FallbackHandler {
///< The address of the fallback function handler.
address handler;
///< The type of call this handler supports (e.g., static or call).
CallType calltype;
}
}
src/interfaces/core/IBaseAccount.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
/// @title BaseAccount
/// @notice Interface for the BaseAccount functionalities compliant with ERC-7579 and ERC-4337.
/// @author Startale Labs
/// Special thanks to the Biconomy team for https://github.com/bcnmy/nexus/ on which this implementation is highly based on.
interface IBaseAccount {
/// @dev Throws an error when a caller is not authorized to access an account.
error AccountAccessUnauthorized();
/// @notice Adds deposit to the EntryPoint to fund transactions.
function addDeposit() external payable;
/// @notice Withdraws ETH from the EntryPoint to a specified address.
/// @param to The address to receive the withdrawn funds.
/// @param amount The amount to withdraw.
function withdrawDepositTo(address to, uint256 amount) external payable;
/// @notice Gets the nonce for a particular key.
/// @param key The nonce key.
/// @return The nonce associated with the key.
function nonce(uint192 key) external view returns (uint256);
/// @notice Returns the current deposit balance of this account on the EntryPoint.
/// @return The current balance held at the EntryPoint.
function getDeposit() external view returns (uint256);
/// @notice Retrieves the address of the EntryPoint contract, currently using version 0.7.
/// @return The address of the EntryPoint contract.
function entryPoint() external view returns (address);
}
src/interfaces/core/IExecutionHelper.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {ExecType, ExecutionMode} from '../../lib/ModeLib.sol';
/// @title IExecutionHelper
/// @notice Interface for executing transactions on behalf of smart account.
/// @author Startale Labs
/// Special thanks to the ERC7579 authors and reference implementation on which this implementation is highly based on.
interface IExecutionHelper {
/// @notice Event emitted when a transaction fails to execute successfully.
event TryExecuteUnsuccessful(address target, bytes callData, bytes result);
/// @notice Event emitted when a transaction fails to execute successfully.
event TryDelegateCallUnsuccessful(bytes callData, bytes result);
/// @notice Error thrown when an execution with an unsupported ExecType was made.
/// @param execType The unsupported execution type.
error UnsupportedExecType(ExecType execType);
/// @notice Executes a transaction with specified execution mode and calldata.
/// @param mode The execution mode, defining how the transaction is processed.
/// @param executionCalldata The calldata to execute.
/// @dev This function ensures that the execution complies with smart account execution policies and handles errors appropriately.
function execute(ExecutionMode mode, bytes calldata executionCalldata) external payable;
/// @notice Allows an executor module to perform transactions on behalf of the account.
/// @param mode The execution mode that details how the transaction should be handled.
/// @param executionCalldata The transaction data to be executed.
/// @return returnData The result of the execution, allowing for error handling and results interpretation by the executor module.
function executeFromExecutor(
ExecutionMode mode,
bytes calldata executionCalldata
) external payable returns (bytes[] memory returnData);
}
src/interfaces/core/IModuleManager.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {IModuleManagerEventsAndErrors} from './IModuleManagerEventsAndErrors.sol';
/// @title IModuleManager
/// @notice Interface for managing modules within Smart Accounts, providing methods for installation and removal of modules.
/// @author Startale Labs
interface IModuleManager is IModuleManagerEventsAndErrors {
/// @notice Installs a Module of a specific type onto the smart account.
/// @param moduleTypeId The identifier for the module type.
/// @param module The address of the module to be installed.
/// @param initData Initialization data for configuring the module upon installation.
function installModule(uint256 moduleTypeId, address module, bytes calldata initData) external payable;
/// @notice Uninstalls a Module of a specific type from the smart account.
/// @param moduleTypeId The identifier for the module type being uninstalled.
/// @param module The address of the module to uninstall.
/// @param deInitData De-initialization data for configuring the module upon uninstallation.
function uninstallModule(uint256 moduleTypeId, address module, bytes calldata deInitData) external payable;
/// @notice Checks if a specific module is installed on the smart account.
/// @param moduleTypeId The module type identifier to check.
/// @param module The address of the module.
/// @param additionalContext Additional information that may be required to verify the module's installation.
/// @return installed True if the module is installed, false otherwise.
function isModuleInstalled(
uint256 moduleTypeId,
address module,
bytes calldata additionalContext
) external view returns (bool installed);
}
src/interfaces/core/IModuleManagerEventsAndErrors.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {CallType} from '../../lib/ModeLib.sol';
/// @title ERC-7579 Module Manager Events and Errors Interface
/// @notice Provides event and error definitions for actions related to module management in smart accounts.
/// @dev Used by IModuleManager to define the events and errors associated with the installation and management of modules.
interface IModuleManagerEventsAndErrors {
/// @notice Emitted when a module is installed onto a smart account.
/// @param moduleTypeId The identifier for the type of module installed.
/// @param module The address of the installed module.
event ModuleInstalled(uint256 moduleTypeId, address module);
/// @notice Emitted when a module is uninstalled from a smart account.
/// @param moduleTypeId The identifier for the type of module uninstalled.
/// @param module The address of the uninstalled module.
event ModuleUninstalled(uint256 moduleTypeId, address module);
/// @notice Emitted when a pre-validation hook uninstallation fails.
/// @param hook The address of the pre-validation hook.
/// @param data The data of the pre-validation hook.
event PreValidationHookUninstallFailed(address hook, bytes data);
/// @notice Emitted when a validator uninstallation fails.
/// @param validator The address of the validator.
/// @param data The data of the validator.
event ValidatorUninstallFailed(address validator, bytes data);
/// @notice Emitted when an executor uninstallation fails.
/// @param executor The address of the executor.
/// @param data The data of the executor.
event ExecutorUninstallFailed(address executor, bytes data);
/// @notice Emitted when a hook uninstallation fails.
/// @param hook The address of the hook.
/// @param data The data of the hook.
event HookUninstallFailed(address hook, bytes data);
/// @notice Emitted when an external call fails.
/// @param target The address of the target.
/// @param callData The data of the call.
/// @param returnData The return data of the call.
event ExternalCallFailed(address target, bytes callData, bytes returnData);
/// @notice Emitted when an interface is installed.
/// @param interfaceId The id of the interface.
event InterfaceInstalled(bytes4 interfaceId);
/// @notice Emitted when an interface is uninstalled.
/// @param interfaceId The id of the interface.
event InterfaceUninstalled(bytes4 interfaceId);
/// @notice Thrown when attempting to remove the last validator.
error CanNotRemoveLastValidator();
/// @dev Thrown when the specified module address is not recognized as valid.
error ValidatorNotInstalled(address module);
/// @dev Thrown when there is no installed validator detected.
error NoValidatorInstalled();
/// @dev Thrown when the specified module address is not recognized as valid.
error InvalidModule(address module);
/// @dev Thrown when an invalid module type identifier is provided.
error InvalidModuleTypeId(uint256 moduleTypeId);
/// @dev Thrown when there is an attempt to install a module that is already installed.
error ModuleAlreadyInstalled(uint256 moduleTypeId, address module);
/// @dev Thrown when an operation is performed by an unauthorized operator.
error UnauthorizedOperation(address operator);
/// @dev Thrown when there is an attempt to uninstall a module that is not installed.
error ModuleNotInstalled(uint256 moduleTypeId, address module);
/// @dev Thrown when a module address is set to zero.
error ModuleAddressCanNotBeZero();
/// @dev Thrown when a post-check fails after hook execution.
error HookPostCheckFailed();
/// @dev Thrown when there is an attempt to install a hook while another is already installed.
error HookAlreadyInstalled(address currentHook);
/// @dev Thrown when there is an attempt to install a PreValidationHook while another is already installed.
error PrevalidationHookAlreadyInstalled(address currentPreValidationHook);
/// @dev Thrown when there is an attempt to install a fallback handler for a selector already having one.
error FallbackAlreadyInstalledForSelector(bytes4 selector);
/// @dev Thrown when there is an attempt to uninstall a fallback handler for a selector that does not have one installed.
error FallbackNotInstalledForSelector(bytes4 selector);
/// @dev Thrown when a fallback handler fails to uninstall properly.
error FallbackHandlerUninstallFailed();
/// @dev Thrown when no fallback handler is available for a given selector.
error MissingFallbackHandler(bytes4 selector);
/// @dev Thrown when Invalid data is provided for MultiType install flow
error InvalidInput();
/// @dev Thrown when unable to validate Module Enable Mode signature
error EnableModeSigError();
/// @dev Thrown when unable to validate Emergency Uninstall signature
error EmergencyUninstallSigError();
/// @notice Error thrown when an invalid nonce is used
error InvalidNonce();
/// Error thrown when account installs/uninstalls module with mismatched moduleTypeId
error MismatchModuleTypeId();
/// @dev Thrown when there is an attempt to install a forbidden selector as a fallback handler.
error FallbackSelectorForbidden();
/// @dev Thrown when there is an attempt to install a fallback handler with an invalid calltype for a given selector.
error FallbackCallTypeInvalid();
/// @notice Error thrown when an execution with an unsupported CallType was made.
/// @param callType The unsupported call type.
error UnsupportedCallType(CallType callType);
/// @notice Error thrown when the default validator is already installed.
error DefaultValidatorAlreadyInstalled();
/// @notice Error thrown when the hook type is invalid.
/// @param hookType The invalid hook type.
error InvalidHookType(uint256 hookType);
}
src/lib/DataParserLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
library DataParserLib {
/// @dev Parses the `userOp.signature` to extract the module type, module initialization data,
/// enable mode signature, and user operation signature. The `userOp.signature` must be
/// encoded in a specific way to be parsed correctly.
/// @param packedData The packed signature data, typically coming from `userOp.signature`.
/// @return module The address of the module.
/// @return moduleType The type of module as a `uint256`.
/// @return moduleInitData Initialization data specific to the module.
/// @return enableModeSignature Signature used to enable the module mode.
/// @return userOpSignature The remaining user operation signature data.
function parseEnableModeData(bytes calldata packedData)
internal
pure
returns (
address module,
uint256 moduleType,
bytes calldata moduleInitData,
bytes calldata enableModeSignature,
bytes calldata userOpSignature
)
{
uint256 p;
assembly ("memory-safe") {
let dataSize := calldatasize() // Get total calldata size
p := packedData.offset
// Check if reading module address is within bounds
if gt(add(p, 0x14), dataSize) { revert(0, 0) }
module := shr(96, calldataload(p))
p := add(p, 0x14)
// Check if reading moduleType is within bounds
if gt(add(p, 0x20), dataSize) { revert(0, 0) }
moduleType := calldataload(p)
// Check if reading moduleInitData length pointer (32 bytes) is within bounds
if gt(add(add(p, 0x20), 0x20), dataSize) { revert(0, 0) }
moduleInitData.length := shr(224, calldataload(add(p, 0x20)))
moduleInitData.offset := add(p, 0x24)
// Boundary Check: Ensure the calculated moduleInitData segment (offset + length)
// does not exceed the actual calldata size. Revert if it does.
if gt(add(moduleInitData.offset, moduleInitData.length), dataSize) { revert(0, 0) }
p := add(moduleInitData.offset, moduleInitData.length)
// Check if reading enableModeSignature length is within bounds
if gt(add(p, 0x20), dataSize) { revert(0, 0) }
enableModeSignature.length := shr(224, calldataload(p))
enableModeSignature.offset := add(p, 0x04)
// Boundary Check: Ensure enableModeSignature segment doesn't exceed calldata
if gt(add(enableModeSignature.offset, enableModeSignature.length), dataSize) { revert(0, 0) }
p := sub(add(enableModeSignature.offset, enableModeSignature.length), packedData.offset)
}
userOpSignature = packedData[p:];
}
/// @dev Parses the data to obtain types and initdata's for Multi Type module install mode
/// @param initData Multi Type module init data, abi.encoded
function parseMultiTypeInitData(bytes calldata initData)
internal
pure
returns (uint256[] calldata types, bytes[] calldata initDatas)
{
// equivalent of:
// (types, initDatas) = abi.decode(initData,(uint[],bytes[]))
assembly ("memory-safe") {
let dataSize := calldatasize() // Get total calldata size
let offset := initData.offset
let baseOffset := offset
// Check if reading first pointer is within bounds
if gt(add(offset, 0x20), dataSize) { revert(0, 0) }
let dataPointer := add(baseOffset, calldataload(offset))
// Check if reading types array length is within bounds
if gt(add(dataPointer, 0x20), dataSize) { revert(0, 0) }
types.offset := add(dataPointer, 32)
types.length := calldataload(dataPointer)
// Check if types array data doesn't exceed calldata
if gt(add(types.offset, mul(types.length, 32)), dataSize) { revert(0, 0) }
offset := add(offset, 32)
// Check if reading second pointer is within bounds
if gt(add(offset, 0x20), dataSize) { revert(0, 0) }
dataPointer := add(baseOffset, calldataload(offset))
// Check if reading initDatas array length is within bounds
if gt(add(dataPointer, 0x20), dataSize) { revert(0, 0) }
initDatas.offset := add(dataPointer, 32)
initDatas.length := calldataload(dataPointer)
// Check if initDatas array data doesn't exceed calldata
if gt(add(initDatas.offset, mul(initDatas.length, 32)), dataSize) { revert(0, 0) }
}
}
}
src/lib/ExecutionLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
import {Execution} from '../types/Structs.sol';
/// @title ExecutionLib
/// @author zeroknots.eth | rhinestone.wtf
/// Helper Library for decoding Execution calldata
/// malloc for memory allocation is bad for gas. use this assembly instead
library ExecutionLib {
function get2771CallData(bytes calldata cd) internal view returns (bytes memory callData) {
/// @solidity memory-safe-assembly
(cd);
assembly {
// as per solidity docs
function allocate(length) -> pos {
pos := mload(0x40)
mstore(0x40, add(pos, length))
}
callData := allocate(add(calldatasize(), 0x20)) //allocate extra 0x20 to store length
mstore(callData, add(calldatasize(), 0x14)) //store length, extra 0x14 is for msg.sender address
calldatacopy(add(callData, 0x20), 0, calldatasize())
// The msg.sender address is shifted to the left by 12 bytes to remove the padding
// Then the address without padding is stored right after the calldata
let senderPtr := allocate(0x14)
mstore(senderPtr, shl(96, caller()))
}
}
/**
* @notice Decode a batch of `Execution` executionBatch from a `bytes` calldata.
* @dev code is copied from solady's LibERC7579.sol
* https://github.com/Vectorized/solady/blob/740812cedc9a1fc11e17cb3d4569744367dedf19/src/accounts/LibERC7579.sol#L146
* Credits to Vectorized and the Solady Team
*/
function decodeBatch(bytes calldata executionCalldata) internal pure returns (Execution[] calldata executionBatch) {
/// @solidity memory-safe-assembly
assembly {
let u := calldataload(executionCalldata.offset)
let s := add(executionCalldata.offset, u)
let e := sub(add(executionCalldata.offset, executionCalldata.length), 0x20)
executionBatch.offset := add(s, 0x20)
executionBatch.length := calldataload(s)
if or(shr(64, u), gt(add(s, shl(5, executionBatch.length)), e)) {
mstore(0x00, 0xba597e7e) // `DecodingError()`.
revert(0x1c, 0x04)
}
if executionBatch.length {
// Perform bounds checks on the decoded `executionBatch`.
// Loop runs out-of-gas if `executionBatch.length` is big enough to cause overflows.
for { let i := executionBatch.length } 1 {} {
i := sub(i, 1)
let p := calldataload(add(executionBatch.offset, shl(5, i)))
let c := add(executionBatch.offset, p)
let q := calldataload(add(c, 0x40))
let o := add(c, q)
// forgefmt: disable-next-item
if or(shr(64, or(calldataload(o), or(p, q))),
or(gt(add(c, 0x40), e), gt(add(o, calldataload(o)), e))) {
mstore(0x00, 0xba597e7e) // `DecodingError()`.
revert(0x1c, 0x04)
}
if iszero(i) { break }
}
}
}
}
function encodeBatch(Execution[] memory executions) internal pure returns (bytes memory callData) {
callData = abi.encode(executions);
}
function decodeSingle(bytes calldata executionCalldata)
internal
pure
returns (address target, uint256 value, bytes calldata callData)
{
target = address(bytes20(executionCalldata[0:20]));
value = uint256(bytes32(executionCalldata[20:52]));
callData = executionCalldata[52:];
}
function decodeDelegateCall(bytes calldata executionCalldata)
internal
pure
returns (address delegate, bytes calldata callData)
{
// destructure executionCallData according to single exec
delegate = address(uint160(bytes20(executionCalldata[0:20])));
callData = executionCalldata[20:];
}
function encodeSingle(
address target,
uint256 value,
bytes memory callData
) internal pure returns (bytes memory userOpCalldata) {
userOpCalldata = abi.encodePacked(target, value, callData);
}
}
src/lib/Initializable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
// keccak256(abi.encode(uint256(keccak256("initializable.transient.startale.account")) - 1)) & ~bytes32(uint256(0xff));
bytes32 constant INIT_SLOT = 0x754fd8b321c4649cb777ae6fdce7e89e9cceaa31a4f639795c7807eb7f1a2700;
/// @title Initializable
/// @dev This library provides a way to set a transient flag on a contract to ensure that it is only initialized during the
/// constructor execution. This is useful to prevent a contract from being initialized multiple times.
library Initializable {
/// @dev Thrown when an attempt to initialize an already initialized contract is made
error NotInitializable();
/// @dev Sets the initializable flag in the transient storage slot to true
function setInitializable() internal {
bytes32 slot = INIT_SLOT;
assembly {
tstore(slot, 0x01)
}
}
/// @dev Checks if the initializable flag is set in the transient storage slot, reverts with NotInitializable if not
function requireInitializable() internal view {
bytes32 slot = INIT_SLOT;
// Load the current value from the slot, revert if 0
assembly {
let isInitializable := tload(slot)
if iszero(isInitializable) {
mstore(0x0, 0xaed59595) // NotInitializable()
revert(0x1c, 0x04)
}
}
}
}
src/lib/ModeLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
/// @title ModeLib
/// @author zeroknots.eth | rhinestone.wtf
/// To allow smart accounts to be very simple, but allow for more complex execution, A custom mode
/// encoding is used.
/// Function Signature of execute function:
/// function execute(ExecutionMode mode, bytes calldata executionCalldata) external payable;
/// This allows for a single bytes32 to be used to encode the execution mode, calltype, execType and
/// context.
/// NOTE: Simple Account implementations only have to scope for the most significant byte. Account that
/// implement
/// more complex execution modes may use the entire bytes32.
///
/// |--------------------------------------------------------------------|
/// | CALLTYPE | EXECTYPE | UNUSED | ModeSelector | ModePayload |
/// |--------------------------------------------------------------------|
/// | 1 byte | 1 byte | 4 bytes | 4 bytes | 22 bytes |
/// |--------------------------------------------------------------------|
///
/// CALLTYPE: 1 byte
/// CallType is used to determine how the executeCalldata paramter of the execute function has to be
/// decoded.
/// It can be either single, batch or delegatecall. In the future different calls could be added.
/// CALLTYPE can be used by a validation module to determine how to decode <userOp.callData[36:]>.
///
/// EXECTYPE: 1 byte
/// ExecType is used to determine how the account should handle the execution.
/// It can indicate if the execution should revert on failure or continue execution.
/// In the future more execution modes may be added.
/// Default Behavior (EXECTYPE = 0x00) is to revert on a single failed execution. If one execution in
/// a batch fails, the entire batch is reverted
///
/// UNUSED: 4 bytes
/// Unused bytes are reserved for future use.
///
/// ModeSelector: bytes4
/// The "optional" mode selector can be used by account vendors, to implement custom behavior in
/// their accounts.
/// the way a ModeSelector is to be calculated is bytes4(keccak256("vendorname.featurename"))
/// this is to prevent collisions between different vendors, while allowing innovation and the
/// development of new features without coordination between ERC-7579 implementing accounts
///
/// ModePayload: 22 bytes
/// Mode payload is used to pass additional data to the smart account execution, this may be
/// interpreted depending on the ModeSelector
///
/// ExecutionCallData: n bytes
/// single, delegatecall or batch exec abi.encoded as bytes
// Custom type for improved developer experience
type ExecutionMode is bytes32;
type CallType is bytes1;
type ExecType is bytes1;
type ModeSelector is bytes4;
type ModePayload is bytes22;
// Default CallType
CallType constant CALLTYPE_SINGLE = CallType.wrap(0x00);
// Batched CallType
CallType constant CALLTYPE_BATCH = CallType.wrap(0x01);
CallType constant CALLTYPE_STATIC = CallType.wrap(0xFE);
// @dev Implementing delegatecall is OPTIONAL!
// implement delegatecall with extreme care.
CallType constant CALLTYPE_DELEGATECALL = CallType.wrap(0xFF);
// @dev default behavior is to revert on failure
// To allow very simple accounts to use mode encoding, the default behavior is to revert on failure
// Since this is value 0x00, no additional encoding is required for simple accounts
ExecType constant EXECTYPE_DEFAULT = ExecType.wrap(0x00);
// @dev account may elect to change execution behavior. For example "try exec" / "allow fail"
ExecType constant EXECTYPE_TRY = ExecType.wrap(0x01);
ModeSelector constant MODE_DEFAULT = ModeSelector.wrap(bytes4(0x00000000));
// Example declaration of a custom mode selector
ModeSelector constant MODE_OFFSET = ModeSelector.wrap(bytes4(keccak256('default.mode.offset')));
/// @dev ModeLib is a helper library to encode/decode ModeCodes
library ModeLib {
function decode(ExecutionMode mode)
internal
pure
returns (CallType _calltype, ExecType _execType, ModeSelector _modeSelector, ModePayload _modePayload)
{
assembly {
_calltype := mode
_execType := shl(8, mode)
_modeSelector := shl(48, mode)
_modePayload := shl(80, mode)
}
}
function decodeBasic(ExecutionMode mode) internal pure returns (CallType _calltype, ExecType _execType) {
assembly {
_calltype := mode
_execType := shl(8, mode)
}
}
function encode(
CallType callType,
ExecType execType,
ModeSelector mode,
ModePayload payload
) internal pure returns (ExecutionMode) {
return
ExecutionMode.wrap(bytes32(abi.encodePacked(callType, execType, bytes4(0), ModeSelector.unwrap(mode), payload)));
}
function encodeSimpleBatch() internal pure returns (ExecutionMode mode) {
mode = encode(CALLTYPE_BATCH, EXECTYPE_DEFAULT, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function encodeSimpleSingle() internal pure returns (ExecutionMode mode) {
mode = encode(CALLTYPE_SINGLE, EXECTYPE_DEFAULT, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function encodeTrySingle() internal pure returns (ExecutionMode mode) {
mode = encode(CALLTYPE_SINGLE, EXECTYPE_TRY, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function encodeTryBatch() internal pure returns (ExecutionMode mode) {
mode = encode(CALLTYPE_BATCH, EXECTYPE_TRY, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function encodeCustom(CallType callType, ExecType execType) internal pure returns (ExecutionMode mode) {
mode = encode(callType, execType, MODE_DEFAULT, ModePayload.wrap(0x00));
}
function getCallType(ExecutionMode mode) internal pure returns (CallType calltype) {
assembly {
calltype := mode
}
}
}
using {_eqModeSelector as ==} for ModeSelector global;
using {_eqCallType as ==} for CallType global;
using {_uneqCallType as !=} for CallType global;
using {_eqExecType as ==} for ExecType global;
function _eqCallType(CallType a, CallType b) pure returns (bool) {
return CallType.unwrap(a) == CallType.unwrap(b);
}
function _uneqCallType(CallType a, CallType b) pure returns (bool) {
return CallType.unwrap(a) != CallType.unwrap(b);
}
function _eqExecType(ExecType a, ExecType b) pure returns (bool) {
return ExecType.unwrap(a) == ExecType.unwrap(b);
}
//slither-disable-next-line dead-code
function _eqModeSelector(ModeSelector a, ModeSelector b) pure returns (bool) {
return ModeSelector.unwrap(a) == ModeSelector.unwrap(b);
}
src/lib/NonceLib.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;
import {MODE_MODULE_ENABLE, MODE_VALIDATION} from '../types/Constants.sol';
/**
* Nonce structure
* [3 bytes empty][1 bytes validation mode][20 bytes validator][8 bytes nonce]
*/
library NonceLib {
/// @dev Parses validator address out of nonce
/// @param nonce The nonce
/// @return validator
function getValidator(uint256 nonce) internal pure returns (address validator) {
assembly {
validator := shr(96, shl(32, nonce))
}
}
/// @dev Detects if Validaton Mode is Module Enable Mode
/// @param nonce The nonce
/// @return res boolean result, true if it is the Module Enable Mode
function isModuleEnableMode(uint256 nonce) internal pure returns (bool res) {
assembly {
let vmode := byte(3, nonce)
res := eq(shl(248, vmode), MODE_MODULE_ENABLE)
}
}
/// @dev Detects if the validator provided in the nonce is address(0)
/// which means the default validator is used
/// @param nonce The nonce
/// @return res boolean result, true if it is the Default Validator Mode
function isDefaultValidatorMode(uint256 nonce) internal pure returns (bool res) {
assembly {
res := iszero(shr(96, shl(32, nonce)))
}
}
/// @dev Detects if Validaton Mode is Validate Mode
/// @param nonce The nonce
/// @return res boolean result, true if it is the Validate Mode
function isValidateMode(uint256 nonce) internal pure returns (bool res) {
assembly {
let vmode := byte(3, nonce)
res := eq(shl(248, vmode), MODE_VALIDATION)
}
}
}
src/types/Constants.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
// Magic value for ERC-1271 valid signature
bytes4 constant ERC1271_MAGICVALUE = 0x1626ba7e;
// Value indicating an invalid ERC-1271 signature
bytes4 constant ERC1271_INVALID = 0xFFFFFFFF;
// Value indicating successful validation
uint256 constant VALIDATION_SUCCESS = 0;
// Value indicating failed validation
uint256 constant VALIDATION_FAILED = 1;
// Module type identifier for Multitype install
uint256 constant MODULE_TYPE_MULTI = 0;
// Module type identifier for validators
uint256 constant MODULE_TYPE_VALIDATOR = 1;
// Module type identifier for executors
uint256 constant MODULE_TYPE_EXECUTOR = 2;
// Module type identifier for fallback handlers
uint256 constant MODULE_TYPE_FALLBACK = 3;
// Module type identifier for hooks
uint256 constant MODULE_TYPE_HOOK = 4;
// Module type identifiers for pre-validation hooks
uint256 constant MODULE_TYPE_PREVALIDATION_HOOK_ERC1271 = 8;
uint256 constant MODULE_TYPE_PREVALIDATION_HOOK_ERC4337 = 9;
// keccak256("ModuleEnableMode(address module,uint256 moduleType,bytes32 userOpHash,bytes initData)")
bytes32 constant MODULE_ENABLE_MODE_TYPE_HASH = 0xf6c866c1cd985ce61f030431e576c0e82887de0643dfa8a2e6efc3463e638ed0;
// keccak256("EmergencyUninstall(address hook,uint256 hookType,bytes deInitData,uint256 nonce)")
bytes32 constant EMERGENCY_UNINSTALL_TYPE_HASH = 0xd3ddfc12654178cc44d4a7b6b969cfdce7ffe6342326ba37825314cffa0fba9c;
// Validation modes
bytes1 constant MODE_VALIDATION = 0x00;
bytes1 constant MODE_MODULE_ENABLE = 0x01;
bytes4 constant SUPPORTS_ERC7739 = 0x77390000;
bytes4 constant SUPPORTS_ERC7739_V1 = 0x77390001;
// custom-storage-location erc7201:startale.account.storage
// ERC-7201 namespaced via `keccak256(abi.encode(uint256(keccak256(bytes("startale.account.storage"))) - 1)) & ~bytes32(uint256(0xff));`
bytes32 constant ACCOUNT_STORAGE_LOCATION = 0x9195d48440658ac27f13a7bd256a2e74da1f2416f468d66228b37e6ac4790c00;
src/types/Structs.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
/// @title Execution
/// @notice Struct to encapsulate execution data for a transaction
struct Execution {
/// @notice The target address for the transaction
address target;
/// @notice The value in wei to send with the transaction
uint256 value;
/// @notice The calldata for the transaction
bytes callData;
}
/// @title Emergency Uninstall
/// @notice Struct to encapsulate emergency uninstall data for a hook
struct EmergencyUninstall {
/// @notice The address of the hook to be uninstalled
address hook;
/// @notice The hook type identifier
uint256 hookType;
/// @notice Data used to uninstall the hook
bytes deInitData;
/// @notice Nonce used to prevent replay attacks
uint256 nonce;
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": false,
"bytecodeHash": "none",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 499,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
"halmos-cheatcodes/=node_modules/halmos-cheatcodes/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/",
"@account-abstraction/=lib/account-abstraction/contracts/",
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"@openzeppelin/contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/contracts/",
"openzeppelin-contracts-upgradeable/=lib/openzeppelin-contracts-upgradeable/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/",
"sentinellist/=lib/sentinellist/src/",
"excessively-safe-call/=lib/ExcessivelySafeCall/src/",
"erc7739Validator/=lib/erc7739Validator/src/",
"solarray/=lib/solarray/src/",
"@ERC4337/=lib/erc7739Validator/node_modules/@ERC4337/",
"@prb/math/=lib/erc7739Validator/node_modules/@prb/math/src/",
"@rhinestone/=lib/erc7739Validator/node_modules/@rhinestone/",
"@safe-global/=lib/erc7739Validator/node_modules/@safe-global/",
"ExcessivelySafeCall/=lib/ExcessivelySafeCall/src/",
"account-abstraction-v0.6/=lib/erc7739Validator/node_modules/@ERC4337/account-abstraction-v0.6/contracts/",
"account-abstraction/=lib/account-abstraction/contracts/",
"ds-test/=lib/erc7739Validator/node_modules/ds-test/src/",
"enumerableset4337/=lib/erc7739Validator/node_modules/@erc7579/enumerablemap4337/src/",
"erc4337-validation/=lib/erc7739Validator/node_modules/@rhinestone/erc4337-validation/src/",
"erc4626-tests/=lib/openzeppelin-contracts-upgradeable/lib/erc4626-tests/",
"erc7579/=lib/erc7739Validator/node_modules/erc7579/src/",
"hardhat-deploy/=node_modules/hardhat-deploy/",
"hardhat/=node_modules/hardhat/",
"kernel/=lib/erc7739Validator/node_modules/@zerodev/kernel/src/",
"module-bases/=lib/erc7739Validator/node_modules/@rhinestone/module-bases/src/",
"modulekit/=lib/erc7739Validator/node_modules/@rhinestone/modulekit/src/",
"safe7579/=lib/erc7739Validator/node_modules/@rhinestone/safe7579/src/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.