Bridging ETH from Ethereum L1 to Optimism L2 Using the Optimism JavaScript SDK

·

TLDR:


Introduction to Optimism

Optimism enhances Ethereum’s scalability through its Layer 2 (L2) network, offering faster transactions and lower fees while maintaining Ethereum’s security. By leveraging optimistic rollups, Optimism processes transactions off-chain and submits compressed data to Ethereum for validation.

👉 Explore Optimism’s rollup technology

Key Features:


Prerequisites

  1. Accounts:

  2. Tools:

    • Node.js (v16.17.0 or later).
  3. Dependencies:

    • @eth-optimism/sdk
    • dotenv
    • ethers

Step-by-Step Guide

1. Set Up Your Environment

Configure Nodes:

Initialize Project:

npm init -y
npm install @eth-optimism/sdk dotenv ethers

Store Secrets:

Create a .env file:

L1_RPC_URL="YOUR_ETHEREUM_SEPOLIA_ENDPOINT"  
L2_RPC_URL="YOUR_OPTIMISM_SEPOLIA_ENDPOINT"  
PRIVATE_KEY="YOUR_WALLET_PRIVATE_KEY"  

2. Implement the Bridge

Code Structure (index.js):

const { CrossChainMessenger, MessageStatus } = require("@eth-optimism/sdk");
const { ethers } = require("ethers");
require("dotenv").config();

// Initialize providers and wallet
const l1Provider = new ethers.providers.JsonRpcProvider(process.env.L1_RPC_URL);
const l2Provider = new ethers.providers.JsonRpcProvider(process.env.L2_RPC_URL);
const wallet = new ethers.Wallet(process.env.PRIVATE_KEY).connect(l1Provider);

async function bridgeEth() {
  const crossChainMessenger = new CrossChainMessenger({
    l1ChainId: await l1Provider.getChainId(),
    l2ChainId: await l2Provider.getChainId(),
    l1Signer: wallet,
    l2Signer: wallet.connect(l2Provider),
  });

  // Deposit 0.1 ETH (in Wei)
  const wei = ethers.utils.parseEther("0.1");
  console.log(`Bridging ${ethers.utils.formatEther(wei)} ETH to L2...`);

  const tx = await crossChainMessenger.depositETH(wei);
  await tx.wait();
  console.log(`Transaction hash: ${tx.hash}`);

  // Wait for relay
  await crossChainMessenger.waitForMessageStatus(tx.hash, MessageStatus.RELAYED);
  console.log("Bridge successful! Balances updated.");
}

bridgeEth();

3. Execute the Script

node index.js

Expected Output:

Bridging 0.1 ETH to L2...  
Transaction hash: 0x...  
Bridge successful! Balances updated.  

👉 Track transactions on Etherscan


FAQ

Q1: How long does bridging take?

A: Typically 5–15 minutes, depending on network congestion.

Q2: Can I bridge back to L1?

A: Yes! Use crossChainMessenger.withdrawETH() for L2 → L1 transfers.

Q3: What’s the minimum ETH required?

A: Must cover gas fees (≈0.001 ETH for testnets).


Conclusion

This tutorial demonstrated bridging ETH using Optimism’s SDK. For advanced use cases, explore:

Optimism’s ecosystem continues to evolve, offering developers scalable solutions with Ethereum-level security.