Verified contractPartialMIT
TimelockPolicy
Address0x58b3033536b630cc893ae2cc66e7abaac03ee91d
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.38
- Same code
1 more contract
Details
- Compiler
- solc 0.8.38+commit.1835d247
- Language
- solidity
- Optimization
- Yes, 10,000 runs
- EVM version
- cancun
- Via IR
- yes
- License
- MIT
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,389,582
- Creation transaction
- 0x4cbdea9659…1bd70a4620
9 files
- lib/kernel-7579-plugins/src/policies/TimelockPolicy.solmain18.74 KB
- lib/account-abstraction/contracts/interfaces/IAccountExecute.sol710 B
- lib/account-abstraction/contracts/interfaces/PackedUserOperation.sol1.47 KB
- lib/kernel-7579-plugins/src/base/PolicyBase.sol1.24 KB
- lib/kernel-7579-plugins/src/interfaces/IERC7579Modules.sol3.75 KB
- lib/kernel-7579-plugins/src/types/Constants.sol592 B
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC4337.sol10.53 KB
- lib/openzeppelin-contracts/contracts/interfaces/draft-IERC7579.sol8.98 KB
- lib/solady/src/accounts/LibERC7579.sol14.15 KB
lib/kernel-7579-plugins/src/policies/TimelockPolicy.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PackedUserOperation} from "account-abstraction/interfaces/PackedUserOperation.sol";
import {IAccountExecute} from "account-abstraction/interfaces/IAccountExecute.sol";
import {IERC7579Execution} from "openzeppelin-contracts/contracts/interfaces/draft-IERC7579.sol";
import {LibERC7579} from "solady/accounts/LibERC7579.sol";
import {IModule, IStatelessValidator, IStatelessValidatorWithSender} from "src/interfaces/IERC7579Modules.sol";
import {PolicyBase} from "src/base/PolicyBase.sol";
import {
MODULE_TYPE_POLICY,
MODULE_TYPE_STATELESS_VALIDATOR,
MODULE_TYPE_STATELESS_VALIDATOR_WITH_SENDER,
SIG_VALIDATION_FAILED_UINT
} from "src/types/Constants.sol";
/**
* @title TimelockPolicy
* @notice A policy module that enforces time-delayed execution of transactions for enhanced security
* @dev Users must first create a proposal, wait for the timelock delay, then execute
*
* SECURITY: Signer Trust Assumption
* This policy trusts whichever signer module is configured on the permission.
* It does NOT independently verify who signed the UserOp — that responsibility
* belongs to the signer module (e.g., ECDSASigner, WeightedECDSASigner).
* The signer validates the signature; this policy only enforces the timelock.
*
* SECURITY: Nonce Isolation
* Proposals are keyed by keccak256(account, keccak256(callData), nonce).
* The nonce here is the full ERC-4337 nonce (192-bit key | 64-bit sequence).
* Each permission has a distinct nonce key, so proposals under different
* permissions are naturally isolated — a proposal created under permission A
* cannot be executed under permission B.
*
* SECURITY: Guardian Design
* The guardian is a CANCELLATION-ONLY role. It cannot create or execute proposals.
* The guardian is scoped per (policyId, wallet) — a guardian for one policy/wallet
* pair cannot cancel proposals belonging to another pair. Guardian is set at install
* time and persists until uninstall. Setting guardian to address(0) disables the
* guardian feature, meaning only the account itself can cancel proposals.
*/
contract TimelockPolicy is PolicyBase, IStatelessValidator, IStatelessValidatorWithSender {
enum ProposalStatus {
None, // Proposal doesn't exist
Pending, // Clock started, waiting for timelock
Executed, // Proposal executed
Cancelled // Proposal cancelled
}
struct TimelockConfig {
uint48 delay; // Timelock delay in seconds
uint48 expirationPeriod; // How long after validAfter the proposal remains valid
address guardian; // Address that can cancel proposals without timelock (address(0) = no guardian)
bool initialized;
}
struct Proposal {
ProposalStatus status;
uint48 validAfter; // Timestamp when timelock passes and proposal becomes executable
uint48 validUntil; // Timestamp when proposal expires
uint256 epoch; // Epoch when proposal was created
}
// Storage: id => wallet => config
mapping(bytes32 => mapping(address => TimelockConfig)) public timelockConfig;
// Storage: id => wallet => epoch (persists across uninstall/reinstall)
mapping(bytes32 => mapping(address => uint256)) public currentEpoch;
// Storage: userOpKey => id => wallet => proposal
// userOpKey = keccak256(abi.encode(account, keccak256(callData), nonce))
mapping(bytes32 => mapping(bytes32 => mapping(address => Proposal))) public proposals;
event ProposalCreated(
address indexed wallet, bytes32 indexed id, bytes32 indexed proposalHash, uint256 validAfter, uint256 validUntil
);
event ProposalExecuted(address indexed wallet, bytes32 indexed id, bytes32 indexed proposalHash);
event ProposalCancelled(address indexed wallet, bytes32 indexed id, bytes32 indexed proposalHash);
event TimelockConfigUpdated(
address indexed wallet, bytes32 indexed id, uint256 delay, uint256 expirationPeriod, address guardian
);
error InvalidDelay();
error InvalidExpirationPeriod();
error ProposalNotPending();
error OnlyAccount();
error ParametersTooLarge();
error SignatureValidationNotSupported();
error StatelessValidationNotSupported();
/**
* @notice Install the timelock policy
* @param _data Encoded: (uint48 delay, uint48 expirationPeriod, address guardian)
*/
function _policyOninstall(bytes32 id, bytes calldata _data) internal override {
(uint48 delay, uint48 expirationPeriod, address guardian) = abi.decode(_data, (uint48, uint48, address));
if (timelockConfig[id][msg.sender].initialized) {
revert IModule.AlreadyInitialized(msg.sender);
}
if (delay == 0) revert InvalidDelay();
if (expirationPeriod == 0) revert InvalidExpirationPeriod();
// Prevent uint48 overflow: uint48(block.timestamp) + delay + expirationPeriod
if (uint256(delay) + uint256(expirationPeriod) > type(uint48).max - block.timestamp) {
revert ParametersTooLarge();
}
// Increment epoch to invalidate any proposals from previous installations
currentEpoch[id][msg.sender]++;
timelockConfig[id][msg.sender] =
TimelockConfig({delay: delay, expirationPeriod: expirationPeriod, guardian: guardian, initialized: true});
emit TimelockConfigUpdated(msg.sender, id, delay, expirationPeriod, guardian);
}
/**
* @notice Uninstall the timelock policy
*/
function _policyOnUninstall(bytes32 id, bytes calldata) internal override {
if (!timelockConfig[id][msg.sender].initialized) {
revert IModule.NotInitialized(msg.sender);
}
delete timelockConfig[id][msg.sender];
}
/**
* @notice Check if this module is a specific type
* @dev Supports policy and stateless validator types
*/
function isModuleType(uint256 moduleTypeId) external pure override(IModule, PolicyBase) returns (bool) {
return moduleTypeId == MODULE_TYPE_POLICY || moduleTypeId == MODULE_TYPE_STATELESS_VALIDATOR
|| moduleTypeId == MODULE_TYPE_STATELESS_VALIDATOR_WITH_SENDER;
}
/**
* @notice Cancel a pending proposal
* @dev Only the account itself or its designated guardian can cancel proposals
* @param id The policy ID
* @param account The account address
* @param callData The calldata of the proposal
* @param nonce The nonce of the proposal
*/
function cancelProposal(bytes32 id, address account, bytes calldata callData, uint256 nonce) external {
// Only the account itself or the designated guardian can cancel proposals
address guardianAddr = timelockConfig[id][account].guardian;
if (msg.sender != account && (guardianAddr == address(0) || msg.sender != guardianAddr)) revert OnlyAccount();
TimelockConfig storage config = timelockConfig[id][account];
if (!config.initialized) revert IModule.NotInitialized(account);
// Create userOp key to look up the proposal
bytes32 userOpKey = keccak256(abi.encode(account, keccak256(callData), nonce));
Proposal storage proposal = proposals[userOpKey][id][account];
if (proposal.status != ProposalStatus.Pending) {
revert ProposalNotPending();
}
proposal.status = ProposalStatus.Cancelled;
emit ProposalCancelled(account, id, userOpKey);
}
/**
* @notice Check user operation against timelock policy
* @dev Called by the smart account during validation phase
* If calldata is a no-op and signature contains proposal data, creates a proposal
* Otherwise, executes an existing proposal
* @param id The policy ID
* @param userOp The user operation to validate
* @return validationData Packed validation data (ERC-4337 format)
* Format: <validAfter (6 bytes)><validUntil (6 bytes)><authorizer/result (20 bytes)>
* Returns 1 if validation fails or proposal created
*/
function checkUserOpPolicy(bytes32 id, PackedUserOperation calldata userOp)
external
payable
override
returns (uint256)
{
return _validateUserOpPolicy(id, userOp, userOp.signature, msg.sender);
}
/**
* @notice Handle proposal creation from a no-op UserOp
* @dev Called when the session key holder submits a no-op UserOp with proposal data in the signature.
* Creates a new Pending proposal with the timelock clock started.
* Signature format: [callDataLength(32)][callData][nonce(32)][remaining sig data]
*/
function _handleProposalCreationInternal(
bytes32 id,
PackedUserOperation calldata userOp,
TimelockConfig storage config,
bytes calldata sig,
address account
) internal returns (uint256) {
// Decode proposal data from signature
// Format: [callDataLength(32 bytes)][callData][nonce(32 bytes)][...]
uint256 callDataLength = uint256(bytes32(sig[0:32]));
// Validate signature has enough data (check callDataLength first to prevent overflow)
if (callDataLength > sig.length || sig.length < 64 + callDataLength) return SIG_VALIDATION_FAILED_UINT;
bytes calldata proposalCallData = sig[32:32 + callDataLength];
uint256 proposalNonce = uint256(bytes32(sig[32 + callDataLength:64 + callDataLength]));
// Calculate proposal timing
uint48 validAfter = uint48(block.timestamp) + config.delay;
uint48 validUntil = validAfter + config.expirationPeriod;
// Create userOp key for storage lookup (using PROPOSAL calldata and nonce, not current userOp)
bytes32 userOpKey = keccak256(abi.encode(userOp.sender, keccak256(proposalCallData), proposalNonce));
Proposal storage proposal = proposals[userOpKey][id][account];
if (proposal.status != ProposalStatus.None) {
return SIG_VALIDATION_FAILED_UINT;
}
// Create proposal with current epoch
proposals[userOpKey][id][account] = Proposal({
status: ProposalStatus.Pending,
validAfter: validAfter,
validUntil: validUntil,
epoch: currentEpoch[id][account]
});
emit ProposalCreated(account, id, userOpKey, validAfter, validUntil);
return _packValidationData(0, 0);
}
/**
* @notice Handle proposal execution from userOp
* @dev Returns validAfter/validUntil so EntryPoint enforces the timelock window.
* The guardian mechanism provides the cancellation path (not a grace period).
*/
function _handleProposalExecutionInternal(bytes32 id, PackedUserOperation calldata userOp, address account)
internal
returns (uint256)
{
// Create userOp key to look up the proposal
bytes32 userOpKey = keccak256(abi.encode(userOp.sender, keccak256(userOp.callData), userOp.nonce));
Proposal storage proposal = proposals[userOpKey][id][account];
// Check proposal exists and is pending
if (proposal.status != ProposalStatus.Pending) return SIG_VALIDATION_FAILED_UINT;
// Check proposal is from current epoch (not a stale proposal from previous installation)
if (proposal.epoch != currentEpoch[id][account]) return SIG_VALIDATION_FAILED_UINT;
// Mark as executed
proposal.status = ProposalStatus.Executed;
emit ProposalExecuted(account, id, userOpKey);
return _packValidationData(proposal.validAfter, proposal.validUntil);
}
/**
* @notice Check if calldata is a no-op operation
* @dev Recognizes 4 forms of no-op:
* 1. Empty calldata
* 2. ERC-7579 execute(mode=0x00, abi.encodePacked(address(0), uint256(0))) — single-call, zero-target, zero-value, no inner calldata
* 3. executeUserOp + empty inner calldata (just the 4-byte selector)
* 4. executeUserOp + ERC-7579 execute no-op (selector + form 2)
*/
function _isNoOpCalldata(bytes calldata callData) internal pure returns (bool) {
uint256 len = callData.length;
// Case 1: Empty calldata
if (len == 0) return true;
// Case 2: ERC-7579 execute with minimal no-op execution data
if (_isNoOpERC7579Execute(callData)) return true;
// Cases 3 & 4: executeUserOp wrapper
if (len >= 4 && bytes4(callData[0:4]) == IAccountExecute.executeUserOp.selector) {
// Case 3: executeUserOp + empty (just the selector, no inner data)
if (len == 4) return true;
// Case 4: executeUserOp + ERC-7579 execute no-op
if (_isNoOpERC7579Execute(callData[4:])) return true;
}
return false;
}
/**
* @notice Check if calldata is an ERC-7579 execute call that performs a zero-value no-op
* @dev execute(bytes32 mode, bytes calldata executionCalldata) where:
* - mode is CALLTYPE_SINGLE (not batch/delegatecall)
* - executionCalldata decodes via LibERC7579.decodeSingle() to (address(0), 0, empty)
* - target is address(0) (a non-zero target could trigger receive()/fallback() side effects)
* - value is 0 (no ETH transfer)
* - no inner calldata
*/
function _isNoOpERC7579Execute(bytes calldata callData) internal pure returns (bool) {
// Minimum: selector(4) + mode(32) + ABI bytes header: offset(32) + length(32) = 100
if (callData.length < 100) return false;
if (bytes4(callData[0:4]) != IERC7579Execution.execute.selector) return false;
// Decode mode and check call type via LibERC7579
bytes32 mode = bytes32(callData[4:36]);
if (LibERC7579.getCallType(mode) != LibERC7579.CALLTYPE_SINGLE) return false;
// Extract executionCalldata from ABI-encoded bytes parameter
uint256 offset = uint256(bytes32(callData[36:68]));
uint256 lenPos = 4 + offset;
if (callData.length < lenPos + 32) return false;
uint256 dataLen = uint256(bytes32(callData[lenPos:lenPos + 32]));
uint256 dataPos = lenPos + 32;
if (callData.length < dataPos + dataLen) return false;
bytes calldata executionCalldata = callData[dataPos:dataPos + dataLen];
// decodeSingle requires length > 0x33 (target(20) + value(32) minimum)
if (executionCalldata.length <= 0x33) return false;
// Use LibERC7579 to decode — same decoding path the account uses
(address target, uint256 val, bytes calldata innerCalldata) = LibERC7579.decodeSingle(executionCalldata);
// No-op: zero target, zero value, and no inner calldata
return target == address(0) && val == 0 && innerCalldata.length == 0;
}
/**
* @notice Pack validAfter and validUntil into validation data (ERC-4337 format)
* @dev Format: <validAfter (6 bytes)><validUntil (6 bytes)><authorizer/result (20 bytes)>
* Bits 0-159: authorizer (address) or 0 for success, 1 for failure
* Bits 160-207: validUntil (uint48)
* Bits 208-255: validAfter (uint48)
* @param validAfter Timestamp when the operation becomes valid
* @param validUntil Timestamp when the operation expires
* @return validationData Packed validation data
*/
function _packValidationData(uint48 validAfter, uint48 validUntil) internal pure returns (uint256) {
return uint256(validAfter) << 208 | uint256(validUntil) << 160;
}
/**
* @notice Check signature against timelock policy (for ERC-1271)
* @dev TimelockPolicy does not support ERC-1271 signature validation - always reverts
*/
function checkSignaturePolicy(bytes32, address, bytes32, bytes calldata) external pure override returns (uint256) {
revert SignatureValidationNotSupported();
}
function validateSignatureWithData(bytes32, bytes calldata, bytes calldata)
external
pure
override(IStatelessValidator)
returns (bool)
{
revert StatelessValidationNotSupported();
}
function validateSignatureWithDataWithSender(address, bytes32, bytes calldata, bytes calldata)
external
pure
override(IStatelessValidatorWithSender)
returns (bool)
{
revert StatelessValidationNotSupported();
}
// ==================== Internal Shared Logic ====================
/**
* @notice Internal function to validate user operation policy
* @dev Shared logic for both installed and stateless validator modes
*/
function _validateUserOpPolicy(bytes32 id, PackedUserOperation calldata userOp, bytes calldata sig, address account)
internal
returns (uint256)
{
TimelockConfig storage config = timelockConfig[id][account];
if (!config.initialized) return SIG_VALIDATION_FAILED_UINT;
// Check if this is a proposal creation request (no-op calldata with proposal data in sig)
if (_isNoOpCalldata(userOp.callData)) {
return _handleProposalCreationInternal(id, userOp, config, sig, account);
}
// Otherwise, this is a proposal execution request
return _handleProposalExecutionInternal(id, userOp, account);
}
/**
* @notice Get proposal details
* @param account The account address
* @param callData The calldata
* @param nonce The nonce
* @param id The policy ID
* @param wallet The wallet address
* @return status The proposal status
* @return validAfter When the timelock passes and proposal becomes executable
* @return validUntil When the proposal expires
*/
function getProposal(address account, bytes calldata callData, uint256 nonce, bytes32 id, address wallet)
external
view
returns (ProposalStatus status, uint256 validAfter, uint256 validUntil)
{
bytes32 userOpKey = keccak256(abi.encode(account, keccak256(callData), nonce));
Proposal storage proposal = proposals[userOpKey][id][wallet];
return (proposal.status, proposal.validAfter, proposal.validUntil);
}
/**
* @notice Compute the user operation key for storage lookup
* @param account The account address
* @param callData The calldata
* @param nonce The nonce
* @return The user operation key
*/
function computeUserOpKey(address account, bytes calldata callData, uint256 nonce) external pure returns (bytes32) {
return keccak256(abi.encode(account, keccak256(callData), nonce));
}
}
lib/account-abstraction/contracts/interfaces/IAccountExecute.sol
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.5;
import "./PackedUserOperation.sol";
interface IAccountExecute {
/**
* 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)
*
* @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;
}
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/kernel-7579-plugins/src/base/PolicyBase.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IPolicy} from "src/interfaces/IERC7579Modules.sol";
import {PackedUserOperation} from "account-abstraction/interfaces/PackedUserOperation.sol";
abstract contract PolicyBase is IPolicy {
function onInstall(bytes calldata data) external payable {
bytes32 id = bytes32(data[0:32]);
bytes calldata _data = data[32:];
_policyOninstall(id, _data);
}
function onUninstall(bytes calldata data) external payable {
bytes32 id = bytes32(data[0:32]);
bytes calldata _data = data[32:];
_policyOnUninstall(id, _data);
}
function isModuleType(uint256 id) external pure virtual returns (bool) {
return id == 5;
}
function checkUserOpPolicy(bytes32 id, PackedUserOperation calldata userOp)
external
payable
virtual
returns (uint256);
function checkSignaturePolicy(bytes32 id, address sender, bytes32 hash, bytes calldata sig)
external
view
virtual
returns (uint256);
function _policyOninstall(bytes32 id, bytes calldata _data) internal virtual;
function _policyOnUninstall(bytes32 id, bytes calldata _data) internal virtual;
}
lib/kernel-7579-plugins/src/interfaces/IERC7579Modules.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.21;
import {PackedUserOperation} from "account-abstraction/interfaces/PackedUserOperation.sol";
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 payable;
/**
* @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 payable;
/**
* @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);
}
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 validation phase
* Note: solely relying on bytes32 hash and signature is not sufficient 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 payable 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
payable
returns (bytes memory hookData);
function postCheck(bytes calldata hookData) external payable;
}
interface IFallback is IModule {}
interface IPolicy is IModule {
function checkUserOpPolicy(bytes32 id, PackedUserOperation calldata userOp) external payable returns (uint256);
function checkSignaturePolicy(bytes32 id, address sender, bytes32 hash, bytes calldata sig)
external
view
returns (uint256);
}
interface ISigner is IModule {
function checkUserOpSignature(bytes32 id, PackedUserOperation calldata userOp, bytes32 userOpHash)
external
payable
returns (uint256);
function checkSignature(bytes32 id, address sender, bytes32 hash, bytes calldata sig) external view returns (bytes4);
}
interface IStatelessValidator is IModule {
function validateSignatureWithData(bytes32 hash, bytes calldata signature, bytes calldata data)
external
view
returns (bool);
}
interface IStatelessValidatorWithSender is IModule {
function validateSignatureWithDataWithSender(
address sender,
bytes32 hash,
bytes calldata signature,
bytes calldata data
) external view returns (bool);
}
lib/kernel-7579-plugins/src/types/Constants.sol
pragma solidity ^0.8.0;
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_POLICY = 5;
uint256 constant MODULE_TYPE_SIGNER = 6;
uint256 constant MODULE_TYPE_STATELESS_VALIDATOR = 7;
uint256 constant MODULE_TYPE_STATELESS_VALIDATOR_WITH_SENDER = 10;
bytes4 constant ERC1271_MAGICVALUE = 0x1626ba7e;
bytes4 constant ERC1271_INVALID = 0xffffffff;
uint256 constant SIG_VALIDATION_FAILED_UINT = 1;
uint256 constant SIG_VALIDATION_SUCCESS_UINT = 0;
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC4337.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (interfaces/draft-IERC4337.sol)
pragma solidity >=0.8.4;
/**
* @dev A https://github.com/ethereum/ercs/blob/master/ERCS/erc-4337.md#useroperation[user operation] is composed of the following elements:
* - `sender` (`address`): The account making the operation
* - `nonce` (`uint256`): Anti-replay parameter (see “Semi-abstracted Nonce Support” )
* - `factory` (`address`): account factory, only for new accounts
* - `factoryData` (`bytes`): data for account factory (only if account factory exists)
* - `callData` (`bytes`): The data to pass to the sender during the main execution call
* - `callGasLimit` (`uint256`): The amount of gas to allocate the main execution call
* - `verificationGasLimit` (`uint256`): The amount of gas to allocate for the verification step
* - `preVerificationGas` (`uint256`): Extra gas to pay the bundler
* - `maxFeePerGas` (`uint256`): Maximum fee per gas (similar to EIP-1559 max_fee_per_gas)
* - `maxPriorityFeePerGas` (`uint256`): Maximum priority fee per gas (similar to EIP-1559 max_priority_fee_per_gas)
* - `paymaster` (`address`): Address of paymaster contract, (or empty, if account pays for itself)
* - `paymasterVerificationGasLimit` (`uint256`): The amount of gas to allocate for the paymaster validation code
* - `paymasterPostOpGasLimit` (`uint256`): The amount of gas to allocate for the paymaster post-operation code
* - `paymasterData` (`bytes`): Data for paymaster (only if paymaster exists)
* - `signature` (`bytes`): Data passed into the account to verify authorization
*
* When passed to on-chain contracts, the following packed version is used.
* - `sender` (`address`)
* - `nonce` (`uint256`)
* - `initCode` (`bytes`): concatenation of factory address and factoryData (or empty)
* - `callData` (`bytes`)
* - `accountGasLimits` (`bytes32`): concatenation of verificationGas (16 bytes) and callGas (16 bytes)
* - `preVerificationGas` (`uint256`)
* - `gasFees` (`bytes32`): concatenation of maxPriorityFeePerGas (16 bytes) and maxFeePerGas (16 bytes)
* - `paymasterAndData` (`bytes`): concatenation of paymaster fields (or empty)
* For EntryPoint v0.9+, may optionally include `paymasterSignature` at the end:
* `paymaster || paymasterVerificationGasLimit || paymasterPostOpGasLimit || paymasterData || paymasterSignature || paymasterSignatureSize || PAYMASTER_SIG_MAGIC`
* - `signature` (`bytes`)
*/
struct PackedUserOperation {
address sender;
uint256 nonce;
bytes initCode; // `abi.encodePacked(factory, factoryData)`
bytes callData;
bytes32 accountGasLimits; // `abi.encodePacked(verificationGasLimit, callGasLimit)` 16 bytes each
uint256 preVerificationGas;
bytes32 gasFees; // `abi.encodePacked(maxPriorityFeePerGas, maxFeePerGas)` 16 bytes each
bytes paymasterAndData; // `abi.encodePacked(paymaster, paymasterVerificationGasLimit, paymasterPostOpGasLimit, paymasterData[, paymasterSignature, paymasterSignatureSize, PAYMASTER_SIG_MAGIC])` (20 bytes, 16 bytes, 16 bytes, dynamic[, dynamic, 2 bytes, 8 bytes])
bytes signature;
}
/**
* @dev Aggregates and validates multiple signatures for a batch of user operations.
*
* A contract could implement this interface with custom validation schemes that allow signature aggregation,
* enabling significant optimizations and gas savings for execution and transaction data cost.
*
* Bundlers and clients whitelist supported aggregators.
*
* See https://eips.ethereum.org/EIPS/eip-7766[ERC-7766]
*/
interface IAggregator {
/**
* @dev Validates the signature for a user operation.
* Returns an alternative signature that should be used during bundling.
*/
function validateUserOpSignature(
PackedUserOperation calldata userOp
) external view returns (bytes memory sigForUserOp);
/**
* @dev Returns an aggregated signature for a batch of user operation's signatures.
*/
function aggregateSignatures(
PackedUserOperation[] calldata userOps
) external view returns (bytes memory aggregatesSignature);
/**
* @dev Validates that the aggregated signature is valid for the user operations.
*
* Requirements:
*
* - The aggregated signature MUST match the given list of operations.
*/
function validateSignatures(PackedUserOperation[] calldata userOps, bytes calldata signature) external view;
}
/**
* @dev Handle nonce management for accounts.
*
* Nonces are used in accounts as a replay protection mechanism and to ensure the order of user operations.
* To avoid limiting the number of operations an account can perform, the interface allows using parallel
* nonces by using a `key` parameter.
*
* See https://eips.ethereum.org/EIPS/eip-4337#semi-abstracted-nonce-support[ERC-4337 semi-abstracted nonce support].
*/
interface IEntryPointNonces {
/**
* @dev Returns the nonce for a `sender` account and a `key`.
*
* Nonces for a certain `key` are always increasing.
*/
function getNonce(address sender, uint192 key) external view returns (uint256 nonce);
}
/**
* @dev Handle stake management for entities (i.e. accounts, paymasters, factories).
*
* The EntryPoint must implement the following API to let entities like paymasters have a stake,
* and thus have more flexibility in their storage access
* (see https://eips.ethereum.org/EIPS/eip-4337#reputation-scoring-and-throttlingbanning-for-global-entities[reputation, throttling and banning.])
*/
interface IEntryPointStake {
/**
* @dev Returns the balance of the account.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Deposits `msg.value` to the account.
*/
function depositTo(address account) external payable;
/**
* @dev Withdraws `withdrawAmount` from the account to `withdrawAddress`.
*/
function withdrawTo(address payable withdrawAddress, uint256 withdrawAmount) external;
/**
* @dev Adds stake to the account with an unstake delay of `unstakeDelaySec`.
*/
function addStake(uint32 unstakeDelaySec) external payable;
/**
* @dev Unlocks the stake of the account.
*/
function unlockStake() external;
/**
* @dev Withdraws the stake of the account to `withdrawAddress`.
*/
function withdrawStake(address payable withdrawAddress) external;
}
/**
* @dev Entry point for user operations.
*
* User operations are validated and executed by this contract.
*/
interface IEntryPoint is IEntryPointNonces, IEntryPointStake {
/**
* @dev A user operation at `opIndex` failed with `reason`.
*/
error FailedOp(uint256 opIndex, string reason);
/**
* @dev A user operation at `opIndex` failed with `reason` and `inner` returned data.
*/
error FailedOpWithRevert(uint256 opIndex, string reason, bytes inner);
/**
* @dev Batch of aggregated user operations per aggregator.
*/
struct UserOpsPerAggregator {
PackedUserOperation[] userOps;
IAggregator aggregator;
bytes signature;
}
/**
* @dev Executes a batch of user operations.
* @param beneficiary Address to which gas is refunded upon completing the execution.
*/
function handleOps(PackedUserOperation[] calldata ops, address payable beneficiary) external;
/**
* @dev Executes a batch of aggregated user operations per aggregator.
* @param beneficiary Address to which gas is refunded upon completing the execution.
*/
function handleAggregatedOps(
UserOpsPerAggregator[] calldata opsPerAggregator,
address payable beneficiary
) external;
}
/**
* @dev Base interface for an ERC-4337 account.
*/
interface IAccount {
/**
* @dev Validates a user operation.
*
* * MUST validate the caller is a trusted EntryPoint
* * MUST validate that the signature is a valid signature of the userOpHash, and SHOULD
* return SIG_VALIDATION_FAILED (and not revert) on signature mismatch. Any other error MUST revert.
* * MUST pay the entryPoint (caller) at least the “missingAccountFunds” (which might
* be zero, in case the current account’s deposit is high enough)
*
* Returns an encoded packed validation data that is composed of the following elements:
*
* - `authorizer` (`address`): 0 for success, 1 for failure, otherwise the address of an authorizer contract
* - `validUntil` (`uint48`): The UserOp is valid only up to this time. Zero for “infinite”.
* - `validAfter` (`uint48`): The UserOp is valid only after this time.
*/
function validateUserOp(
PackedUserOperation calldata userOp,
bytes32 userOpHash,
uint256 missingAccountFunds
) external returns (uint256 validationData);
}
/**
* @dev Support for executing user operations by prepending the {executeUserOp} function selector
* to the UserOperation's `callData`.
*/
interface IAccountExecute {
/**
* @dev Executes a user operation.
*/
function executeUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external;
}
/**
* @dev Interface for a paymaster contract that agrees to pay for the gas costs of a user operation.
*
* NOTE: A paymaster must hold a stake to cover the required entrypoint stake and also the gas for the transaction.
*/
interface IPaymaster {
enum PostOpMode {
opSucceeded,
opReverted,
postOpReverted
}
/**
* @dev Validates whether the paymaster is willing to pay for the user operation. See
* {IAccount-validateUserOp} for additional information on the return value.
*
* NOTE: Bundlers will reject this method if it modifies the state, unless it's whitelisted.
*/
function validatePaymasterUserOp(
PackedUserOperation calldata userOp,
bytes32 userOpHash,
uint256 maxCost
) external returns (bytes memory context, uint256 validationData);
/**
* @dev Verifies the sender is the entrypoint.
* @param actualGasCost the actual amount paid (by account or paymaster) for this UserOperation
* @param actualUserOpFeePerGas total gas used by this UserOperation (including preVerification, creation, validation and execution)
*/
function postOp(
PostOpMode mode,
bytes calldata context,
uint256 actualGasCost,
uint256 actualUserOpFeePerGas
) external;
}
lib/openzeppelin-contracts/contracts/interfaces/draft-IERC7579.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.6.0) (interfaces/draft-IERC7579.sol)
pragma solidity >=0.8.4;
import {PackedUserOperation} from "./draft-IERC4337.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;
/// @dev Minimal configuration interface for ERC-7579 modules
interface IERC7579Module {
/**
* @dev This function is called by the smart account during installation of the module
* @param data arbitrary data that may be passed to the module during `onInstall` initialization
*
* MUST revert on error (e.g. 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 passed to 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 ERC-7579 Validation module (type 1).
*
* A module that implements logic to validate user operations and signatures.
*/
interface IERC7579Validator is IERC7579Module {
/**
* @dev Validates a UserOperation
* @param userOp the ERC-4337 PackedUserOperation
* @param userOpHash the hash of the ERC-4337 PackedUserOperation
*
* MUST validate that the signature is a valid signature of the userOpHash
* SHOULD return ERC-4337's SIG_VALIDATION_FAILED (and not revert) on signature mismatch
* See {IAccount-validateUserOp} for additional information on the return value
*/
function validateUserOp(PackedUserOperation calldata userOp, bytes32 userOpHash) external returns (uint256);
/**
* @dev Validates a signature using ERC-1271
* @param sender the address that sent the ERC-1271 request to the smart account
* @param hash the hash of the ERC-1271 request
* @param signature the signature of the ERC-1271 request
*
* MUST return the ERC-1271 `MAGIC_VALUE` if the signature is valid
* MUST NOT modify state
*/
function isValidSignatureWithSender(
address sender,
bytes32 hash,
bytes calldata signature
) external view returns (bytes4);
}
/**
* @dev ERC-7579 Hooks module (type 4).
*
* A module that implements logic to execute before and after the account executes a user operation,
* either individually or batched.
*/
interface IERC7579Hook is IERC7579Module {
/**
* @dev Called by the smart account before execution
* @param msgSender the address that called the smart account
* @param value the value that was sent to the smart account
* @param msgData the data that was sent to the smart account
*
* MAY return arbitrary data in the `hookData` return value
*/
function preCheck(
address msgSender,
uint256 value,
bytes calldata msgData
) external returns (bytes memory hookData);
/**
* @dev Called by the smart account after execution
* @param hookData the data that was returned by the `preCheck` function
*
* MAY validate the `hookData` to validate transaction context of the `preCheck` function
*/
function postCheck(bytes calldata hookData) external;
}
struct Execution {
address target;
uint256 value;
bytes callData;
}
/**
* @dev ERC-7579 Execution.
*
* Accounts should implement this interface so that the Entrypoint and ERC-7579 modules can execute operations.
*/
interface IERC7579Execution {
/**
* @dev Executes a transaction on behalf of the account.
* @param mode The encoded execution mode of the transaction. See account/utils/draft-ERC7579Utils.sol (Mode encoding via encodeMode/decodeMode) for details
* @param executionCalldata The encoded execution call data
*
* MUST ensure adequate authorization control: e.g. onlyEntryPointOrSelf if used with ERC-4337
* If a mode is requested that is not supported by the Account, it MUST revert
*/
function execute(bytes32 mode, bytes calldata executionCalldata) external payable;
/**
* @dev Executes a transaction on behalf of the account.
* This function is intended to be called by Executor Modules
* @param mode The encoded execution mode of the transaction. See account/utils/draft-ERC7579Utils.sol (Mode encoding via encodeMode/decodeMode) for details
* @param executionCalldata The encoded execution call data
* @return returnData An array with the returned data of each executed subcall
*
* MUST ensure adequate authorization control: i.e. onlyExecutorModule
* If a mode is requested that is not supported by the Account, it MUST revert
*/
function executeFromExecutor(
bytes32 mode,
bytes calldata executionCalldata
) external payable returns (bytes[] memory returnData);
}
/**
* @dev ERC-7579 Account Config.
*
* Accounts should implement this interface to expose information that identifies the account, supported modules and capabilities.
*/
interface IERC7579AccountConfig {
/**
* @dev Returns the account id of the smart account
* @return accountImplementationId the account id of the smart account
*
* MUST return a non-empty string
* The accountId SHOULD be structured like so:
* "vendorname.accountname.semver"
* The id SHOULD be unique across all smart accounts
*/
function accountId() external view returns (string memory accountImplementationId);
/**
* @dev Function to check if the account supports a certain execution mode (see above)
* @param encodedMode the encoded mode
*
* MUST return true if the account supports the mode and false otherwise
*/
function supportsExecutionMode(bytes32 encodedMode) external view returns (bool);
/**
* @dev Function to check if the account supports a certain module typeId
* @param moduleTypeId the module type ID according to the ERC-7579 spec
*
* MUST return true if the account supports the module type and false otherwise
*/
function supportsModule(uint256 moduleTypeId) external view returns (bool);
}
/**
* @dev ERC-7579 Module Config.
*
* Accounts should implement this interface to allow installing and uninstalling modules.
*/
interface IERC7579ModuleConfig {
event ModuleInstalled(uint256 moduleTypeId, address module);
event ModuleUninstalled(uint256 moduleTypeId, address module);
/**
* @dev Installs a Module of a certain type on the smart account
* @param moduleTypeId the module type ID according to the ERC-7579 spec
* @param module the module address
* @param initData arbitrary data that may be passed to the module during `onInstall`
* initialization.
*
* MUST implement authorization control
* MUST call `onInstall` on the module with the `initData` parameter if provided
* MUST emit ModuleInstalled event
* MUST revert if the module is already installed or the initialization on the module failed
*/
function installModule(uint256 moduleTypeId, address module, bytes calldata initData) external;
/**
* @dev Uninstalls a Module of a certain type on the smart account
* @param moduleTypeId the module type ID according the ERC-7579 spec
* @param module the module address
* @param deInitData arbitrary data that may be passed to the module during `onUninstall`
* deinitialization.
*
* MUST implement authorization control
* MUST call `onUninstall` on the module with the `deInitData` parameter if provided
* MUST emit ModuleUninstalled event
* MUST revert if the module is not installed or the deInitialization on the module failed
*/
function uninstallModule(uint256 moduleTypeId, address module, bytes calldata deInitData) external;
/**
* @dev Returns whether a module is installed on the smart account
* @param moduleTypeId the module type ID according the ERC-7579 spec
* @param module the module address
* @param additionalContext arbitrary data that may be passed to determine if the module is installed
*
* MUST return true if the module is installed and false otherwise
*/
function isModuleInstalled(
uint256 moduleTypeId,
address module,
bytes calldata additionalContext
) external view returns (bool);
}
lib/solady/src/accounts/LibERC7579.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for handling ERC7579 mode and execution data.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/accounts/LibERC7579.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/main/contracts/account/utils/draft-ERC7579Utils.sol)
library LibERC7579 {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Cannot decode `executionData`.
error DecodingError();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev A single execution.
bytes1 internal constant CALLTYPE_SINGLE = 0x00;
/// @dev A batch of executions.
bytes1 internal constant CALLTYPE_BATCH = 0x01;
/// @dev A single `staticcall` execution.
bytes1 internal constant CALLTYPE_STATICCALL = 0xfe;
/// @dev A `delegatecall` execution.
bytes1 internal constant CALLTYPE_DELEGATECALL = 0xff;
/// @dev Default execution type that reverts on failure.
bytes1 internal constant EXECTYPE_DEFAULT = 0x00;
/// @dev Execution type that does not revert on failure.
bytes1 internal constant EXECTYPE_TRY = 0x01;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODE OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Encodes the fields into a mode.
function encodeMode(bytes1 callType, bytes1 execType, bytes4 selector, bytes22 payload)
internal
pure
returns (bytes32 result)
{
/// @solidity memory-safe-assembly
assembly {
result := or(shl(8, byte(0, callType)), byte(0, execType))
result := or(shr(224, selector), shl(64, result))
result := or(shr(80, payload), shl(176, result))
}
}
/// @dev Returns the call type of the mode.
function getCallType(bytes32 mode) internal pure returns (bytes1) {
return bytes1(mode);
}
/// @dev Returns the call type of the mode.
function getExecType(bytes32 mode) internal pure returns (bytes1) {
return mode[1];
}
/// @dev Returns the selector of the mode.
function getSelector(bytes32 mode) internal pure returns (bytes4) {
return bytes4(bytes32(uint256(mode) << 48));
}
/// @dev Returns the payload stored in the mode.
function getPayload(bytes32 mode) internal pure returns (bytes22) {
return bytes22(bytes32(uint256(mode) << 80));
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EXECUTION DATA OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Decodes a single call execution.
/// Reverts if `executionData` is not correctly encoded.
function decodeSingle(bytes calldata executionData)
internal
pure
returns (address target, uint256 value, bytes calldata data)
{
/// @solidity memory-safe-assembly
assembly {
if iszero(gt(executionData.length, 0x33)) {
mstore(0x00, 0xba597e7e) // `DecodingError()`.
revert(0x1c, 0x04)
}
target := shr(96, calldataload(executionData.offset))
value := calldataload(add(executionData.offset, 0x14))
data.offset := add(executionData.offset, 0x34)
data.length := sub(executionData.length, 0x34)
}
}
/// @dev Decodes a single call execution without bounds checks.
function decodeSingleUnchecked(bytes calldata executionData)
internal
pure
returns (address target, uint256 value, bytes calldata data)
{
/// @solidity memory-safe-assembly
assembly {
target := shr(96, calldataload(executionData.offset))
value := calldataload(add(executionData.offset, 0x14))
data.offset := add(executionData.offset, 0x34)
data.length := sub(executionData.length, 0x34)
}
}
/// @dev Decodes a single delegate execution.
/// Reverts if `executionData` is not correctly encoded.
function decodeDelegate(bytes calldata executionData)
internal
pure
returns (address target, bytes calldata data)
{
/// @solidity memory-safe-assembly
assembly {
if iszero(gt(executionData.length, 0x13)) {
mstore(0x00, 0xba597e7e) // `DecodingError()`.
revert(0x1c, 0x04)
}
target := shr(96, calldataload(executionData.offset))
data.offset := add(executionData.offset, 0x14)
data.length := sub(executionData.length, 0x14)
}
}
/// @dev Decodes a single delegate execution without bounds checks.
function decodeDelegateUnchecked(bytes calldata executionData)
internal
pure
returns (address target, bytes calldata data)
{
/// @solidity memory-safe-assembly
assembly {
target := shr(96, calldataload(executionData.offset))
data.offset := add(executionData.offset, 0x14)
data.length := sub(executionData.length, 0x14)
}
}
/// @dev Decodes a batch.
/// Reverts if `executionData` is not correctly encoded.
function decodeBatch(bytes calldata executionData)
internal
pure
returns (bytes32[] calldata pointers)
{
/// @solidity memory-safe-assembly
assembly {
let u := calldataload(executionData.offset)
let s := add(executionData.offset, u)
let e := sub(add(executionData.offset, executionData.length), 0x20)
pointers.offset := add(s, 0x20)
pointers.length := calldataload(s)
if or(shr(64, u), gt(add(s, shl(5, pointers.length)), e)) {
mstore(0x00, 0xba597e7e) // `DecodingError()`.
revert(0x1c, 0x04)
}
if pointers.length {
// Perform bounds checks on the decoded `pointers`.
// Loop runs out-of-gas if `pointers.length` is big enough to cause overflows.
for { let i := pointers.length } 1 {} {
i := sub(i, 1)
let p := calldataload(add(pointers.offset, shl(5, i)))
let c := add(pointers.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 }
}
}
}
}
/// @dev Decodes a batch without bounds checks.
/// This function can be used in `execute`, if the validation phase has already
/// decoded the `executionData` with checks via `decodeBatch`.
function decodeBatchUnchecked(bytes calldata executionData)
internal
pure
returns (bytes32[] calldata pointers)
{
/// @solidity memory-safe-assembly
assembly {
let o := add(executionData.offset, calldataload(executionData.offset))
pointers.offset := add(o, 0x20)
pointers.length := calldataload(o)
}
}
/// @dev Decodes a batch and optional `opData`.
/// Reverts if `executionData` is not correctly encoded.
function decodeBatchAndOpData(bytes calldata executionData)
internal
pure
returns (bytes32[] calldata pointers, bytes calldata opData)
{
opData = emptyCalldataBytes();
pointers = decodeBatch(executionData);
if (hasOpData(executionData)) {
/// @solidity memory-safe-assembly
assembly {
let e := sub(add(executionData.offset, executionData.length), 0x20)
let p := calldataload(add(0x20, executionData.offset))
let q := add(executionData.offset, p)
opData.offset := add(q, 0x20)
opData.length := calldataload(q)
if or(shr(64, or(opData.length, p)), gt(add(q, opData.length), e)) {
mstore(0x00, 0xba597e7e) // `DecodingError()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Decodes a batch without bounds checks.
/// This function can be used in `execute`, if the validation phase has already
/// decoded the `executionData` with checks via `decodeBatchAndOpData`.
function decodeBatchAndOpDataUnchecked(bytes calldata executionData)
internal
pure
returns (bytes32[] calldata pointers, bytes calldata opData)
{
opData = emptyCalldataBytes();
pointers = decodeBatchUnchecked(executionData);
if (hasOpData(executionData)) {
/// @solidity memory-safe-assembly
assembly {
let q := add(executionData.offset, calldataload(add(0x20, executionData.offset)))
opData.offset := add(q, 0x20)
opData.length := calldataload(q)
}
}
}
/// @dev Returns whether the `executionData` has optional `opData`.
function hasOpData(bytes calldata executionData) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
result :=
iszero(or(lt(executionData.length, 0x40), lt(calldataload(executionData.offset), 0x40)))
}
}
/// @dev Returns the `i`th execution at `pointers`, without bounds checks.
/// The bounds check is excluded as this function is intended to be called in a bounded loop.
function getExecution(bytes32[] calldata pointers, uint256 i)
internal
pure
returns (address target, uint256 value, bytes calldata data)
{
/// @solidity memory-safe-assembly
assembly {
let c := add(pointers.offset, calldataload(add(pointers.offset, shl(5, i))))
target := calldataload(c)
value := calldataload(add(c, 0x20))
let o := add(c, calldataload(add(c, 0x40)))
data.offset := add(o, 0x20)
data.length := calldataload(o)
}
}
/// @dev Reencodes `executionData` such that it has `opData` added to it.
/// Like `abi.encode(abi.decode(executionData, (Call[])), opData)`.
/// Useful for forwarding `executionData` with extra `opData`.
/// This function does not perform any check on the validity of `executionData`.
function reencodeBatch(bytes calldata executionData, bytes memory opData)
internal
pure
returns (bytes memory result)
{
/// @solidity memory-safe-assembly
assembly {
result := add(0x64, mload(0x40)) // Give some space for `reencodeBatchAsExecuteCalldata`.
let s := calldataload(executionData.offset) // Offset of `calls`.
let n := sub(executionData.length, s) // Byte length of `calls`.
mstore(add(result, 0x20), 0x40) // Store the new offset of `calls`.
calldatacopy(add(result, 0x60), add(executionData.offset, s), n)
mstore(add(result, 0x40), add(0x40, n)) // Store the new offset of `opData`.
let o := add(add(result, 0x60), n) // Start offset of `opData` destination in memory.
let d := sub(opData, o) // Offset difference between `opData` source and `o`.
let end := add(mload(opData), add(0x20, o)) // End of `opData` destination in memory.
for {} 1 {} {
mstore(o, mload(add(o, d)))
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(result, sub(o, add(result, 0x20))) // Store the length of `result`.
calldatacopy(end, calldatasize(), 0x40) // Zeroize the bytes after `end`.
mstore(0x40, add(0x20, o)) // Allocate memory.
}
}
/// @dev `abi.encodeWithSignature("execute(bytes32,bytes)", mode, reencodeBatch(executionData, opData))`.
function reencodeBatchAsExecuteCalldata(
bytes32 mode,
bytes calldata executionData,
bytes memory opData
) internal pure returns (bytes memory result) {
result = reencodeBatch(executionData, opData);
/// @solidity memory-safe-assembly
assembly {
let n := mload(result)
result := sub(result, 0x64)
mstore(add(result, 0x44), 0x40) // Offset of `executionData`.
mstore(add(result, 0x24), mode)
mstore(add(result, 0x04), 0xe9ae5c53) // `execute(bytes32,bytes)`.
mstore(result, add(0x64, n))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HELPERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Helper function to return empty calldata bytes.
function emptyCalldataBytes() internal pure returns (bytes calldata result) {
/// @solidity memory-safe-assembly
assembly {
result.offset := 0
result.length := 0
}
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"libraries": {},
"optimizer": {
"runs": 10000,
"enabled": true
},
"viaSSACFG": false,
"evmVersion": "cancun",
"remappings": [
"@openzeppelin/contracts/=lib/openzeppelin-contracts/contracts/",
"account-abstraction/=lib/account-abstraction/contracts/",
"forge-std/=lib/forge-std/src/",
"solady/=lib/solady/src/",
"kernel-7579-plugins/=lib/kernel-7579-plugins/src/",
"lib/kernel-7579-plugins/src/:src/=lib/kernel-7579-plugins/src/",
"erc4626-tests/=lib/openzeppelin-contracts/lib/erc4626-tests/",
"halmos-cheatcodes/=lib/openzeppelin-contracts/lib/halmos-cheatcodes/src/",
"openzeppelin-contracts/=lib/openzeppelin-contracts/"
],
"experimental": false
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.