Exploring the Openzeppelin CrossChain Functionality
What is the new CrossChain support and how can you use it.
For the first time Openzeppelin Contracts have added CrossChain Support. In particular the following chains are currently supported:
- Polygon: One of the most popular sidechains right now. We've discussed it previously here.
- Optimism: A Layer 2 chain based on optimistic rollups. We discussed the tech previously here.
- Arbitrum: A different Layer 2 chain also based on optimistic rollups.
- AMB: The Arbitrary Message Bridge is a general tool one can use to relay any data between two chains.

What are the Difficulties with CrossChain?
So what exactly are the things to consider in CrossChain communication?
- Why even send data to begin with? Well you might have governance-owned contract on Ethereum mainnet for example controlled by a native ERC-20. And you want this contract to be able to change fundamental things, for example upgrade another contract on the child chain. Then you need a way to allow the contract from the mainnet to send data to the child in a secure way.
- The sender problem: One difficulty of sending cross-chain messages is determining the sender address, because from the contract's perspective msg.sender will actually be a child system address. What exactly msg.sender will be of course depends on the child chain, but it won't be the actual sender from the root chain.
- The access control problem: Another issue with CrossChain is the potential for an address existing twice, so be aware that a contract with identical address can exist on child and root chain.
- Signature Double-Use: And if you allow for any signatures in your contract, they might be double used. This is why you should always double check the chain id or better use EIP-712 which handles all the complexities with secure signatures.
How the OZ CrossChain Support works
Openzeppelin has added contracts to support the usage in Polygon, Optimism, Arbitrum and AMB. There is a master interface CrossChainEnabled.sol which all four implementations make use of. And there is a new AccessControlCrossChain.sol to allow for secure access control via roles but with CrossChain support. An overview of it all can be seen here.
Each chain implementation contains a different mechanism to retrieve the original CrossChain sender which roughly looks like this:
function processMessageFromRoot(
uint256, /* stateId */
address rootMessageSender,
bytes calldata data
)
AMB_Bridge(bridge).messageSender()
LibArbitrumL2.crossChainSender(LibArbitrumL2.ARBSYS)
Optimism_Bridge(messenger).xDomainMessageSender()
For the full details, check out the contract code here.
How to use it - Polygon Example
Let's take a deeper dive in how you would actually use this with the example of Polygon.
We'll create contracts on the root and child chain with secure access control.
1. Creating the Root Contract
So first let's create a contract that we will deploy on the root blockchain. In the normal case this would be the Ethereum mainnet. We can inherit from the FxBaseRootTunnel.sol contract and pass check point and root addresses depending on the network:
- GOERLI_CHECKPOINT_MANAGER = 0x2890bA17EfE978480615e330ecB65333b880928e
- GOERLI_FX_ROOT = 0x3d1d3E34f7fB6D26245E6640E1c50710eFFf15bA
- MAINNET_CHECKPOINT_MANAGER = 0x86E4Dc95c7FBdBf52e33D563BbDB00823894C287
- MAINNET_FX_ROOT = 0xfe5e5D361b2ad62c541bAb87C45a0B9B018389a2
It will give you two internal functions to work with
_processMessageFromChild
: Override this to respond to messages sent from the child contract._sendMessageToChild
: Call this to send a message to the child.
import {FxBaseRootTunnel} from
"fx-portal/contracts/tunnel/FxBaseRootTunnel.sol";
// see left for full addresses
address constant GOERLI_CP_MANAGER = 0x2890bA17EfE978480615e...;
address constant GOERLI_FX_ROOT = 0x3d1d3E34f7fB6D26245E6640...;
contract PolygonRoot is FxBaseRootTunnel {
bytes public latestData;
constructor()
FxBaseRootTunnel(GOERLI_CP_MANAGER, GOERLI_FX_ROOT) {
}
function _processMessageFromChild(
bytes memory data
) internal override {
latestData = data;
}
function sendMessageToChild(bytes memory message) public {
_sendMessageToChild(message);
}
}
import {CrossChainEnabledPolygonChild} from
"oz/contracts/crosschain/polygon/CrossChainEnabledPolygonChild.sol";
import {AccessControlCrossChain} from
"oz/contracts/access/AccessControlCrossChain.sol";
address constant MUMBAI_FX_CHILD = 0xCf73231F...; // see right
contract PolygonChild is
CrossChainEnabledPolygonChild,
AccessControlCrossChain
{
event MessageSent(bytes message);
uint256 public myNumber = 12;
constructor(
address rootParent
) CrossChainEnabledPolygonChild(MUMBAI_FX_CHILD) {
_grantRole(
_crossChainRoleAlias(DEFAULT_ADMIN_ROLE),
rootParent
);
}
function setNumberForParentChain(
uint256 newNumber
) external onlyRole(DEFAULT_ADMIN_ROLE) {
myNumber = newNumber;
}
function _sendMessageToRoot(
bytes memory message
) internal {
emit MessageSent(message);
}
}
2. Creating the Child Contract
And then we can create the child contract that we will deploy on the child blockchain. In our case this will be the Polygon network. We can inherit from the Openzeppelin CrossChainEnabledPolygonChild.sol contract and pass FX Portal Child contract depending on the network:
- MUMBAI_FX_CHILD = 0xCf73231F28B7331BBe3124B907840A94851f9f11
- MAINNET_FX_CHILD = 0x8397259c983751DAf40400790063935a11afa28a
And now we can also make use of the AccessControlCrossChain.sol from Openzeppelin. Just inherit from it in the contract and we'll get the usual access control functions along with a new _crossChainRoleAlias
function.
In our example upon deployment we will pass the previously deployed root contract address here and immediately grant it the admin role, but since this is actually a crosschain communication, it works a little differently:
- Of course the onlyRole modifier cannot just check the msg.sender, so instead it uses the CrossChainEnabled.sol interface to determine the actual CrossChain sender.
- And to further prevent access from contracts in the child chain with the same address as in the root chain, we need to distinguish between senders from msg.sender directly or from CrossChain. For that we can grant a specific role using
_crossChainRoleAlias
.
And then let's add a test function setNumberForParentChain
which only the CrossChain root is allowed to call.
And just for completeness, if you wanted to send a message back to the root, in Polygon you could do so by emitting the MessageSent event.
3. Get Encoded Data Helper
This is completely optional, but for our testing you could add an extra function like this:
function getEncodedSetNumberData(uint256 newNumber) external pure returns (bytes memory) {
return abi.encodeWithSelector(PolygonChild.setNumberForParentChain.selector, newNumber);
}
Basically it will return the encoded data if you wanted to call setNumberForParentChain. This data is what you would need to send along in the root contract via sendMessageToChild
. Of course in most setups you would implement this just using Web3.js or whatever frontend framework you're using.
4. Testing the CrossChain Transfer on Remix
// SPDX-License-Identifier: MIT
pragma solidity 0.8.13;
import {CrossChainEnabledPolygonChild} from "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/crosschain/polygon/CrossChainEnabledPolygonChild.sol";
import {AccessControlCrossChain} from "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/AccessControlCrossChain.sol";
import {FxBaseRootTunnel} from "https://github.com/fx-portal/contracts/blob/main/contracts/tunnel/FxBaseRootTunnel.sol";
address constant MUMBAI_FX_CHILD = 0xCf73231F28B7331BBe3124B907840A94851f9f11;
address constant GOERLI_CHECKPOINT_MANAGER = 0x2890bA17EfE978480615e330ecB65333b880928e;
address constant GOERLI_FX_ROOT = 0x3d1d3E34f7fB6D26245E6640E1c50710eFFf15bA;
address constant MAINNET_FX_CHILD = 0x8397259c983751DAf40400790063935a11afa28a;
address constant MAINNET_CHECKPOINT_MANAGER = 0x86E4Dc95c7FBdBf52e33D563BbDB00823894C287;
address constant MAINNET_FX_ROOT = 0xfe5e5D361b2ad62c541bAb87C45a0B9B018389a2;
contract PolygonChild is CrossChainEnabledPolygonChild, AccessControlCrossChain {
uint256 public myNumber;
constructor(address rootParent) CrossChainEnabledPolygonChild(MUMBAI_FX_CHILD) {
_grantRole(_crossChainRoleAlias(DEFAULT_ADMIN_ROLE), rootParent);
myNumber = 12;
}
function setNumberForParentChain(uint256 newNumber) external onlyRole(DEFAULT_ADMIN_ROLE) {
myNumber = newNumber;
}
function getEncodedSetNumberData(uint256 newNumber) external pure returns (bytes memory) {
return abi.encodeWithSelector(PolygonChild.setNumberForParentChain.selector, newNumber);
}
}
contract PolygonRoot is FxBaseRootTunnel {
bytes public latestData;
constructor() FxBaseRootTunnel(GOERLI_CHECKPOINT_MANAGER, GOERLI_FX_ROOT) {}
function _processMessageFromChild(bytes memory data) internal override {
latestData = data;
}
function sendMessageToChild(bytes memory message) public {
_sendMessageToChild(message);
}
}
And now you can
- Switch MetaMask to Goerli and deploy the PolygonRoot.
- Switch MetaMask to Mumbai and copy the address and deploy PolygonChild for the constructor input.
- Switch MetaMask to Goerli and call
setFxChildTunnel
on PolygonRoot passing the child address. - Now encode the data you want to send. For example to set the number for
setNumberForParentChain
as 42, the encoded data would be: 0x21148d91000000000000000000000000000000000000000000000000000000000000002a. The easiest way to get this is viagetEncodedSetNumberData
. - Call sendMessageToChild and pass along the encoded data. This will initiate the CrossChain transfer. It might take a while.
- Wait.... meanwhile you can double check the events from the FX_CHILD here or simply the transfers of the zero address here.


