The Hackett Group Announces Strategic Acquisition of Leading Gen AI Development Firm LeewayHertz
Select Page

How to Build a dApp on Polygon?

dApp-on-Polygon

Ethereum is immensely popular due to its open-source ecosystem and the capability to address the challenges of Bitcoin blockchain. Like, Bitcoin blockchain cannot support the development of decentralized applications and solutions. In contrast, Ethereum offers an open-source platform where anyone can build blockchain-powered solutions and contribute to the ecosystem’s growth.

Even though Ethereum brings unique features, including its built-in programming language, EVM (Ethereum virtual machine), and smart contracts, some limitations exist within this blockchain. Network congestion, low throughput, and high transaction cost lead to scalability issues in Ethereum. To solve the prevailing issues on Ethereum, a core team of four software developers launched the Polygon network.

Polygon adopts the proof-of-stake consensus mechanism and is driven by the layer-2 scaling solutions. The network leverages Ethereum’s technology and adds more value to it. With that, Polygon enables higher throughput, low-cost transactions, and better development options on Ethereum’s ecosystem and various Ethereum-compatible blockchains.

Polygon is also popular for its unique viability in supporting dApp development. Developers can leverage Polygon’s SDKs and developer’s tools and build their business-specific decentralized applications. This insight will elaborate dApp development on the Polygon network through a step-to-step tutorial.

What is Polygon Blockchain?

Polygon is a blockchain scalability platform and framework focused on connecting and building Ethereum- compatible blockchain networks. Polygon was formerly known as the Matic network. It calls itself ‘Ethereum’s internet of blockchains’ since Polygon is on a mission to aggregate scalable solutions to form a multichain Ethereum ecosystem. Following are the distinct features of Polygon:-

  • Polygon network is also known as a layer-2 solution for Ethereum designed to be interoperable with Ethereum’s existing and future infrastructures while offering an advanced framework consisting of sidechains and sovereign blockchains.
  • Layer 2 solution is built on the base chain to reduce the limitations associated with the base chain and complement its basic pain points.
  • Polygon is essentially a Plasma-based aggregator that offers a framework supporting off-chain dApp development with fortified security, speed, and scalability. This Plasma framework is one of the leading reasons behind the mass adoption of Polygon.
  • Polygon implements Plasma in the form of Polygon Plasma Chains. It constitutes a framework for dApp development besides reducing transaction load on the main blockchain for faster and cheaper transactions.

For an in-depth analysis of Polygon blockchain, read this detailed insight.

What Limitations are there on Ethereum?

Ethereum blockchain has been designed to be a powerful and revolutionary blockchain for enterprises. However, it has certain limitations.

  • The biggest challenge for Ethereum is the low throughput issue. It can handle only 30 transactions per second and is comparatively low than most second-generation blockchains.
  • The average transaction fee on Ethereum is $51.45. However, the exact fee is determined by the supply and demand tactics of the network’s miners.
  • Ethereum lacks true interoperability. Thus it cannot allow the Ethereum-compatible blockchains to interact with each other.
  • With no protocol to connect these blockchains, Ethereum creates major challenges related to the development and leads to ecosystem fragmentation.

How can Polygon solve these limitations?

Polygon acts as a protocol and framework that supports the development of Ethereum-compatible blockchains and connects all of these networks to Ethereum. Here’s how Polygon can address Ethereum’s limitations.

  • Polygon enables the one-click deployment of encoded blockchain networks.
  • It offers a growing set of modules to develop custom networks.
  • With its interoperability protocol, Polygon allows Ethereum and other blockchains to share arbitrary messages among them.
  • Enhances security system on the blockchains using its modular and optional ‘security as a service.’
  • Polygon’s adaptor modules enable higher interoperability for existing blockchain networks.

Why Consider dApp Development on Polygon?

Polygon has emerged as a leading platform facilitating the development of scalable Ethereum solutions and various decentralized infrastructures. The network keeps growing with multiple project partners and ingenious tools introduced from time to time.

As of now, 300+ decentralized applications have been built on the ecosystem, and more projects are under development. With this scope in view, let’s explore the benefits of Polygon for its developers.

dApp-Development-on-Polygon

How to Build a Decentralized App on Polygon?

This section will guide you on building a decentralized application (dApp) on the Polygon blockchain that allows users to create a wallet using their email and connect to multiple networks within the app.

For this guide, we are using Magic as a key-based authentication system. Magic is a developer SDK that integrates with your existing application and enables passwordless authentication using magic links (exactly like Medium and Slack).

Developer Quick Start

If you are versed with Ethereum-based development, you can be a good Polygon developer. Every tool you use on Ethereum is supported on Polygon, like Truffle, Remix, Web3js.

Hence, Switch over to Polygon’s RPC and start developing your dApp.

Step:1 Connecting to Polygon

Using magic.js, we need two Magic and two Web3 instances to use one for each network; Ethereum and Polygon. By this feature, you allow users to switch between these two platforms.

We will use the same API key for both Magic instances so users’ public address doesn’t change. Run the following command:

Unlock the power of web3 with our Polygon Development Services.

LeewayHertz Polygon Development Services

import { Magic } from 'magic-sdk';
import Web3 from 'web3';
/**
NOTE: When connecting to a testnet, TEST API keys must be used from the Magic dashboard (live API keys for eth mainnet)
*/
const customNodeOptions = {
rpcUrl: 'https://rpc-mumbai.matic.today',
chainId: 80001
}
// Setting network to Matic
export const magicMatic = new Magic(process.env.REACT_APP_MAGIC_PUBLISHABLE_KEY, { network: customNodeOptions });
magicMatic.network = "matic"
export const maticWeb3 = new Web3(magicMatic.rpcProvider);
// Setting network to Ethereum (Ropsten Testnet)
export const magicEthereum = new Magic(process.env.REACT_APP_MAGIC_PUBLISHABLE_KEY, { network: 'ropsten' });
magicEthereum.network = "ethereum"
export const ethWeb3 = new Web3(magicEthereum.rpcProvider);

