Communicating between chains in Solidity

Communicating between OP Stack and Ethereum in Solidity

This tutorial explains how to write Solidity contracts on OP Stack and Ethereum that can talk to each other. Here you'll use a contract on OP Stack that can set a "greeting" variable on a contract on Ethereum, and vice-versa. This is a simple example, but the same technique can be used to send any kind of message between the two chains.

You won't actually be deploying any smart contracts as part of this tutorial. Instead, you'll reuse existing contracts that have already been deployed to OP Stack and Ethereum. Later in the tutorial you'll learn exactly how these contracts work so you can follow the same pattern to deploy your own contracts.

Just looking to bridge tokens between OP Stack and Ethereum? Check out the tutorial on Bridging ERC-20 Tokens to OP Stack With the viem.

Message passing basics

OP Stack uses a smart contract called the CrossDomainMessenger to pass messages between OP Stack and Ethereum. Both chains have a version of this contract (the L1CrossDomainMessenger and the L2CrossDomainMessenger). Messages sent from Ethereum to OP Stack are automatically relayed behind the scenes. Messages sent from OP Stack to Ethereum must be explicitly relayed with a second transaction on Ethereum. Read more about message passing in the guide to Sending Data Between L1 and L2.

Dependencies

Get ETH on Sepolia and OP Sepolia

This tutorial explains how to send messages from Sepolia to OP Sepolia. You will need to get some ETH on both of these testnets.

You can use this faucet (opens in a new tab) to get ETH on Sepolia. You can use the Superchain Faucet (opens in a new tab) to get ETH on OP Sepolia.

Review the contracts

You're about to use two contracts that have already been deployed to Sepolia and OP Sepolia, the Greeter contracts. You can review the source code for the L1 Greeter contract here on Etherscan (opens in a new tab). You can review the source code for the L2 Greeter contract here on Etherscan (opens in a new tab). Both contracts have exactly the same source code.

Feel free to review the source code for these two contracts now if you'd like. This tutorial will explain how these contracts work in detail later on in the How It Works section below.

Interact with the L1 Greeter

You're first going to use the L1 Greeter contract to set the greeting on the L2 Greeter contract. You'll send a transaction directly to the L1 Greeter contract which will ask the L1CrossDomainMessenger to send a message to the L2 Greeter contract. After just a few minutes, you'll see the corresponding greeting set on the L2 Greeter contract.

Connect to Etherscan

Sending a message to the L2 Greeter contract via the L1 Greeter contract requires that you call the sendGreeting function. For simplicity, you'll interact with the contract directly on Etherscan. Open up the L1 Greeter contract on Sepolia Etherscan (opens in a new tab) and click the "Connect to Web3" button.

Send your greeting

Put a greeting into the field next to the "sendGreeting" function and click the "Write" button. You can use any greeting you'd like.

Wait a few minutes

It will take a few minutes for your message to reach L2. Feel free to take a quick break while you wait.

You can use Viem to programmatically check the status of any message between L1 and L2. Later on in this tutorial you'll learn how to use Viem and the waitToProve function to wait for various message statuses. This same function can be used to wait for a message to be relayed from L1 to L2.

Check the L2 Greeter

After a few minutes, you should see the greeting on the L2 Greeter contract change to the greeting you set. Open up the L2 Greeter contract on OP Sepolia Etherscan (opens in a new tab) and click the "Read Contract" button. Paste your address into the field next to the "greeting" function and click the "Query" button. You should see the message you sent from L1.

💡

Haven't seen your message yet? You might need to wait a little longer. L2 transactions triggered on L1 are typically processed within one minute but can occasionally be slightly delayed.

Interact with the L2 Greeter

Now you're going to use the L2 Greeter contract to set the greeting on the L1 Greeter contract. You'll send a transaction directly to the L2 Greeter contract which will ask the L2CrossDomainMessenger to send a message to the L1 Greeter contract. Unlike the previous step, you'll need to relay the message from L2 to L1 yourself! You'll do this by sending two transactions on Sepolia, one proving transaction and one relaying transaction.

Connect to Etherscan

Just like before, sending a message to the L1 Greeter contract via the L2 Greeter contract requires that you call the sendGreeting function. Open up the L2 Greeter contract on OP Sepolia Etherscan (opens in a new tab) and click the "Connect to Web3" button.

Send your greeting

Put a greeting into the field next to the "sendGreeting" function and click the "Write" button. You can use any greeting you'd like.

💡

Copy the transaction hash from the transaction you just sent. You'll need this for the next few steps. Feel free to keep this tab open so you can easily copy the transaction hash later.

Create a demo project folder

You're going to use the viem to prove and relay your message to L1.

mkdir cross-dom
cd cross-dom

Initialize the project

Set up the project as a basic Node.js project with pnpm or your favorite package manager.

pnpm init

Install viem

Install Viem with pnpm or your favorite package manager.

pnpm add viem

Add your 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 is the private key for the address you used to send the transaction to the L2 Greeter contract.

export TUTORIAL_PRIVATE_KEY=0x...

Add your transaction hash to your environment

You'll also need the hash of the transaction you sent to the L2 Greeter contract. Set this as an environment variable with the export command.

export TUTORIAL_TRANSACTION_HASH=0x...

Start a Node REPL

Now you'll use the Node.js REPL to run a few commands. Start the Node.js REPL with the node command.

node

Import Viem

const { createPublicClient, http } = require('viem');
const { optimismSepolia } = require('viem/chains');
const {  publicActionsL1, publicActionsL2} = require('viem/op-stack');

Load your transaction hash

const transactionHash = process.env.TUTORIAL_TRANSACTION_HASH