If that looks confusing to you, then that's no surprise. The zero address is a special system address in Polygon which is used to commit the CrossChain transfers. And the transfers also end up in the events list of the child.
In my tests it took anywhere between 2 to 25 minutes until the CrossChain transfer on Polygon was completed.
And that's it!
If you did everything correctly, you can switch back to Mumbai and read the newly set number which should have changed to 42.

Solidity Developer
More great blog posts from Markus Waas
How to use ChatGPT with Solidity
Using the Solidity Scholar and other GPT tips
How to integrate Uniswap 4 and create custom hooks
Let's dive into Uniswap v4's new features and integration
How to integrate Wormhole in your smart contracts
Entering a New Era of Blockchain Interoperability
Solidity Deep Dive: New Opcode 'Prevrandao'
All you need to know about the latest opcode addition
How Ethereum scales with Arbitrum Nitro and how to use it
A blockchain on a blockchain deep dive
The Ultimate Merkle Tree Guide in Solidity
Everything you need to know about Merkle trees and their future
The New Decentralized The Graph Network
What are the new features and how to use it
zkSync Guide - The future of Ethereum scaling
How the zero-knowledge tech works and how to use it
Deploying Solidity Contracts in Hedera
What is Hedera and how can you use it.
Writing ERC-20 Tests in Solidity with Foundry
Blazing fast tests, no more BigNumber.js, only Solidity
ERC-4626: Extending ERC-20 for Interest Management
How the newly finalized standard works and can help you with Defi
Advancing the NFT standard: ERC721-Permit
And how to avoid the two step approve + transferFrom with ERC721-Permit (EIP-4494)
Moonbeam: The EVM of Polkadot
Deploying and onboarding users to Moonbeam or Moonriver
Advanced MultiSwap: How to better arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
Deploying Solidity Smart Contracts to Solana
What is Solana and how can you deploy Solidity smart contracts to it?
Smock 2: The powerful mocking tool for Hardhat
Features of smock v2 and how to use them with examples
How to deploy on Evmos: The first EVM chain on Cosmos
Deploying and onboarding users to Evmos
EIP-2535: A standard for organizing and upgrading a modular smart contract system.
Multi-Facet Proxies for full control over your upgrades
MultiSwap: How to arbitrage with Solidity
Making multiple swaps across different decentralized exchanges in a single transaction
The latest tech for scaling your contracts: Optimism
How the blockchain on a blockchain works and how to use it
Ultimate Performance: The Aurora Layer2 Network
Deploying and onboarding users to the Aurora Network powered by NEAR Protocol
What is ecrecover in Solidity?
A dive into the waters of signatures for smart contracts
How to use Binance Smart Chain in your Dapp
Deploying and onboarding users to the Binance Smart Chain (BSC)
Using the new Uniswap v3 in your contracts
What's new in Uniswap v3 and how to integrate Uniswap v3
What's coming in the London Hardfork?
Looking at all the details of the upcoming fork
Welcome to the Matrix of blockchain
How to get alerted *before* getting hacked and prevent it
The Ultimate Ethereum Mainnet Deployment Guide
All you need to know to deploy to the Ethereum mainnet
SushiSwap Explained!
Looking at the implementation details of SushiSwap
Solidity Fast Track 2: Continue Learning Solidity Fast
Continuing to learn Solidity fast with the advanced basics
What's coming in the Berlin Hardfork?
Looking at all the details of the upcoming fork
Using 1inch ChiGas tokens to reduce transaction costs
What are gas tokens and example usage for Uniswap v2
Openzeppelin Contracts v4 in Review
Taking a look at the new Openzeppelin v4 Release
EIP-3156: Creating a standard for Flash Loans
A new standard for flash loans unifying the interface + wrappers for existing ecosystems
Tornado.cash: A story of anonymity and zk-SNARKs
What is Tornado.cash, how to use it and the future
High Stakes Roulette on Ethereum
Learn by Example: Building a secure High Stakes Roulette
How to implement generalized meta transactions
We'll explore a powerful design for meta transactions based on 0x
Utilizing Bitmaps to dramatically save on Gas
A simple pattern which can save you a lot of money
Using the new Uniswap v2 as oracle in your contracts
How does the Uniswap v2 oracle function and how to integrate with it
Smock: The powerful mocking tool for Hardhat
Features of smock and how to use them with examples
How to build and use ERC-721 tokens in 2021
An intro for devs to the uniquely identifying token standard and its future
Trustless token management with Set Protocol
How to integrate token sets in your contracts
Exploring the new Solidity 0.8 Release
And how to upgrade your contracts to Solidity 0.8
How to build and use ERC-1155 tokens
An intro to the new standard for having many tokens in one
Leveraging the power of Bitcoins with RSK
Learn how RSK works and how to deploy your smart contracts to it
Solidity Fast Track: Learn Solidity Fast
'Learn X in Y minutes' this time with X = Solidity 0.7 and Y = 20
Sourcify: The future of a Decentralized Etherscan
Learn how to use the new Sourcify infrastructure today
Integrating the 0x API into your contracts
How to automatically get the best prices via 0x
How to build and use ERC-777 tokens
An intro to the new upgraded standard for ERC-20 tokens
COMP Governance Explained
How Compound's Decentralized Governance is working under the hood
How to prevent stuck tokens in contracts
And other use cases for the popular EIP-165
Understanding the World of Automated Smart Contract Analyzers
What are the best tools today and how can you use them?
A Long Way To Go: On Gasless Tokens and ERC20-Permit
And how to avoid the two step approve + transferFrom with ERC20-Permit (EIP-2612)!
Smart Contract Testing with Waffle 3
What are the features of Waffle and how to use them.
How to use xDai in your Dapp
Deploying and onboarding users to xDai to avoid the high gas costs
Stack Too Deep
Three words of horror
Integrating the new Chainlink contracts
How to use the new price feeder oracles
TheGraph: Fixing the Web3 data querying
Why we need TheGraph and how to use it
Adding Typescript to Truffle and Buidler
How to use TypeChain to utilize the powers of Typescript in your project
Integrating Balancer in your contracts
What is Balancer and how to use it
Navigating the pitfalls of securely interacting with ERC20 tokens
Figuring out how to securely interact might be harder than you think
Why you should automatically generate interests from user funds
How to integrate Aave and similar systems in your contracts
How to use Polygon (Matic) in your Dapp
Deploying and onboarding users to Polygon to avoid the high gas costs
Migrating from Truffle to Buidler
And why you should probably keep both.
Contract factories and clones
How to deploy contracts within contracts as easily and gas-efficient as possible
How to use IPFS in your Dapp?
Using the interplanetary file system in your frontend and contracts
Downsizing contracts to fight the contract size limit
What can you do to prevent your contracts from getting too large?
Using EXTCODEHASH to secure your systems
How to safely integrate anyone's smart contract
Using the new Uniswap v2 in your contracts
What's new in Uniswap v2 and how to integrate Uniswap v2
Solidity and Truffle Continuous Integration Setup
How to setup Travis or Circle CI for Truffle testing along with useful plugins.
Upcoming Devcon 2021 and other events
The Ethereum Foundation just announced the next Devcon in 2021 in Colombia
The Year of the 20: Creating an ERC20 in 2020
How to use the latest and best tools to create an ERC-20 token contract
How to get a Solidity developer job?
There are many ways to get a Solidity job and it might be easier than you think!
Design Pattern Solidity: Mock contracts for testing
Why you should make fun of your contracts
Kickstart your Dapp frontend development with create-eth-app
An overview on how to use the app and its features
The big picture of Solidity and Blockchain development in 2020
Overview of the most important technologies, services and tools that you need to know
Design Pattern Solidity: Free up unused storage
Why you should clean up after yourself
How to setup Solidity Developer Environment on Windows
What you need to know about developing on Windows
Avoiding out of gas for Truffle tests
How you do not have to worry about gas in tests anymore
Design Pattern Solidity: Stages
How you can design stages in your contract
Web3 1.2.5: Revert reason strings
How to use the new feature
Gaining back control of the internet
How Ocelot is decentralizing cloud computing
Devcon 5 - Review
Impressions from the conference
Devcon 5 - Information, Events, Links, Telegram
What you need to know
Design Pattern Solidity: Off-chain beats on-chain
Why you should do as much as possible off-chain
Design Pattern Solidity: Initialize Contract after Deployment
How to use the Initializable pattern
Consensys Blockchain Jobs Report
What the current blockchain job market looks like
Provable — Randomness Oracle
How the Oraclize random number generator works
Solidity Design Patterns: Multiply before Dividing
Why the correct order matters!
Devcon 5 Applications closing in one week
Devcon 5 Applications closing
Randomness and the Blockchain
How to achieve secure randomness for Solidity smart contracts?