Foundational principles enabling smart contract wallets and programmable transaction logic on Layer 2 networks.
Account Abstraction on Layer 2 for DeFi
Core Concepts of Account Abstraction
Smart Contract Wallets
Externally Owned Accounts (EOAs) are replaced by smart contracts as the primary wallet. This enables programmable logic for transaction validation, such as multi-signature schemes, social recovery, and spending limits. For DeFi, this allows batch transactions and gas sponsorship, significantly improving user experience and security on L2s like Arbitrum and Optimism.
Paymaster & Gas Abstraction
Paymaster contracts allow third parties to sponsor transaction fees or enable payment in ERC-20 tokens. This removes the need for users to hold the native gas token. In DeFi, protocols can subsidize onboarding costs, and dApps can offer gasless transactions, reducing friction for new users on networks like zkSync and Starknet.
User Operation & Bundler
UserOperations are pseudo-transaction objects representing a user's intent, which are submitted to a Bundler. The Bundler packages these operations into a single L1 transaction. This architecture enables advanced features like atomic multi-step DeFi operations (e.g., swap then supply) and efficient fee aggregation, optimizing for L2 rollup economics.
Signature Abstraction
Signature validation logic is decoupled from the elliptic curve scheme used by EOAs. Smart accounts can implement custom authorization, such as quantum-resistant signatures, session keys for dApps, or hardware security module (HSM) integration. This future-proofs DeFi interactions and enables secure, non-custodial delegation of specific transaction rights.
Account Factory & Deployment
Counterfactual addresses allow a smart account's address to be computed and used before it is deployed on-chain. This enables users to receive funds to a secure smart wallet address immediately. For DeFi, this simplifies onboarding; a user's wallet can be deployed with their first transaction, paid for by a paymaster.
EntryPoint Contract
The singleton EntryPoint contract is the central, trusted verification and execution hub for all UserOperations. It standardizes account abstraction logic, ensuring security and interoperability across different smart account implementations. This contract handles paymaster verification and execution, forming the core infrastructure layer for AA on Ethereum and its L2s.
Account Abstraction on Major Layer 2s
Understanding the Basics
Account Abstraction (AA) allows you to use smart contracts as your primary wallet, enabling features like social recovery, gas sponsorship, and batch transactions. On Layer 2s, this makes DeFi interactions cheaper and more flexible.
Key Advantages
- Gas Sponsorship: Protocols like Base's
paymastercan pay your transaction fees, removing the need to hold the native token (e.g., ETH) for gas. - Batch Transactions: Execute multiple actions (e.g., approve and swap on Uniswap) in a single transaction, saving time and cost.
- Enhanced Security: Set up recovery mechanisms using social logins or hardware wallets, moving beyond a single vulnerable private key.
Practical Example
When swapping tokens on a DEX like Uniswap V3 on Arbitrum, an abstracted account could bundle the token approval and the swap into one transaction. A sponsor could pay the gas fee in USDC, so you don't need to manage ETH for gas.
Deploy and Fund a Smart Account
Process overview
Initialize the Account Factory
Set up the smart account factory contract on your chosen L2.
Detailed Instructions
First, select a smart account implementation like Safe{Core} AA SDK, Biconomy, or ZeroDev. Import the necessary factory contract into your project. For a SimpleAccount from the ERC-4337 reference implementation, you would deploy the SimpleAccountFactory. On a testnet like Arbitrum Sepolia, find the official entry point address (e.g., 0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789).
- Sub-step 1: Install required packages:
npm install @account-abstraction/contracts - Sub-step 2: In your deployment script, import the factory ABI and bytecode.
- Sub-step 3: Instantiate and deploy the factory, passing the canonical entry point address as a constructor argument.
javascriptconst factory = await ethers.getContractFactory("SimpleAccountFactory"); const accountFactory = await factory.deploy(ENTRYPOINT_ADDRESS); await accountFactory.waitForDeployment(); console.log("Factory deployed at:", await accountFactory.getAddress());
Tip: Verify the factory contract on a block explorer post-deployment to enable community trust and interaction.
Create the Smart Account for a User
Generate a deterministic smart account address and deploy it on-demand.
Detailed Instructions
Smart accounts are deployed via the create2 opcode, allowing for counterfactual address calculation before any on-chain deployment. Call the createAccount function on your factory, providing the user's EOA address as the owner and a salt (often 0). This function returns the deterministic smart account address. The actual contract deployment only occurs when the first UserOperation is sent.
- Sub-step 1: Calculate the future address using
getAddresson the factory with the owner and salt. - Sub-step 2: Fund this pre-computed address with test ETH for future gas fees.
- Sub-step 3: To trigger deployment, prepare a UserOperation with a
initCodefield containing the factory call data.
solidity// Example interface call function createAccount(address owner, uint256 salt) public returns (address) { return address(new SimpleAccount{salt: bytes32(salt)}(ENTRYPOINT_ADDRESS, owner)); }
Tip: The salt enables creating multiple accounts per owner; for most users, a salt of 0 is sufficient.
Fund the Account with Native Gas Tokens
Transfer ETH or the L2 native token to the smart account for transaction fees.
Detailed Instructions
A smart account must hold the chain's native token (e.g., ETH on Arbitrum, MATIC on Polygon) to pay for its own gas via the EntryPoint. Send funds from an EOA or another wallet to the smart account's address. For testnets, use a faucet. For mainnet, execute a standard transfer. Verify the balance on a block explorer. Remember, the account needs funds before submitting its first UserOperation, as the bundler will pay upfront and be reimbursed from the account's balance.
- Sub-step 1: From your EOA, send a transaction to the smart account address (e.g., 0.01 ETH).
- Sub-step 2: Check the transaction confirmation on the block explorer.
- Sub-step 3: Query the smart account's balance using
provider.getBalance(smartAccountAddress).
javascriptconst tx = { to: smartAccountAddress, value: ethers.parseEther("0.01") }; const sentTx = await signer.sendTransaction(tx); await sentTx.wait();
Tip: For production, implement a paymaster to allow sponsorship, removing the need for the account to hold native tokens.
Set Up a Paymaster for Gas Abstraction
Configure a paymaster to sponsor transaction fees, enabling gasless UX.
Detailed Instructions
Integrate a paymaster to allow transactions where the smart account does not pay gas in the native token. This is critical for onboarding and DeFi interactions. Use a verified paymaster service like Biconomy or deploy your own VerifyingPaymaster from the ERC-4337 suite. The paymaster must be staked in the EntryPoint. In your UserOperation, set the paymasterAndData field. The paymaster will validate a signature from the account owner and cover the gas costs.
- Sub-step 1: Choose a paymaster endpoint (e.g., Biconomy's dashboard) and get an API key.
- Sub-step 2: In your client, when building a UserOperation, fetch paymaster data via RPC call
eth_paymasterAndDataForUserOp. - Sub-step 3: The paymaster will verify the user's operation and provide a signature for the bundler.
javascript// Example paymaster data structure in a UserOp const userOp = { ... paymasterAndData: "0x<PaymasterAddress><ValidUntil><ValidAfter><Signature>", ... };
Tip: For testing, use a paymaster that accepts all requests, but in production, implement strict validation logic to prevent abuse.
Execute the First UserOperation
Send a bundled transaction through the EntryPoint to activate the account.
Detailed Instructions
A UserOperation is a pseudo-transaction object representing a user's intent. Assemble it with the smart account as the sender, the target contract, calldata, and signatures. Use a bundler service (like Stackup, Alchemy) to send it to the EntryPoint. The EntryPoint will validate the account's signature, pay the gas via the account's balance or paymaster, and execute the call. This first operation will also deploy the counterfactual smart account contract.
- Sub-step 1: Construct the UserOperation object with
sender,nonce,callData, andsignature. - Sub-step 2: Estimate gas limits using
eth_estimateUserOperationGasvia RPC. - Sub-step 3: Send the operation to the bundler via
eth_sendUserOperation.
javascriptconst userOp = await smartAccount.createUserOp({ target: "0x...", // DeFi contract address data: "0x...", // call data for swap or deposit value: 0n }); const uoHash = await bundler.sendUserOperation(userOp, entryPointAddress);
Tip: Monitor the transaction hash returned by the bundler. The UserOperation will be included in a bundle transaction mined on-chain.
EOA vs. Smart Account for DeFi
Comparison of key operational and security features between Externally Owned Accounts and Smart Contract Accounts on Layer 2.
| Feature | Externally Owned Account (EOA) | Smart Contract Account (SCA) | Key Implication for DeFi |
|---|---|---|---|
Transaction Sponsorship | Not natively supported | Native via paymasters | Enables gasless onboarding and fee abstraction |
Batch Execution | Single operation per tx | Multi-call batching in one tx | Reduces L2 gas costs for complex DeFi interactions |
Recovery & Security | Single private key; loss is permanent | Social recovery, multi-sig, session keys | Mitigates key loss risk and enables granular permissions |
Signature Flexibility | ECDSA (secp256k1) only | Any verifiable scheme (e.g., BLS, MPC) | Future-proofs for new authentication standards |
Delegation & Automation | Requires separate relayer or bot | Native via signed user operations | Enables automated yield harvesting or limit orders |
Upgradability | Fixed address and logic | Logic can be updated via proxy patterns | Can adopt new security features post-deployment |
Initial Deployment Cost | ~0.001 ETH on L2 | ~0.002 - 0.005 ETH for contract creation | One-time cost for enhanced functionality |
Typical Gas Overhead | Base L2 transaction cost | ~10-20% higher than EOA for simple ops | Cost-benefit for batch operations is positive |
DeFi-Specific Use Cases
Account Abstraction enables advanced transaction logic and automation, unlocking novel DeFi interactions on Layer 2 networks.
Batch Transactions
Atomic composability allows multiple DeFi actions in one transaction.
- Execute a swap, deposit liquidity, and stake LP tokens without separate approvals.
- Example: Convert ETH to USDC, provide USDC/DAI liquidity on Uniswap V3, and stake the NFT position in a single click.
- This reduces gas costs, eliminates slippage between steps, and protects users from MEV sandwich attacks.
Sponsored Transactions
Gas abstraction lets dApps or protocols pay for user transactions.
- A lending protocol can sponsor the gas for a user's debt repayment or liquidation call.
- Example: Aave fronting the gas cost for a user to supply collateral, improving capital efficiency and UX.
- This removes the need for users to hold the native token for gas, lowering onboarding friction.
Session Keys
Delegated authority grants temporary permissions for specific contract interactions.
- A user can approve a trading bot to execute limit orders on Perpetual Protocol for 24 hours without full wallet access.
- Keys can be scoped to a maximum trade size and specific contract addresses.
- This enables secure, non-custodial automation while significantly reducing the risk of unlimited approvals.
Social Recovery & Multi-Sig Wallets
Custom authorization logic replaces immutable private keys with programmable security.
- Set up a 2-of-3 social recovery scheme using trusted devices or contacts to regain wallet access.
- Example: A DAO treasury managed by a 5-of-9 multi-signature smart contract wallet for governance proposals.
- This mitigates single points of failure and enables institutional-grade custody for DeFi protocols.
Conditional & Scheduled Transactions
Transaction automation executes based on predefined on-chain or off-chain conditions.
- Automatically repay a loan on Aave when collateral value drops to a specific health factor threshold.
- Schedule a recurring DCA purchase of ETH via CowSwap every Friday.
- This creates resilient, hands-off DeFi strategies that react faster than manual intervention.
Unified Asset Approval
Global permit management streamlines token approvals across multiple protocols.
- Grant a single, revocable permission for a DEX aggregator like 1inch to access USDC, usable across all integrated pools.
- This replaces the need for separate, infinite approvals for each new router or pool contract.
- It enhances security by centralizing control and simplifying the revocation process.
Implement Session Keys for a DEX
Process for deploying and integrating session keys to enable gasless, batched trading on a Layer 2 DEX using Account Abstraction.
Design the Session Key Policy
Define the scope and permissions for the session key.
Detailed Instructions
Define the authorization rules for the session key smart contract. This contract will validate if a user operation signed by the session key is permitted.
- Sub-step 1: Specify allowed actions. Determine which DEX contract functions the key can call, such as
swapExactTokensForTokenson a Uniswap V3 router (e.g.,0xE592427A0AEce92De3Edee1F18E0157C05861564). - Sub-step 2: Set resource limits. Implement maximum values for total transaction value (e.g., 10 ETH), gas budget per session, and a session expiration timestamp.
- Sub-step 3: Define validation logic. The policy contract's
validateSessionUserOpfunction must check these rules and returnVALIDATION_SUCCESS(0) for approved operations.
solidity// Example struct for session rules struct SessionRules { address allowedTarget; bytes4 allowedSelector; uint256 maxValue; uint48 validUntil; }
Tip: Use a whitelist of selectors rather than allowing any call to the target address for enhanced security.
Deploy the Session Key Manager Module
Integrate the session key logic with the user's smart account.
Detailed Instructions
Deploy a Session Key Manager as an execution module for a smart account (e.g., using Safe{Core} Protocol or a custom ERC-4337 account). This module manages active sessions.
- Sub-step 1: Write the manager contract. It must store a mapping of session keys to their associated policy rules and be able to add/revoke sessions via calls from the account owner.
- Sub-step 2: Deploy to your Layer 2. Compile and deploy the manager using a tool like Foundry:
forge create SessionKeyManager --rpc-url <L2_RPC> --private-key <DEPLOYER_KEY>. - Sub-step 3: Enable the module on the user's account. For an ERC-4337 account, call
installModule(address(manager)). Verify the module is listed in the account'sisModuleInstalledfunction.
solidity// Simplified function to add a session function addSessionKey( address sessionKey, SessionRules calldata rules ) external onlyOwner { activeSessions[sessionKey] = rules; }
Tip: Emit events for key additions and revocations to allow off-chain services like bundlers to track valid sessions.
Generate and Sign the Session Key
Create the off-chain session key pair and user approval.
Detailed Instructions
Generate a dedicated cryptographic key pair that will sign transactions for the duration of the session, separate from the account owner's master key.
- Sub-step 1: Create the key pair. Use
ethers.Wallet.createRandom()in a backend service or client to generate a new private key and address. Never expose this private key to the frontend. - Sub-step 2: Sign the session authorization. The account owner must sign a message (EIP-712 typed data) approving the specific session rules (target, limits, expiry). This signature authorizes the session key manager to activate the session.
- Sub-step 3: Transmit the session key securely. The session private key is encrypted and sent to the intended user client (e.g., a trading bot) via a secure channel. The authorization signature is submitted on-chain to enable the session.
javascript// Example EIP-712 type hash for session authorization const types = { SessionAuth: [ { name: "sessionKey", type: "address" }, { name: "validUntil", type: "uint48" }, { name: "allowedTarget", type: "address" } ] };
Tip: Use short-lived sessions (e.g., 24 hours) and low value limits to minimize risk if the session key is compromised.
Construct and Submit a UserOperation
Build a gasless transaction signed by the session key for the bundler.
Detailed Instructions
The session key holder constructs an ERC-4337 UserOperation to execute a DEX trade without holding gas funds.
- Sub-step 1: Build the call data. Encode the call to the DEX contract, e.g., a swap on a Uniswap V3 Router. Use the session key's address as the
senderin the UserOperation. - Sub-step 2: Sign the UserOperation. The session key signs the UserOperation hash. The bundler will forward this to the EntryPoint, which validates the signature against the session key and the rules in the manager module.
- Sub-step 3: Set paymaster details. To make it gasless, specify a paymaster in the UserOperation that will sponsor the gas fees. Ensure the
verificationGasLimitis sufficient for the session rule validation.
javascript// Example UserOperation structure for a session key trade const userOp = { sender: smartAccountAddress, nonce: accountNonce, initCode: "0x", callData: swapCalldata, callGasLimit: 300000, verificationGasLimit: 150000, // Includes module validation preVerificationGas: 50000, maxFeePerGas: parseUnits("30", "gwei"), maxPriorityFeePerGas: parseUnits("1", "gwei"), paymasterAndData: paymasterAddress, signature: sessionKeySignature // Signed by session key, not master key };
Tip: Use a bundler service like Stackup or Pimlico that supports custom module validation and paymaster integration on your target Layer 2.
Account Abstraction FAQ
Further Resources
Ready to Start Building?
Let's bring your Web3 vision to life.
From concept to deployment, ChainScore helps you architect, build, and scale secure blockchain solutions.