My Image
CoursesQuizzesProblemsContestsSmartBooks
Contest!

No results found

LOGINREGISTER
My ProgressCoursesQuizzesProblemsContestsSmartbooks
Published on 16 Aug 2021
Transfer assets from Ethereum to Polygon using Plasma bridge
Plasma method of transferring assets from Polygon to Ethereum
img
Aniket Savji
0
Like
612

Introduction

Polygon brings you a trustless two-way transaction channel between Polygon and Ethereum by introducing the cross-chain bridge with Plasma and PoS security. With this users can transfer tokens across Polygon without incurring third-party risks and market liquidity limitations.

A bridge is basically a set of contracts that help in moving assets from the root chain to the child chain. There are primarily two bridges to move assets between Ethereum and Matic. First one is the Plasma bridge and the second one is called the PoS Bridge or Proof of Stake bridge. Plasma bridge provides an increased security guarantees due to the Plasma exit mechanism.

This Smartbook will show you, transferring of assets from Polygon network to Ethereum network i.e from Parent chain to Child chain or we can say depositing assets using Plasma Bridge. You can refer this Smartbook for the same transfer but with implementing POS bridge .

In this SmartBook we will be using Goeril test network as our parent network and Matic Mumbai test network as our child network and transfer already mapped ERC20 Test Token.

 

Configuration

1. Getting rpc url 

RPC urls of both the networks are needed in order to communicate with respective blockchain networks. There are many rpc providers such as Infura, Alchemy, Chainstack, MaticVigil, QuickNode and Ankr but for this toutorial we will be using,

  • Infura for Goeril Testnet.
  • MaticVigil for Matic Mumbai Testnet.

Visit Infura and MaticVigil , log in and create your project to get rpc urls.

2. Getting test tokens

You can get test tokens from matic's faucet. 

There you need to select  (Plasma) Test ERC20 from Select Token section and from Select Network section , select Goerli. Then enter your address, click on submit and confirm.

3. Configuring Metamask

In order to interact with Polygon blockchain, Polygon network must be configured on Metamask. You can refer this article to configure Metamask. You need to add test tokens mentioned in the previous step.

Addresses for both of these tokens are as follows :

  • Plasma Parent Chain  -  Goeril ERC20-Test Token                  :    "0x3f152B63Ec5CA5831061B2DccFb29a874C317502" 
  • Plasma Child Chain     -  Matic Mumbai ERC20-Test Token  :    "0x2d7882beDcbfDDce29Ba99965dd3cdF7fcB10A1e" 

 

NodeJs Code

1. Initialise Nodejs 

First initialise nodejs project and create working file with following commands,

> npm init

> touch index.js

2. Install Dependencies

Dependencies required and their commands for installation are as follows  :

a) Dependencies

  • Maticjs 
  • Truffle's hdwallet provider
  • Web3

b) Commands

> npm install @maticnetwork/maticjs

> npm install @truffle/hdwallet-provider

> npm install web3

Now that installation process is complete lets look at the code.

Deposit Code

a) Initialise dependencies

Let's first initialise the installed dependencies

const web3 = require('web3');
const Matic = require("@maticnetwork/maticjs").default;
const HDWalletProvider = require("@truffle/hdwallet-provider");
const Network = require("@maticnetwork/meta/network");

b) Initialise Matic Object

To create a MaticPOSClient instance its object require parent provider and child provider i.e matic provider . We can create those providers with the rpc url and private key of the account from which we are going to do transactions with the help of HDWalletProvider that we initialised before from truffle's hdwallet provider library.

const network = new Network("testnet", "mumbai");
const from = "<Public Key>";
const private_key = "<Private Key>";

const matic = new Matic({
    network: "testnet",
    version: "mumbai",
    parentProvider: new HDWalletProvider(
        private_key,
        "https://goerli.infura.io/v3/<API>"
    ),
    maticProvider: new HDWalletProvider(
        private_key,
        "https://rpc-mumbai.maticvigil.com/v1/<API>"
    ),
    parentDefaultOptions: from,
    maticDefaultOptions: from,
});