Step:2 Switching Between Networks

The Polygon-based dApps allow you to switch between the Ethereum and Polygon network through the select element dropdown list. One Magic instance points towards Ethereum and the other towards Polygon. Thus, you need to update the instance we are using for our decentralized app based on users’ network selection. Use the given command:

import { magicEthereum, magicMatic, ethWeb3, maticWeb3 } from "../magic";

const handleChangeNetwork = (e) => {

e.target.value === 'ethereum' ? setMagic(magicEthereum) : setMagic(magicMatic);

fetchBalance(userMetadata.publicAddress);

fetchContractMessage();

}

return (
< select name="network" onchange="{(e)">handleChangeNetwork(e)}>
< option value="ethereum">Ethereum (Ropsten Testnet)< /option>
< option value="matic">Matic (Mumbai Testnet)< /option>
</div > )

Step: 3 Viewing User Balance

Users’ public address remains the same on Ethereum and Polygon blockchain (unless you use a different API for each instance). Thus, a simple web3.eth.getBalance call is required for both the networks. Because the native token of Ethereum is ETH, and for Polygon is MATIC, we’re displaying the appropriate token symbol based on the network we’re connected to.
The public address for a user. Use the given command:

const fetchBalance = (address) => {

web3.eth.getBalance(address).then(bal => setBalance(web3.utils.fromWei(bal)))

}

return (

Balance


{balance.toString().substring(0, 6)} {magic.network === 'matic' ? 'MATIC' : 'ETH'}

)


Step:4 Sending Transaction

Sending a transaction is no brainstormer, and it’s the same for the network you are connected to. You only need to provide the amount to send, and from and to addresses. Moreover, if no gas or gas prices are passed, the overall gas limit and price are calculated automatically.

const web3 = magic.network === "ethereum" ? ethWeb3 : maticWeb3;

const sendTransaction = async () => {

if (!toAddress || !amount) return;

const receipt = await web3.eth.sendTransaction({

from: publicAddress,

to: toAddress,

value: web3.utils.toWei(amount)

});

}

return (

Send Transaction
< input type="text" value="{toAddress}" /> setToAddress(e.target.value)}

placeholder="To Address"

/>

< input type="text" value="{amount}" /> setAmount(e.target.value)}

placeholder="Amount"

/>

Send Transaction

)

Step:5 Calling Smart Contracts

You need to deploy separate smart contracts on Ethereum and Polygon to allow users to interact with them separately. For this, you must know the correct address where contracts need to be deployed.

const network = magic.network === "ethereum" ? 'ethereum' : 'matic';

const ropstenContractAddress = '0x8cb46E4bFc14Ce010dFbE5Ecb61BA64d798D3A67';

const maticContractAddress = '0x9ebE0B009146643bb3560375A4562D8d89E135e9';

const contract = new web3.eth.Contract(abi, network === "ethereum" ? ropstenContractAddress : maticContractAddress);

// Grabbing message variable value stored in the smart contract

const fetchContractMessage = () => contract.methods.message().call().then(setMessage)

// Update contract message value on the blockchain

const updateContractMessage = async () => {

if (!newMessage) return;

const receipt = await contract.methods.update(newMessage).send({ from: user.publicAddress });

}

return (
Contract Message
{message}
Update Message
< Input type="text" value="{newMessage}" /> setNewMessage(e.target.value)}

placeholder="New Message" />
Update

)

Final Step: Done
That’s done! You have successfully built your dApp on Polygon.

EndNote- Build Your Decentralized App with LeewayHertz

Combining the core features of Ethereum and the scaling benefits, Polygon presents a brilliant solution to make your dApps more scalable and powerful. With multiple Polygon chains living on Ethereum, our experts are constantly exploring the utility and implementation of Polygon with Ethereum.

Our Blockchain developers help you utilize full-stack interoperability solutions offered by Polygon. We provide development services for decentralized applications, Polygon wallets and customize interchain development for enhanced security, scalability, and interoperability of all your Blockchain projects. We also offer blockchain consultation services that can maximize your returns.

If you are looking for dApp development services or to integrate the benefits of Polygon and Ethereum implementations in your next business project, contact LeewayHertz.

Author’s Bio

Akash Takyar
Akash Takyar
CEO LeewayHertz
Akash Takyar is the founder and CEO of LeewayHertz. With a proven track record of conceptualizing and architecting 100+ user-centric and scalable solutions for startups and enterprises, he brings a deep understanding of both technical and user experience aspects.
Akash's ability to build enterprise-grade technology solutions has garnered the trust of over 30 Fortune 500 companies, including Siemens, 3M, P&G, and Hershey's. Akash is an early adopter of new technology, a passionate technology enthusiast, and an investor in AI and IoT startups.

Start a conversation by filling the form

Once you let us know your requirement, our technical expert will schedule a call and discuss your idea in detail post sign of an NDA.
All information will be kept confidential.

Insights

How to Develop a dApp on Algorand?

How to Develop a dApp on Algorand?

Algorand is a smart contract-oriented, decentralized network designed to solve the blockchain trilemma of achieving speed, security, and decentralization simultaneously.

read more

Follow Us