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:
- Staking and Plasma smart contracts on Ethereum
- Heimdall (Proof of Stake layer)
- Bor (Block producer layer)

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

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
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/

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",
});
- Burn the funds on the sidechain.
- 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);
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.
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
Exploring the Openzeppelin CrossChain Functionality
What is the new CrossChain support and how can you 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
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?