How to use Polygon (Matic) in your Dapp

Deploying and onboarding users to  Polygon  to avoid the high gas costs

Gas costs are exploding again, ETH2.0 is still too far away and people are now looking at layer 2 solutions. Here's a good overview of existing layer 2 projects: https://github.com/Awesome-Layer-2/awesome-layer-2. Today we will take a closer look at Polygon (previously known as Matic) as a solution for your Dapp.

Why Polygon?

With Polygon you essentially get two layer 2 solutions in one, sidechains and Plasma. They have recently launched their mainnet Proof-of-Stake sidechain and you can deploy your smart contracts to it. Or you could use Plasma for less complex functionality, but with higher security.

Polygon has a three-layer architecture:

  1. Staking and Plasma smart contracts on Ethereum
  2. Heimdall (Proof of Stake layer)
  3. Bor (Block producer layer)

Matic Architecture

The system ensures liveliness using PoS checkpoints which are pushed to the Ethereum mainchain. Those checkpoints for Plasma ensure high security of funds using the mainchain as security. For the sidechain they allow synchronisation with the mainchain relying on the PoS security.

Let's see the differences between both approaches.

Sidechains

Sidechains are generally EVM-compatible, separate blockchains with their own consensus models. Polygon is using a Proof-of-Stake mechanism using their own MATIC token on the Ethereum mainnet. Sidechains are designed to easily allow transfer of value and arbitrary state with the Ethereum chain.

+ allow you to run fully functioning smart contracts
+ arbitrary data exchange with mainchain
- security relies on small set of nodes in the sidechain
- not suitable for high-value applications


side chain vs plasma

Plasma

Plasma uses a combination of smart contracts and cryptographic verification. Together, these enable fast and cheap transactions by offloading these transactions from the main Ethereum blockchain into a plasma chain. In contrast to regular sidechains, you cannot run any smart contract in here, but they allow users to retrieve funds even if the plasma chain operator is malicious. For more details have a look here.

+ rely on mainchain security
+ require much less trust in chain operator
- no arbitrary data exchange
- only allow simple transfers, e.g., ERC-20


What makes Polygon different

Polygon's hybrid approach allows you to use Plasma and sidechains in one system. For general smart contracts, you can deploy and use it as a general sidechain, while for simple, high-value transfers you can make use of Plasma. Polygon also uses a public checkpointing layer which publishes checkpoints after periodic intervals allowing the side chains to operate at high speeds while publishing the checkpoints in batches.

How to deploy to Polygon

Deploying to the Polygon sidechain is very simple. If you're using Truffle, simply add the Polygon network configuration like this:

matic: {
      provider: () => new HDWalletProvider(mnemonic, `https://rpc-mumbai.matic.today`),
      network_id: 80001,
      confirmations: 2,
      timeoutBlocks: 200,
      skipDryRun: true
    },
}

You'll also need funds in the sidechain of course. For the testnet you can use the faucet or transfer funds from the public chain. The Mumbai testnet is connected to the Goerli testnet. You can find a Goerli faucet here or the Mumbai faucet here. For how to transfer funds from the public chain, read on.

Onboarding users

MetaMask

To interact with the side chain, users need to add the Polygon network to their MetaMask. Click on the network selection in MetaMask and then choose 'Custom RPC'. For the current testnet, use the configuration of

  • RPC URL: https://rpc-mumbai.matic.today
  • ChainID: 80001
  • Symbol: MATIC
Block Explorer URL: https://mumbai-explorer.matic.today

While for the mainnet, you can use:

  • RPC URL: https://rpc-mainnet.matic.network
  • ChainID: 137
  • Symbol: MATIC
  • Block Explorer URL: https://explorer.matic.network/


Matic MetaMask

Using the MaticJS library

For the best user experience, you may want to integrate moving funds from sidechain <-> mainchain properly in your Dapp. You can use the MaticJs library for that. For the mainnet, just make sure to use the correct RPC urls.

$ npm install @maticnetwork/maticjs --save

Then you can initialize the client.

import Matic from "@maticnetwork/maticjs";

const maticPOSClient = new Matic.MaticPOSClient({
  parentProvider: new HDWalletProvider(
    PRIVATE_KEY,
    "https://goerli.infura.io/v3/75aa7935112647bc8cc49d20beafa189"
  ),
  maticProvider: new HDWalletProvider(
    PRIVATE_KEY,
    "https://rpc-mumbai.matic.today"
  ),
  posRootChainManager: "0xBbD7cBFA79faee899Eaf900F13C9065bF03B1A74",
});
Now you can transfer funds from and to the sidechain. In the example on the right, we deposit ETH from the Goerli testnet. Later on we can move it back in 2-step process:
  1. Burn the funds on the sidechain.
  2. Once the checkpoint is added, retrieve in back to the testnet.

Checkpoints on the Mumbai testnet only take 5 minutes of time for improved testing capabilities. On the mainnet this will be a 7-day period.
const txConfig = { from, gasPrice: "10000000000" };

// Deposit
await maticPOSClient.depositEtherForUser(from, amount, txConfig);

// Burn
const burnHash = await maticPOSClient.burnERC20(
  "0x4DfAe612aaCB5b448C12A591cD0879bFa2e51d62", // WETH address
  amount,
  txConfig
);

// Retrieve in main after checkpoint
await maticPOSClient.exitERC20(burnHash);
You can also use the Matic Wallet tool for transferring funds manually: https://wallet.matic.today/.

The Plasma way

Using the MaticJs library, the deposit and withdraw via Plasma are very similar. Just keep in mind that if you want to ensure the Plasma securities, you cannot run any smart contract. You can however allow simple transfers, for example like this:

await maticPlasma.transferERC20Tokens(token, recipient, amount, { from })

See here on how to initialize the maticPlasma client.

Layer-2 solutions

That's it, it's really quite simple from a developer's perspective. But really make sure you understand the trade-offs between layer-1, sidechains and plasma before making a decision. That's the hard part.

 If you feel like adding Polygon, you might also want to look at the 50,000$ bounty program they currently have ongoing: https://blog.matic.network/launching-of-large-scale-developer-initiatives-for-mainnet-adoption/.


Have you used Polygon before? Maybe even on Mainnet? Or what other layer-2 solutions did you look at or would be interested to hear about next? Please let me know in the comments.


Markus Waas

Solidity Developer

More great blog posts from Markus Waas

© 2024 Solidity Dev Studio. All rights reserved.

This website is powered by Scrivito, the next generation React CMS.