Create the RPC providers and wallets

 
const l1Provider = createPublicClient({ chain: sepolia, transport: http("https://rpc.ankr.com/eth_sepolia") }).extend(publicActionsL1())

Wait until the message is ready to prove

Next, you will send messages from L2 to L1 is to prove that the message was sent on L2. You first need to wait until the message is ready to prove.

console.log('Waiting for message to be provable...')
await l1Provider.getWithdrawalStatus({ 
  receipt, 
  targetChain: l2Provider.chain, 
}) 

This step can take a few minutes. Feel free to take a quick break while you wait.

Prove the message on L1

Once the message is ready to be proven, you'll send an L1 transaction to prove that the message was sent on L2.

console.log('Proving message...')
const receipt = await l2Provider.getTransactionReceipt(transactionHash)
const output = await l1Provider.waitToProve({ 
  receipt, 
  targetChain: l2Provider.chain, 
}) 

Wait until the message is ready for relay

The final step to sending messages from L2 to L1 is to relay the messages on L1. This can only happen after the fault proof period has elapsed. On OP Stack, this takes 7 days.

💡

We're currently testing fault proofs on OP Sepolia, so withdrawal times reflect Mainnet times.

console.log('Waiting for message to be relayable...')
await l1Provider.getWithdrawalStatus({ 
  receipt, 
  targetChain: l2Provider.chain, 
}) 

Relay the message on L1

Once the withdrawal is ready to be relayed you can finally complete the message sending process.

console.log('Relaying message...')
const [message] = getWithdrawals(receipt)
await l1Provider.waitToFinalize({ withdrawalHash: message.withdrawalHash, targetChain: l2Provider.chain }) 

Wait until the message is relayed

Now you simply wait until the message is relayed.

console.log('Waiting for message to be relayed...')
await l1Provider.getWithdrawalStatus({ receipt, targetChain: l2Provider.chain }) 

Check the L1 Greeter

Now that you've relayed the message, you should see the greeting on the L1 Greeter contract change to the greeting you set. Open up the L1 Greeter contract on Sepolia Etherscan (opens in a new tab) and click the "Read Contract" button. Paste your address into the field next to the "greeting" function and click the "Query" button. You should see the message you sent from L2.

How it works

Congratulations! You've successfully sent a message from L1 to L2 and from L2 to L1. This section will explain how the Greeter contracts work so you can follow the same pattern to deploy your own contracts. Luckily, both Greeter contracts are exactly the same so it's easy to see how everything comes together.

The Messenger variable

The Greeter contract has a MESSENGER variable that keeps track of the CrossDomainMessenger contract on the current chain. Check out the Contract Addresses page to see the addresses of the CrossDomainMessenger contracts on whichever network you'll be using.

    ICrossDomainMessenger public immutable MESSENGER;

The other Greeter variable

The Greeter contract also has an OTHER_GREETER variable that keeps track of the Greeter contract on the other chain. On L1, this variable is set to the address of the L2 Greeter contract, and vice-versa.

    Greeter public immutable OTHER_GREETER;

The Greetings mapping

The Greeter contract keeps track of the different greetings that users have sent inside a greetings mapping. By using a mapping, this contract can keep track of greetings from different users at the same time.

    mapping (address => string) public greetings;

The Constructor

The Greeter has a simple constructor that sets the MESSENGER and OTHER_GREETER variables.

    constructor(
        ICrossDomainMessenger _messenger,
        Greeter _otherGreeter
    ) {
        MESSENGER = _messenger;
        OTHER_GREETER = _otherGreeter;
    }

The sendGreeting function

The sendGreeting function is the most important function in the Greeter contract. This is what you called earlier to send messages in both directions. All this function is doing is using the sendMessage function found within the CrossChainMessenger contract to send a message to the Greeter contract on the other chain.

Here, the first parameter is the address of the recipient of the message (the Greeter contract on the other chain). The second parameter is the ABI-encoded function call to the setMessage function. The final parameter is the gas limit that gets used when the message is relayed on the other side.

    function sendGreeting(string memory _greeting) public {
        MESSENGER.sendMessage(
            address(OTHER_GREETER),
            abi.encodeCall(
                this.setGreeting,
                (
                    msg.sender,
                    _greeting
                )
            ),
            200000
        );
    }

The setGreeting function

The setMessage function is the function that actually sets the greeting. This function is called by the CrossDomainMessenger contract on the other chain. It checks explicitly that the function can only be called by the CrossDomainMessenger contract. It also checks that the CrossChainMessenger is saying that the message came from the Greeter contract on the other chain. Finally, it sets the greeting in the greetings mapping.

    function setGreeting(address _sender, string memory _greeting) public {
        require(
            msg.sender == address(MESSENGER),
            "Greeter: Direct sender must be the CrossDomainMessenger"
        );
 
        require(
            MESSENGER.xDomainMessageSender() == address(OTHER_GREETER),
            "Greeter: Remote sender must be the other Greeter contract"
        );
 
        greetings[_sender] = _greeting;
    }
💡

The two require statements in this function are important! Without them, anyone could call this function and set the greeting to whatever they want. You can follow a similar pattern in your own smart contracts.

Conclusion

You just learned how you can write Solidity contracts on Sepolia and OP Sepolia that can talk to each other. You can follow the same pattern to write contracts that can talk to each other on Ethereum and OP Stack.

This sort of cross-chain communication is useful for a variety of reasons. For example, the Standard Bridge contracts use this same system to bridge ETH and ERC-20 tokens between Ethereum and OP Stack.

One cool way to take advantage of cross-chain communication is to do most of your heavy lifting on OP Stack and then send a message to Ethereum only when you have important results to share. This way you can take advantage of the low gas costs on OP Stack while still being able to use Ethereum when you need it.