Supported networks
Viem supports any of the Superchain networks. The OP Stack networks are included in Viem by default. If you want to use a network that isn’t included by default, you can add it to Viem’s chain configurations.Dependencies
Create a demo project
You’re going to use Viem for this tutorial. Since Viem is a Node.js library, you’ll need to create a Node.js project to use it.1
Make a project folder
2
Initialize the project
3
Install the Viem library
Want to create a new wallet for this tutorial?
If you have
cast
installed you can run cast wallet new
in your terminal to create a new wallet and get the private key.Get ETH on Sepolia
This tutorial explains how to bridge ETH from Sepolia to OP Sepolia. You will need to get some ETH on Sepolia to follow along.You can use this faucet to get ETH on Sepolia.
Add a private key to your environment
You need a private key in order to sign transactions. Set your private key as an environment variable with the export command. Make sure this private key corresponds to an address that has ETH on Sepolia.Start the Node REPL
You’re going to use the Node REPL to interact with Viem. To start the Node REPL run the following command in your terminal:Import dependencies
You need to import some dependencies into your Node REPL session.1
Import Viem and other packages
2
Load private key and set account
3
Create L1 public client for reading from the Sepolia network
4
Create L1 wallet client for sending transactions on Sepolia
5
Create L2 public client for interacting with OP Sepolia
6
Create L2 wallet client on OP Sepolia
Get ETH on Sepolia
You’re going to need some ETH on L1 that you can bridge to L2. You can get some Sepolia ETH from this faucet.Deposit ETH
Now that you have some ETH on L1 you can deposit that ETH into theOptimismPortalProxy
contract. You’ll then receive the same number of ETH on L2 in return.
Using a smart contract wallet?
As a safety measure,
depositETH
will fail if you try to deposit ETH from a smart contract wallet without specifying a recipient
.
Add the recipient
option to the depositETH
call to fix this.Withdraw ETH
You just bridged some ETH from L1 to L2. Nice! Now you’re going to repeat the process in reverse to bridge some ETH from L2 to L1.Important Considerations
- Challenge period: The 7-day withdrawal challenge Period is crucial for security.
- Gas costs: Withdrawals involve transactions on both L2 and L1, each incurring gas fees.
- Private Key handling: Use secure key management practices in real applications.
- RPC endpoint security: Keep your API key (or any RPC endpoint) secure.
Next Steps
- Develop a user interface for easier interaction with these bridging functions.
- Implement robust error handling and retry mechanisms for production use.
viem/op-stack
.
You should now be able to write applications that use viem/op-stack
to transfer ETH between L1 and L2.
Although this tutorial used Sepolia and OP Sepolia, the same process works for Ethereum and OP Mainnet.