c) Deposit Assets

According to Polygon's guidelines, Deposit ERC20 is a 2 step process :

  • The tokens need to be first approved to the Matic rootchain contract on Parent Chain (Ethereum/Goerli).
  • Once approved, then the deposit function is to be invoked where the tokens get deposited to the Matic contract, and are available for use in the Matic network.

So let's create a function execute and put both, approve and deposit function, in it.

async function execute() {

    const token = network.Main.Contracts.Tokens.TestToken;
    const amount = matic.web3Client.web3.utils.toWei('0.01');

    // approve
    console.log("Approve Initiated");
    await matic.approveERC20TokensForDeposit(token, amount, {
        from: from
    }).then((res) => {
        console.log("approve hash: ", res.transactionHash)
    });

    // deposit
    console.log("Deposit Initiated");
    await matic.depositERC20ForUser(token, from, amount, {
        from: from
    }).then((res) => {
        console.log("deposit hash: ", res.transactionHash)
    });
}

execute().then(_ => process.exit(0));

 d) Execute Code

Replace Public Address, Private Key and API of both providers before executing.  Use the following command to run the code and you will see assets getting deposited.

> node index.js

Deposits from Ethereum to Matic happen using a state sync mechanism and takes about ~5-7 minutes. 

 

Complete Code

const web3 = require('web3');
const Matic = require("@maticnetwork/maticjs").default;
const HDWalletProvider = require("@truffle/hdwallet-provider");
const Network = require("@maticnetwork/meta/network");

const network = new Network("testnet", "mumbai");
const from = "<Public Key>";
const private_key = "<Private Key>";

const matic = new Matic({
    network: "testnet",
    version: "mumbai",
    parentProvider: new HDWalletProvider(
        private_key,
        "https://goerli.infura.io/v3/<API>"
    ),
    maticProvider: new HDWalletProvider(
        private_key,
        "https://rpc-mumbai.maticvigil.com/v1/<API>"
    ),
    parentDefaultOptions: from,
    maticDefaultOptions: from,
});

async function execute() {

    const token = network.Main.Contracts.Tokens.TestToken;
    const amount = matic.web3Client.web3.utils.toWei('0.01');

    // approve
    console.log("Approve Initiated");
    await matic.approveERC20TokensForDeposit(token, amount, {
        from: from
    }).then((res) => {
        console.log("approve hash: ", res.transactionHash)
    });

    // deposit
    console.log("Deposit Initiated");
    await matic.depositERC20ForUser(token, from, amount, {
        from: from
    }).then((res) => {
        console.log("deposit hash: ", res.transactionHash)
    });
}

execute().then(_ => process.exit(0));
Enjoyed the SmartBook?
Like
logo
contact@dapp-world.com
Katraj, Pune, Maharashtra, India - 411048

Follow Us

linkedintwitteryoutubediscordinstagram

Products

  • SmartBooks
  • Courses
  • Quizzes
  • Assessments

Support

  • Contact Us
  • FAQ
  • Privacy Policy
  • T&C

Backed By

ah! ventures

Copyright 2023 - All Rights Reserved.

Recommended from DAppWorld
img
1 May 2021
How to connect Ganache with Metamask and deploy Smart contracts on remix without
Set up your development environment with (Metamask + Ganache + Remix) and skip truffle :)
3 min read
11509
5
img
8 Jul 2021
How to interact with smart contarct from backend node js
call and send functions from backend server side using nodejs
3 min read
8103
2
img
18 Aug 2021
Send transaction with web3 using python
Introduction to web3.py and sending transaction on testnet
3 min read
6229
5
img
5 Aug 2021
Deploy Smart Contract on Polygon POS using Hardhat
how to deploy smart contracts on polygon pos chain using hardhat both mainnet and testnet ?
3 min read
5540
3