State Transfer

Overview

Matic validators continuously monitor a contract on Ethereum chain called StateSender. Each time a registered contract on Ethreum chain calls this contract, it emits an event. Using this event Matic validators relay the data to another contract on Matic chain. This StateSync mechanism is used to send data from Ethereum to Matic.

Matic validators also periodically submit a hash of all transactions on Matic chain to Ethereum chain. This Checkpoint can be used to verify any transaction that happened on Matic. Once a transaction is verified to have happened on Matic chain, action can be taked accordingly on Ethereum.

These 2 mechanisms can be used together to enable two way data(state) transfer between Ethereum and Matic. To abstract out all these interactions, you can directly inherit our FxBaseRootTunnel (on Ethereum) and FxBaseChildTunnel (on Matic) contracts.

Root Tunnel Contract

Use the FxBaseRootTunnel contract from here. This contract gives access to following functions:

  • function _processMessageFromChild(bytes memory data): This is a virtual function that needs to be implemented in the contract which inherits it to handle data being sent from ChildTunnel.
  • _sendMessageToChild(bytes memory message): This function can be called internally with any bytes data as a message. This data will be sent as it is to the child tunnel.
  • receiveMessage(bytes memory inputData): This function needs to be called to receive the message emitted by ChildTunnel. The proof of transaction needs to be provided as calldata. An example script to generate proof using matic.js is included below.

Child Tunnel Contract

Use the FxBaseChildTunnel contract from here. This contract gives access to following functions:

  • function _processMessageFromRoot(uint256 stateId, address sender, bytes memory data): This is a virtual function that needs to implement the logic to handle message sent from the RootTunnel.
  • function _sendMessageToRoot(bytes memory message): This function can be called internally to send any bytes message to the root tunnel.

Pre-requisite

Example contracts of state transfer bridge

State transfer from Ethereum to Matic

State transfer from Matic to Ethereum

// npm i @maticnetwork/maticjs
const maticPOSClient = new require("@maticnetwork/maticjs").MaticPOSClient({
maticProvider: "https://rpc-mumbai.matic.today", // replace if using mainnet
parentProvider: "https://rpc.slock.it/goerli", // replace if using mainnet
});
const proof = maticPOSClient.posRootChainManager
.customPayload(
"0x3cc9f7e675bb4f6af87ee99947bf24c38cbffa0b933d8c981644a2f2b550e66a", // replace with txn hash of sendMessageToRoot
"0x8c5261668696ce22758910d05bab8f186d6eb247ceac2af2e82c7dc17669b036" // SEND_MESSAGE_EVENT_SIG, do not change
)
.then(console.log);