Back to homepage
#blockchain#polygon#dapps#web3#smart-contracts

Step-by-Step Tutorial - Developing and Deploying Decentralized Applications (dApps) on the Polygon Platform

7 min read

This tutorial provides a detailed guide for developing a decentralized application (dApp) on the Polygon platform. It covers setting up the environment with MetaMask, Truffle, and the Polygon Mumbai Testnet, writing and deploying a simple smart contract, and interacting with the deployed contract through a web interface. Essential tools like Truffle, HDWalletProvider, and web3.js are used, with a focus on security and best practices for managing sensitive data such as mnemonics.

Step-by-Step Tutorial - Developing and Deploying Decentralized Applications (dApps) on the Polygon Platform

This tutorial will guide you, step by step, through the process of developing your first dApp on the Polygon platform, the key to unlocking a whole new world of possibilities.

Required Tools

Let's gather our tools. Here's what we need:

  1. MetaMask: This is a crypto wallet that will allow us to interact with the Ethereum network.
  2. Truffle: It's a development environment, testing framework and asset pipeline for Ethereum.
  3. Polygon Mumbai Testnet: We will use this for testing our dApp.

For this tutorial, I am assuming that you have a basic understanding of JavaScript, Solidity, Ethereum, and blockchain technology.

Step 1: Setting Up the Environment

First things first, let's install Truffle:

bash
1npm install -g truffle

With Truffle in place, let's configure MetaMask to use the Polygon Mumbai Testnet. Follow these instructions from the official Polygon documentation to do so.

Great! You should see something like this when you open your Metamask:

MetaMask

Step 2: Configuring Truffle

Let's initialize Truffle in our project:

bash
1truffle init

The truffle init command creates a new Truffle project with the necessary configuration files and directories. Among these is the truffle-config.js file, which is essential for configuring Truffle's behavior.

Open the truffle-config.js file. You will see various configurations commented out. For now, we're interested in setting up our project to use the Polygon Mumbai Testnet.

Find the networks section in the configuration file and add the following configuration:

javascript
1networks: {
2 matic: {
3 provider: () => new HDWalletProvider(mnemonic, `https://rpc-mumbai.maticvigil.com`),
4 network_id: 80001,
5 gas: 8000000,
6 confirmations: 2,
7 timeoutBlocks: 200,
8 skipDryRun: true
9 },
10},

You'll need to replace mnemonic with your MetaMask wallet's mnemonic phrase.

Please note that your mnemonic phrase should be kept secret. Do not share it with anyone or publish it online. Also, in a real-world production setting, you would not hardcode the mnemonic phrase in the truffle-config.js file for security reasons. You might use environment variables or a secure secret management system.

Also, update your Truffle configuration to match the Solidity version we'll use:

javascript
1compilers: {
2 solc: {
3 version: "^0.8.0",
4 },
5},

Finally, you'll need to install HDWalletProvider, a Truffle package that allows us to connect to different Ethereum networks:

bash
1npm install @truffle/hdwallet-provider

At the top of your truffle-config.js file, require the HDWalletProvider:

javascript
1const HDWalletProvider = require("@truffle/hdwallet-provider");

With these configurations, you're now ready to compile and migrate your smart contracts using Truffle on the Polygon Mumbai Testnet.

Step 3: Writing a Smart Contract

Let's create a simple smart contract. This contract will just store and retrieve a string. In the root of your project directory, create a new file called HelloWorld.sol in the contracts directory and copy the following Solidity code into it:

solidity
1pragma solidity ^0.8.0;
2
3contract HelloWorld {
4 string public message;
5 function setMessage(string memory newMessage) public {
6 message = newMessage;
7 }
8 function getMessage() public view returns (string memory) {
9 return message;
10 }
11}

Step 4: Compiling the Smart Contract

Let's compile our smart contract using Truffle:

bash
1truffle compile

Step 5: Deploying the Smart Contract to the Polygon Mumbai Testnet

We create a migration script in the migrations directory:

javascript
1const HelloWorld = artifacts.require("HelloWorld");
2
3module.exports = function(deployer) {
4 deployer.deploy(HelloWorld);
5};

You should name the file with a number followed by a description. For example, if your contract's name is HelloWorld, you might create a new file named 2_deploy_hello_world.js for example. The number at the beginning indicates the order in which the migration should run.

And finally, deploy your contract:

