Ethereum Account Abstraction (AA) is an important technology for improving user experience and smart contract account functionality. Here's a comprehensive analysis of account abstraction:
Basic Concepts of Account Abstraction
Ethereum has two account types:
- Externally Owned Accounts (EOA): Controlled by private keys, no code
- Contract Accounts (CA): Controlled by code, has smart contracts
Account abstraction aims to make all accounts as flexible as smart contracts, providing richer functionality and better user experience.
EIP-4337: Account Abstraction Standard
1. Core Concepts
EIP-4337 implements account abstraction through entry point contracts and user operations without protocol layer changes.
2. Architecture Components
solidity// User operation structure struct UserOperation { address sender; // Sender account uint256 nonce; // Account nonce bytes initCode; // Initialization code (if new account) bytes callData; // Call data uint256 callGasLimit; // Call gas limit uint256 verificationGasLimit; // Verification gas limit uint256 preVerificationGas; // Pre-verification gas uint256 maxFeePerGas; // Maximum gas fee uint256 maxPriorityFeePerGas; // Maximum priority fee bytes paymasterAndData; // Paymaster data bytes signature; // Signature } // Entry point contract interface IEntryPoint { function handleOps( UserOperation[] calldata ops, address payable beneficiary ) external; function handleAggregatedOps( UserOpsPerAggregator[] calldata opsPerAggregator, address payable beneficiary ) external; }
Smart Contract Wallet Implementation
1. Basic Smart Contract Wallet
solidity// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; contract SmartWallet { address public owner; uint256 public nonce; IEntryPoint public entryPoint; event OwnerChanged(address indexed oldOwner, address indexed newOwner); event TransactionExecuted(address indexed target, uint256 value, bytes data); modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _; } constructor(address _owner, address _entryPoint) { owner = _owner; entryPoint = IEntryPoint(_entryPoint); } function execute(address target, uint256 value, bytes memory data) external { require(msg.sender == address(entryPoint), "Not entry point"); (bool success, ) = target.call{value: value}(data); require(success, "Execution failed"); emit TransactionExecuted(target, value, data); } function changeOwner(address newOwner) external { require(msg.sender == address(entryPoint), "Not entry point"); emit OwnerChanged(owner, newOwner); owner = newOwner; } function validateUserOp( UserOperation calldata userOp, bytes32 userOpHash, uint256 missingAccountFunds ) external returns (uint256 validationData) { require(msg.sender == address(entryPoint), "Not entry point"); // Verify signature bytes32 ethSignedMessageHash = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", userOpHash) ); address signer = recoverSigner(ethSignedMessageHash, userOp.signature); require(signer == owner, "Invalid signature"); // Pay missing funds if needed if (missingAccountFunds > 0) { payable(address(entryPoint)).transfer(missingAccountFunds); } return 0; // Validation successful } function recoverSigner(bytes32 messageHash, bytes memory signature) internal pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(signature); return ecrecover(messageHash, v, r, s); } function splitSignature(bytes memory sig) internal pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "Invalid signature length"); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } } receive() external payable {} }
2. Multi-Signature Wallet
soliditycontract MultiSigWallet { address[] public owners; mapping(address => bool) public isOwner; uint256 public required; uint256 public nonce; IEntryPoint public entryPoint; struct Transaction { address to; uint256 value; bytes data; bool executed; } mapping(uint256 => Transaction) public transactions; mapping(uint256 => mapping(address => bool)) public confirmations; event OwnerAdded(address indexed owner); event OwnerRemoved(address indexed owner); event RequirementChanged(uint256 required); event TransactionSubmitted(uint256 indexed txId); event TransactionConfirmed(uint256 indexed txId, address indexed owner); event TransactionExecuted(uint256 indexed txId); constructor(address[] memory _owners, uint256 _required, address _entryPoint) { require(_owners.length >= _required, "Invalid owners"); require(_required > 0, "Invalid required"); for (uint256 i = 0; i < _owners.length; i++) { require(!isOwner[_owners[i]], "Duplicate owner"); owners.push(_owners[i]); isOwner[_owners[i]] = true; emit OwnerAdded(_owners[i]); } required = _required; entryPoint = IEntryPoint(_entryPoint); } function executeTransaction( uint256 txId, address to, uint256 value, bytes memory data, bytes[] memory signatures ) external { require(msg.sender == address(entryPoint), "Not entry point"); // Verify signatures uint256 validSignatures = 0; for (uint256 i = 0; i < signatures.length; i++) { bytes32 txHash = keccak256(abi.encodePacked(txId, to, value, data, nonce)); bytes32 ethSignedMessageHash = keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", txHash) ); address signer = recoverSigner(ethSignedMessageHash, signatures[i]); if (isOwner[signer] && !confirmations[txId][signer]) { confirmations[txId][signer] = true; validSignatures++; emit TransactionConfirmed(txId, signer); } } require(validSignatures >= required, "Insufficient signatures"); require(!transactions[txId].executed, "Already executed"); transactions[txId] = Transaction({ to: to, value: value, data: data, executed: true }); (bool success, ) = to.call{value: value}(data); require(success, "Execution failed"); nonce++; emit TransactionExecuted(txId); } function recoverSigner(bytes32 messageHash, bytes memory signature) internal pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(signature); return ecrecover(messageHash, v, r, s); } function splitSignature(bytes memory sig) internal pure returns (bytes32 r, bytes32 s, uint8 v) { require(sig.length == 65, "Invalid signature length"); assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } } receive() external payable {} }
Paymaster
1. Gas Sponsorship
soliditycontract Paymaster { IEntryPoint public entryPoint; address public owner; mapping(address => uint256) public balances; event Deposit(address indexed account, uint256 amount); event Withdraw(address indexed account, uint256 amount); constructor(address _entryPoint) { entryPoint = IEntryPoint(_entryPoint); owner = msg.sender; } function deposit(address account) public payable { balances[account] += msg.value; emit Deposit(account, msg.value); } function withdraw(uint256 amount) public { require(balances[msg.sender] >= amount, "Insufficient balance"); balances[msg.sender] -= amount; payable(msg.sender).transfer(amount); emit Withdraw(msg.sender, amount); } function validatePaymasterUserOp( UserOperation calldata userOp, bytes32 userOpHash, uint256 maxCost ) external returns (bytes memory context, uint256 validationData) { require(msg.sender == address(entryPoint), "Not entry point"); address account = userOp.sender; require(balances[account] >= maxCost, "Insufficient balance"); return ("", 0); // Validation successful } function postOp( bytes calldata context, uint256 actualGasCost ) external { require(msg.sender == address(entryPoint), "Not entry point"); // Post-processing logic } receive() external payable {} }
Account Abstraction Advantages
1. Batch Transactions
soliditycontract BatchWallet { address public owner; IEntryPoint public entryPoint; struct BatchCall { address target; uint256 value; bytes data; } function executeBatch(BatchCall[] calldata calls) external { require(msg.sender == address(entryPoint), "Not entry point"); for (uint256 i = 0; i < calls.length; i++) { (bool success, ) = calls[i].target.call{value: calls[i].value}(calls[i].data); require(success, "Execution failed"); } } }
2. Social Recovery
soliditycontract SocialRecoveryWallet { address[] public guardians; mapping(address => bool) public isGuardian; address public owner; uint256 public recoveryThreshold; IEntryPoint public entryPoint; struct RecoveryRequest { address newOwner; uint256 timestamp; mapping(address => bool) approvals; uint256 approvalCount; } mapping(uint256 => RecoveryRequest) public recoveryRequests; uint256 public recoveryNonce; event GuardianAdded(address indexed guardian); event GuardianRemoved(address indexed guardian); event RecoveryRequested(uint256 indexed requestId, address indexed newOwner); event RecoveryApproved(uint256 indexed requestId, address indexed guardian); event RecoveryExecuted(uint256 indexed requestId, address indexed newOwner); constructor(address[] memory _guardians, uint256 _threshold, address _entryPoint) { for (uint256 i = 0; i < _guardians.length; i++) { guardians.push(_guardians[i]); isGuardian[_guardians[i]] = true; emit GuardianAdded(_guardians[i]); } recoveryThreshold = _threshold; entryPoint = IEntryPoint(_entryPoint); owner = msg.sender; } function requestRecovery(address newOwner) external { require(isGuardian[msg.sender], "Not guardian"); uint256 requestId = recoveryNonce; RecoveryRequest storage request = recoveryRequests[requestId]; request.newOwner = newOwner; request.timestamp = block.timestamp; emit RecoveryRequested(requestId, newOwner); recoveryNonce++; } function approveRecovery(uint256 requestId) external { require(isGuardian[msg.sender], "Not guardian"); RecoveryRequest storage request = recoveryRequests[requestId]; require(!request.approvals[msg.sender], "Already approved"); request.approvals[msg.sender] = true; request.approvalCount++; emit RecoveryApproved(requestId, msg.sender); if (request.approvalCount >= recoveryThreshold) { owner = request.newOwner; emit RecoveryExecuted(requestId, request.newOwner); } } }
3. Transaction Limits
soliditycontract LimitWallet { address public owner; IEntryPoint public entryPoint; uint256 public dailyLimit; uint256 public dailySpent; uint256 public lastResetTime; event DailyLimitChanged(uint256 newLimit); event TransactionExecuted(address indexed target, uint256 value); constructor(uint256 _dailyLimit, address _entryPoint) { dailyLimit = _dailyLimit; entryPoint = IEntryPoint(_entryPoint); owner = msg.sender; lastResetTime = block.timestamp; } function execute(address target, uint256 value, bytes memory data) external { require(msg.sender == address(entryPoint), "Not entry point"); // Reset daily limit if (block.timestamp >= lastResetTime + 1 days) { dailySpent = 0; lastResetTime = block.timestamp; } // Check limit require(dailySpent + value <= dailyLimit, "Daily limit exceeded"); dailySpent += value; // Execute transaction (bool success, ) = target.call{value: value}(data); require(success, "Execution failed"); emit TransactionExecuted(target, value); } }
Account Abstraction Best Practices
- Security First: Thoroughly test smart contract wallets
- User Experience: Provide clear interface and guidance
- Gas Optimization: Optimize gas usage
- Backup Recovery: Implement multiple recovery methods
- Permission Management: Fine-grained permission control
- Audit Monitoring: Regular audits and monitoring
Famous Projects
- ERC-4337: Account abstraction standard
- Safe: Multi-signature wallet
- Argent: Smart contract wallet
- Gnosis Safe: Multi-signature solution
- WalletConnect: Wallet connection protocol
Account abstraction is changing the Ethereum user experience, making blockchain applications more accessible and widespread.