Overview
EIP-7702 introduces a new transaction type, 0x04, in Ethereum's Pectra upgrade that enables externally owned accounts (EOAs) to execute temporary smart contract functionality. This advancement in Account Abstraction bridges the gap between EOAs and smart contracts, enabling key features like batch transactions, sponsored gas payments, and controlled access delegation.
EIP-7702 is now active on Ethereum mainnet and testnets like Sepolia as part of the Pectra upgrade. Developers can test EIP-7702 in local Foundry environmentsβeither on a fresh local network or by forking mainnet. This guide will walk you through setting up a fresh local network for testing purposes.
This comprehensive guide will walk you through the technical details of EIP-7702, its use cases, and how to test it using Foundry and Foundry's cheatcodes. By the end, you'll have a clear understanding of how to leverage EIP-7702 in your projects, deploy implementation contracts, and test EIP-7702 features effectively.
What You Will Learn
- Implement
0x04transactions with an EOA - Develop smart accounts using EIP-7702
- Test and deploy
0x04transactions on a local network - Send EIP-7702 transactions with Viem
- Understand batch transactions and gas sponsorship mechanisms
Prerequisites
- Foundry installed on your system
- Basic knowledge of Foundry, Solidity, and smart contract development
- A text editor or IDE (e.g., VS Code)
- Understanding of Ethereum account types and transaction mechanics
Understanding EIP-7702 Transactions
Traditional Ethereum transactions either transfer funds or interact with smart contracts, but the new 0x04 transaction type allows EOAs to execute code directly. This breakthrough unlocks new possibilities for externally owned accounts, enabling them to function more like smart contracts while maintaining their fundamental characteristics.
With this new standard, EOAs can execute smart contract logic directly from their own address, enabling several advanced functionalities:
- Batch Transactions: Combine multiple actions into a single atomic transaction (token approvals, swaps, transfers)
- Limited Access Delegation: Grant temporary, scoped permissions without key exposure
- Gas Sponsorship: Allow third parties (e.g., paymasters) to cover gas fees for your transactions
- Wallet Recovery: Implement recovery mechanisms for private key loss scenarios
Ethereum Account Types Explained
- Externally Owned Accounts (EOAs): Controlled only by a private key; they hold funds but cannot run code (e.g., user wallets such as MetaMask)
- Smart Contract Accounts: Hold code and can execute complex operations (e.g., Uniswap Factory, Uniswap Router)
The user (EOA) signs an authorization message that includes the chain ID, nonce, delegation address, and signature components (y_parity, r, s). This generates a signed authorization, ensuring that only the approved implementation contract can execute transactions while protecting against replay attacks.
For each authorized delegation address, the user stores a delegation designator, a pointer to the implementation contract that the EOA will delegate to. When the user (or a sponsor) executes an EIP-7702 transaction, it loads and runs the code from the address indicated by that pointer.
Transaction Construction Mechanics
In standard Ethereum transactions, calling a function on a smart contract requires setting the to field to that contract's address and including the appropriate data to call its function. With EIP-7702, you set the to field to the EOA's address and include the data to call the implementation contract's function with the signed authorization message.
EIP-7702 Transaction Anatomy
The process involves generating an authorization signature for a specific contract, then constructing a transaction where the to field is set to the smart account's own address. The data field is created by encoding a call to the execute function with an array of call objects. The transaction includes the signed authorization in an authorizationList, enabling the smart account to delegate execution to the implementation contract.
If another wallet (a sponsor) wants to execute this transaction (a sponsored transaction), it can use the same authorization signature to delegate execution to the implementation contract.
π Explore advanced transaction building techniques
Sending EIP-7702 Transactions with Viem
import { createWalletClient, http, parseEther } from 'viem'
import { anvil } from 'viem/chains'
import { privateKeyToAccount } from 'viem/accounts'
import { eip7702Actions } from 'viem/experimental'
import { abi, contractAddress } from './contract'
const account = privateKeyToAccount('0x...')
const walletClient = createWalletClient({
account,
chain: anvil,
transport: http(),
}).extend(eip7702Actions())
const authorization = await walletClient.signAuthorization({
contractAddress,
})
const hash = await walletClient.sendTransaction({
authorizationList: [authorization],
data: encodeFunctionData({
abi,
functionName: 'execute',
args: [
[
{
data: '0x',
to: '0xcb98643b8786950F0461f3B0edf99D88F274574D',
value: parseEther('0.001'),
},
{
data: '0x',
to: '0xd2135CfB216b74109775236E36d4b433F1DF507B',
value: parseEther('0.002'),
},
],
]
}),
to: walletClient.account.address,
})EIP-7702 Transaction Flow
The transaction flow begins with the EOA signing an authorization message, which is then included in the transaction's authorization list. The network processes this transaction by temporarily elevating the EOA's capabilities through the specified implementation contract, executing the desired operations, and then reverting the EOA back to its normal state after transaction completion.
Testing EIP-7702 Features with Foundry
This section provides practical guidance on implementing EIP-7702 features using Foundry, a powerful smart contract development toolkit. Foundry provides a set of cheatcodesβspecial commands that modify the behavior of the Ethereum Virtual Machine (EVM) to simplify testing. We'll utilize the signDelegation, attachDelegation, and signAndAttachDelegation cheatcodes to test EIP-7702 features comprehensively.
Project Overview
In this project, we deploy an implementation contract called BatchCallAndSponsor that enables:
- Batch Transactions: Execute multiple calls in a single transaction
- Sponsored Transactions: Allow sponsors to pay for gas fees
- Replay Protection: Use nonces to prevent transaction replay attacks
The project includes the following files:
BatchCallAndSponsor.solβ Contains core logic for batched and sponsored transactionsBatchCallAndSponsor.t.solβ Includes unit tests for both direct and sponsored executionBatchCallAndSponsor.s.solβ Script for deploying contracts and executing transactionsMockERC20.solβ Mock ERC-20 token contract for testing token transfers
Environment Setup
Step 1: Install Foundry
Install Foundry using the following command:
curl -L https://foundry.paradigm.xyz | bashRestart your terminal and run:
foundryupStep 2: Initialize Foundry Project
Initialize a new Foundry project:
forge init eip-7702-project
cd eip-7702-projectAlternatively, clone the sample project:
git clone https://github.com/quiknode-labs/qn-guide-examples.git
cd qn-guide-examples/ethereum/eip-7702Step 3: Install Dependencies
Install required libraries:
forge install foundry-rs/forge-std
forge install OpenZeppelin/openzeppelin-contractsStep 4: Configure Remappings
Create remappings to simplify import paths:
forge remappings > remappings.txtStep 5: Update Foundry Configuration
Modify foundry.toml to ensure compatibility with EIP-7702 by setting the Prague hardfork:
evm_version = "prague"Step 6: Implement Smart Contract
Create BatchCallAndSponsor.sol in the src folder and add the contract logic from the sample project. This implementation contract supports batch transactions and sponsored gas features.
Step 7: Write Test Cases
Create BatchCallAndSponsor.t.sol in the test folder and add test cases from the sample project. These tests cover direct execution, sponsored execution, replay protection, and error handling scenarios.
Step 8: Create Deployment Script
Create BatchCallAndSponsor.s.sol in the script folder and add the deployment script from the sample project. This script handles contract deployment, token minting, and transaction execution.
The complete project structure should look like this:
βββ README.md
βββ foundry.toml
βββ lib
β βββ forge-std
β βββ openzeppelin-contracts
βββ remappings.txt
βββ script
β βββ BatchCallAndSponsor.s.sol
βββ src
β βββ BatchCallAndSponsor.sol
βββ test
βββ BatchCallAndSponsor.t.solImplementation Contract Details
The BatchCallAndSponsor contract is a straightforward implementation that supports batch transactions and sponsored gas functionality. The contract includes several key components:
Batch Execution Logic
The execute function takes an array of Call structs, each representing a different call with target address, value, and calldata specifications. The function processes these calls sequentially, ensuring atomic execution where either all calls succeed or none execute.
Signature Verification
The contract verifies signatures using OpenZeppelin's ECDSA library and MessageHashUtils, ensuring transactions were signed by the appropriate EOA and preventing unauthorized execution.
Execution Modes
The contract supports both direct execution (where the caller executes calls themselves) and sponsored execution (where a sponsor executes calls on behalf of the caller after verifying their signature).
Replay Protection
A nonce system prevents replay attacks by incrementing after each successful execution, ensuring that signed authorizations cannot be reused maliciously.
Test Cases Overview
The test suite comprehensively validates the contract's functionality through multiple scenarios:
Direct Execution Test
Validates that users can execute batch transactions directly, combining multiple operations like ETH transfers and token transfers into a single atomic transaction.
Sponsored Execution Test
Verifies that third parties can execute transactions on behalf of users, with proper signature verification and authorization mechanisms.
Signature Validation Tests
Ensure the contract correctly rejects invalid signatures and prevents unauthorized access to account functionality.
Replay Protection Test
Confirms that the nonce system effectively prevents transaction replay attacks by rejecting previously used signatures.
Deployment Script Functionality
The deployment script handles contract deployment, token minting, and execution of both direct and sponsored transactions. It provides a practical demonstration of EIP-7702 functionality in action, showing how these features work together in a real-world scenario.
Running and Testing the EIP-7702 Project
Step 1: Start Local Network
Run a local network with the Prague hardfork:
anvil --hardfork pragueStep 2: Install Dependencies
Install project dependencies:
forge installStep 3: Build Contracts
Compile the smart contracts:
forge buildStep 4: Run Tests
Execute the test suite:
forge test -vvvStep 5: Execute Deployment Script
Run the deployment script to see EIP-7702 in action:
forge script ./script/BatchCallAndSponsor.s.sol --tc BatchCallAndSponsorScript --broadcast --rpc-url 127.0.0.1:8545When prompted about transactions to addresses without code (EOAs), type y to continue, as this is expected behavior before EIP-7702 application.
Frequently Asked Questions
What is the main benefit of EIP-7702?
EIP-7702 enables externally owned accounts to temporarily function as smart contracts, allowing batch transactions, gas sponsorship, and delegated execution without requiring users to migrate to smart contract wallets. This significantly improves user experience while maintaining backward compatibility.
How does EIP-7702 improve transaction efficiency?
By enabling batch transactions, EIP-7702 allows multiple operations to be executed atomically in a single transaction, reducing gas costs and blockchain congestion while improving the user experience for complex operations.
Is EIP-7702 compatible with existing Ethereum wallets?
Yes, EIP-7702 maintains full backward compatibility with existing wallets and smart contracts. The new transaction type is optional, and traditional transactions continue to work exactly as before.
How does EIP-7702 handle security concerns?
The implementation includes signature verification, nonce-based replay protection, and strict authorization checks to ensure only approved implementation contracts can execute transactions on behalf of EOAs.
Can EIP-7702 transactions be sponsored by third parties?
Yes, one of the key features enables gas sponsorship, where third parties can pay transaction fees on behalf of users, opening up new business models and improving user onboarding experiences.
What are the limitations of EIP-7702?
The functionality is temporary and transaction-specific. EOAs only gain smart contract capabilities during the execution of an EIP-7702 transaction and revert to normal functionality afterward, which maintains security while enabling advanced features.
Conclusion
EIP-7702 represents a significant advancement in Ethereum's account abstraction capabilities, opening the door to innovative use cases like batch transactions, delegated execution, and sponsored transactions. This novel feature has the potential to transform how users interact with smart contracts and decentralized applications.
This guide has covered the fundamentals of EIP-7702, its practical applications, and implementation techniques using Foundry. Through hands-on testing with implementation contracts on a local network, you've gained practical experience with this emerging standard. The knowledge gained provides a solid foundation for exploring more advanced EIP-7702 applications and contributing to the evolving ecosystem of account abstraction solutions on Ethereum.