bash
1truffle migrate --network matic
bash
1Compiling your contracts...
2===========================
3> Everything is up to date, there is nothing to compile.
4
5
6Starting migrations...
7======================
8> Network name: 'matic'
9> Network id: 80001
10> Block gas limit: 20235543 (0x134c517)
11
122_deploy_hello_world.js
13=======================
14
15 Deploying 'HelloWorld'
16 ----------------------
17 > transaction hash: 0x4e5081f75cdc0082d61ad375b3636bf66a22fb88278f9a254b318d5ebffdbfc1
18 > Blocks: 2 Seconds: 4
19 > contract address: 0xe53F9E3671B631A61a26A6Cc54e46da781323311
20 > block number: 37673287
21 > block timestamp: 1688762067
22 > account: 0xeAE0666664347AdaE0Bd3a107713D11a610B3f10
23 > balance: 0.136666589580666176
24 > gas used: 333364 (0x51634)
25 > gas price: 2.500000016 gwei
26 > value sent: 0 ETH
27 > total cost: 0.000833410005333824 ETH
28
29 Pausing for 2 confirmations...
30
31 -------------------------------
32 > confirmation number: 2 (block: 37673289)
33 > Saving artifacts
34 -------------------------------------
35 > Total cost: 0.000833410005333824 ETH
36
37Summary
38=======
39> Total deployments: 1
40> Final cost: 0.000833410005333824 ETH

Our Smart Contract is deployed to the Polygon Mumbai Testnet:

Polygon Mumbai Testnet

https://mumbai.polygonscan.com/address/0xe53F9E3671B631A61a26A6Cc54e46da781323311

Step 6: Interacting with the Smart Contract

First, let's create a basic HTML file called index.html in the root of your project directory:

html
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>HelloWorld dApp</title>
7</head>
8<body>
9 <h1>HelloWorld dApp</h1>
10 <input id="message-input" type="text" placeholder="Type a message...">
11 <button id="message-button">Set Message</button>
12 <div id="message-output"></div>
13
14 <!-- Include web3.js -->
15 <script src="https://cdnjs.cloudflare.com/ajax/libs/web3/1.2.9/web3.min.js"></script>
16 <!-- Include our JavaScript file -->
17 <script src="app.js"></script>
18</body>
19</html>

Next, we create a JavaScript file called app.js:

javascript
1// replace with your contract's ABI (can be found in the JSON file in the build/contracts directory)
2const contractABI = [...];
3
4// replace with your contract's deployed address
5const contractAddress = '...';
6
7const web3 = new Web3(window.ethereum);
8const helloWorldContract = new web3.eth.Contract(contractABI, contractAddress);
9
10window.ethereum.enable().then((accounts) => {
11 const account = accounts[0];
12
13 const messageButton = document.getElementById('message-button');
14 const messageOutput = document.getElementById('message-output');
15
16 // Display current message
17 helloWorldContract.methods.getMessage().call()
18 .then(result => {
19 messageOutput.innerText = result;
20 });
21
22 // Set new message
23 messageButton.addEventListener('click', () => {
24 const messageInput = document.getElementById('message-input');
25
26 helloWorldContract.methods.setMessage(messageInput.value)
27 .send({ from: account })
28 .on('transactionHash', () => {
29 messageOutput.innerText = messageInput.value;
30 });
31 });
32});

Please remember to replace the contractABI and contractAddress with your actual contract's ABI and the address where it was deployed. Also, ensure that MetaMask is installed in your browser, or else window.ethereum will be undefined.

You can now open the index.html file in your browser. Don't forget to connect your MetaMask to the Polygon Mumbai Testnet and the correct account.

After connecting, you can interact with your deployed HelloWorld contract by typing a new message and clicking the 'Set Message' button. You should see the message updated.

MetaMask confirmation

HelloWorld dApp

HelloWorld dApp

https://mumbai.polygonscan.com/tx/0x0d1bc5727a731aeb7bc9bcef4e2dc6d123e59d841a229d4c23257fad5c91c39e

Congratulations! You've now developed and interacted with your first decentralized application (dApp) on the Polygon platform, directly from your browser.

  1. Polygon Wiki— This is the official documentation by Polygon Network. It covers in detail the various aspects of the Polygon Network and its development tools.
  2. Truffle Suite — Truffle Suite's official website with extensive documentation and tutorials on using Truffle for Ethereum development.
  3. Remix Ethereum — This is an online compiler and Solidity IDE. It's a quick way to write, test, debug, and deploy smart contracts on Ethereum networks.
  4. OpenZeppelin — This library provides secure and community-audited smart contract components for Solidity.
  5. Web3.js — This is the Ethereum compatible JavaScript API which implements the Generic JSON RPC spec. It's used for interacting with Ethereum blockchain and smart contracts on it.
  6. Solidity Documentation — This is the official Solidity documentation, a great place to get a deep understanding of Solidity language.
  7. Etherscan — It allows you to explore the Ethereum and Polygon blockchains, transactions, addresses, and more.
  8. Hardhat — A development environment to compile, deploy, test, and debug your Ethereum software.
  9. Polygon Faucet — This is a faucet for the Polygon Mumbai Testnet. You can use it to request Matic tokens for testing your dApps on the test network.
  10. PolygonScan — This is the equivalent of Etherscan but for the Polygon Network. You can use it to explore transactions, addresses, blocks, and other activities happening on the Polygon Network.