How to Deploy a Polygon (Matic) Smart Contract Tutorial
Tags: polygon, solidity, blockchain, alchemy
Published: 2022-04-06 06:55:58

---
title: How to Deploy a Polygon (Matic) Smart Contract Tutorial
published: true
description: This is a step-by-step introductory tutorial that will teach you how to create and deploy a smart contract on Polygon Mumbai testnet + Matic Mainnet.
tags: polygon, solidity, blockchain, alchemy
//cover_image: https://direct_url_to_image.jpg
---

(originally published on the [Alchemy documentation hub](https://docs.alchemy.com/alchemy/tutorials/how-to-deploy-a-polygon-smart-contract))

HELLO!

If you are new to blockchain development and don’t know where to start, or if you've explored Ethereum mainnet a bit and found it wayyy toooo expensive.. this guide is for you :) 

We will walk through coding, deploying, and interacting a simple smart contract on the Polygon Mumbai test network using [Metamask](https://metamask.io/), [Solidity](https://docs.soliditylang.org/), [Hardhat](https://hardhat.org/), [Ethers.js](https://docs.ethers.io/v5/), and [Alchemy](	https://alchemy.com/?a=polygon-smart-contract). 

And don’t worry if you don’t understand what any of this means yet, I'll explain everything!

If you have questions at any point, here are some ways to debug:

1. Look for your question on [Ethereum StackExchange]() using the [polygon](https://ethereum.stackexchange.com/questions/tagged/polygon) tag or the [alchemy](https://ethereum.stackexchange.com/questions/tagged/alchemy) tag.
2. Reach out for help in the [Alchemy Discord](https://www.alchemy.com/discord)!
3. Tweet at us [@AlchemyPlatform](https://twitter.com/AlchemyPlatform) or [@thatguyintech](https://twitter.com/thatguyintech).

## Step 1. Initialize Your Project

First, we’ll need to create a folder for our project. Navigate to your command line and type:

```
mkdir polygon-smart-contract-tutorial
cd polygon-smart-contract-tutorial
```

Now that we’re inside our project folder, we’ll use `npm init --yes` to initialize the project. If you don’t already have `npm` installed, follow [these instructions](https://docs.alchemy.com/alchemy/guides/alchemy-for-macs#1-install-nodejs-and-npm) (we’ll also need Node.js so download that too!).

```
npm init --yes
```

You should see something like the following output based on your newly created project configuration `package.json`:

```json
Wrote to /Users/thatguyintech/Documents/co/polygon-smart-contract-tutorial/package.json:

{
  "name": "new",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
```

## Step 2. Download [Hardhat](https://hardhat.org/getting-started/#installation)

Hardhat is a development environment to compile, deploy, test, and debug your Ethereum software. It helps developers when building smart contracts and blockchain applications locally before deploying to a live chain.

Inside our `polygon-smart-contract-tutorial` project run:

```
npm install --save-dev hardhat
```

## Step 3. Create a Hardhat Project

Inside our `polygon-smart-contract-tutorial` project folder, run: 

```
npx hardhat
```

You should then see a welcome message and option to select what you want to do. Select `Create a basic sample project`:

![npx hardhat options](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cnenayr5r1xww2hfqv40.png)

And then just use all the default settings!

```
✔ What do you want to do? · Create a basic sample project
✔ Hardhat project root: · /Users/thatguyintech/Documents/co/new
✔ Do you want to install this sample project's dependencies with npm (@nomiclabs/hardhat-waffle ethereum-waffle chai @nomiclabs/hardhat-ethers ethers)? (Y/n) · y
```

Hardhat will then generate a `hardhat.config.js` file for us along with a couple of folders with sample code we can work with, including `contracts`, `scripts`, and `test`.

## Step 4. Review Your Smart Contract

In `contracts/Greeter.sol`, we can see our example smart contract. Let's review it to understand a bit about what's going on in Solidity code!

Here's the entire contract code:

```solidity
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "hardhat/console.sol";

contract Greeter {
    string private greeting;

    constructor(string memory _greeting) {
        console.log("Deploying a Greeter with greeting:", _greeting);
        greeting = _greeting;
    }

    function greet() public view returns (string memory) {
        return greeting;
    }

    function setGreeting(string memory _greeting) public {
        console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);
        greeting = _greeting;
    }
}
```

Let's break it down line by line :) 

```solidity
//SPDX-License-Identifier: Unlicense
```

The [SPDX License Identifier](https://www.linuxfoundation.org/blog/solving-license-compliance-at-the-source-adding-spdx-license-ids/) lets other engineers know what they are allowed to do with your code. "[Unlicense](https://unlicense.org/)" means that your code is free to use by public domain.

```solidity
pragma solidity ^0.8.0;
```

This line tells the solidity compiler which version it should use to compile your smart contract into byte code. `^0.8.0` means that any minor version from 0.8.0 and upwards is fair to use!

```solidity
contract Greeter {
  ...
}
```

Every smart contract is a collection of functions and data (its state). Once deployed, a contract resides at a specific address on the Ethereum blockchain. The `contract` syntax is very similar to working with classes or objects in other languages.

```solidity
string private greeting;
```

Here we define a state variable that the contract keeps track of, `greeting`. It is a string. Because it is marked with the  `private` modifier, only the contract itself has permissions to modify it. Although the data is still visible and public on the blockchain, other contracts and accounts will not be able to access or modify a private variable. 

This is useful in cases when you want to minimize access to your smart contract state. Otherwise you can use the `public` modifier.

```solidity
    constructor(string memory _greeting) {
        console.log("Deploying a Greeter with greeting:", _greeting);
        greeting = _greeting;
    }
```

Similar to many class-based object-oriented languages, a constructor is a special function that is only executed once, upon contract creation.

In our `Greeter` constructor, we expect a string `_greeting` to be passed in when the contract is deployed. We then log to hardhat console, and then write the `_greeting` string to the blockchain by setting it to the state variable `greeting`.

```solidity
    function greet() public view returns (string memory) {
        return greeting;
    }
```

Now we have our first smart contract function, `greet`. 

This is a read-only function that does not cost any gas to execute because it doesn't change any blockchain state. It requires no input arguments either, and simply returns whatever the contract has saved in the private `greeting` variable.

```solidity
    function setGreeting(string memory _greeting) public {
        console.log("Changing greeting from '%s' to '%s'", greeting, _greeting);
        greeting = _greeting;
    }
```

`setGreeting` is a write function that will cost gas for users to execute because it modifies the `greeting` variable stored on the blockchain. Similar to the logic in the constructor, it takes in one string input and uses that to update the smart contract state variable.

---

Now that we understand some basics on how Solidity code works, let's finish setting up some accounts and configurations to prepare for deployment to the Polygon blockchain!

## Step 5. Connect to the Polygon blockchain network with Alchemy

There are many ways to make requests to the Polygon chain. For simplicity, we’ll use a free account on Alchemy, a blockchain developer platform and API that allows us to communicate with the Polygon chain without having to run our own nodes. The platform also has developer tools for monitoring and analytics that we’ll take advantage of in this tutorial to understand what’s going on under the hood during our smart contract deployment. If you don’t already have an Alchemy account, you can [sign up for free here](https://alchemy.com/?a=polygon-smart-contract).

Once you’ve created an Alchemy account, generate an API key by creating an app. This will allow us to make requests to the Mumbai test network. If you’re not familiar with testnets, check out [this guide](https://docs.alchemy.com/alchemy/guides/choosing-a-network#polygon).

Navigate to the “Create App” page in your Alchemy Dashboard by hovering over “Apps” in the nav bar and clicking “Create App”.

![Create Alchemy App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/epfyf0t7q064wgjngapm.png)

Name your app “Polygon Smart Contract”, offer a short description, select “Staging” for the Environment (used for your app bookkeeping), select “Polygon” for the chain, and "Polygon Mumbai" for the network.

![App Settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ltqsmi21y1c71qe2pifp.png)

Click “Create app” and that’s it! Your app should appear in your apps table.

By clicking on the "View Key" link to the right of the the table row for your app, you will be able to find the HTTP RPC URL you can use to access a Polygon Mumbai Testnet node using Alchemy.

![View API Key](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7cn65ewkj2b19valuvjh.png)

You can see in our example that our HTTP URL is:

`https://polygon-mumbai.g.alchemy.com/v2/Ed7AeuPuIgo6fNDi49TDy_x4UBymLBsJ`

DO NOT SHARE THIS WITH ANYONE! This is your access to your node. If you share it, then others will be able to freely use up your app's resources and then you'll be sad.

Copy this down for later, we will use this in our MetaMask configuration, as well as in our hardhat configuration file to deploy the smart contract.

## Step 6. Create an Ethereum account!

Now we need an Ethereum account to send and receive transactions.

For this tutorial, we’ll use MetaMask, a virtual wallet in the browser used to manage your Ethereum account address.

You can download and create a MetaMask account for free [here](https://metamask.io/).

## Step 7. Switch to the Polygon Mumbai test network

After you create your MetaMask account, make sure to switch over to the “Mumbai Test Network”.

MetaMask doesn't come with the Mumbai Test Network by default, so you will need to make some changes to create the connection.

![Example MetaMask Mumbai Network](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1x3gtdxqq2d1qkca4x03.png)

You can do this by clicking on your MetaMask profile icon and going down to settings.

![Settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1kmzumcr4oarrkybsuls.png)

Then click on "Networks" and then the "Add network" button.

![Networks](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1u1uqp88w4k6l4fooit1.png)
![Add Network](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qi2k7bwt5je9jfd890p4.png)


Input the following settings:

- Network Name: Polygon Mumbai
- New RPC URL: <your rpc url from Step 3>
- Chain ID: 80001
- Currency Symbol: MATIC
- Block Explorer URL
- https://mumbai.polygonscan.com

![Polygon Mumbai network settings](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wch6qk2dwm71e4769yfh.png)

After you confirm the settings, MetaMask should automatically be connected to the new Polygon Mumbai test network.

## Step 8. Get some free test ETH from a faucet

Go to https://mumbaifaucet.com/ and input your wallet address (ethereum account address) from MetaMask.

You can get your wallet address by opening MetaMask and copying the long string that goes `0x...` at the top.

![Copy Wallet Address](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/inoed8l2jrx5et5ohz75.png)

Once you input your wallet address into the faucet input box and click "Send Me MATIC", you will see a new transaction link show up. That links you to the polygonscan page where you can view a receipt of the faucet transaction. Here is an [example](https://mumbai.polygonscan.com/tx/0x9c20ebc97f9569ce66826d3e9956a750de867b38585ee24111519abd15167740).

![Completed faucet request](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/h0t35jom5i40fkpm4mbh.png)

Good stuff! Now that you have some "money", we can actually go back to our contract and deploy it!

## Step 9. Connect MetaMask and Alchemy to your project.

We’ve created a MetaMask wallet, Alchemy account, and written our smart contract, now it’s time to connect the three.

Every transaction sent from your virtual wallet requires a signature using your unique private key. To provide our program with this permission, we can safely store our private key (and Alchemy API key) in an environment file.

First, install the [dotenv](https://www.npmjs.com/package/dotenv) package in your project directory:

```bash
npm install dotenv --save
```

Then, create a `.env` file in the root directory of our project, and add your MetaMask private key and HTTP Alchemy API URL to it.

NOTE: Your environment file must be named `.env` or it won't be recognized as an environment file. Do not name it `process.env` or `.env-custom` or anything else.

- Follow [these instructions](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key) to export your private key
- Review the end of Step 5 to get your HTTP Alchemy API URL

So at this point, your `.env` file should look like this:

```
API_URL = "https://polygon-mumbai.g.alchemy.com/v2/<your-api-key>"
PRIVATE_KEY = "your-metamask-private-key"
```

Now let's make sure these environment variables are correctly loaded in our hardhat project.

We'll use the `dotenv` module inside our `hardhat.config.js` file to do so.

## Step 13: Update hardhat.config.js

We’ve added several dependencies and plugins so far, now we need to update hardhat.config.js so that our project knows about all of them.

Update your `hardhat.config.js` to look like this:

```javascript
require("@nomiclabs/hardhat-waffle");
require("dotenv").config();

const { API_URL, PRIVATE_KEY } = process.env;

// This is a sample Hardhat task. To learn how to create your own go to
// https://hardhat.org/guides/create-task.html
task("accounts", "Prints the list of accounts", async (taskArgs, hre) => {
  const accounts = await hre.ethers.getSigners();

  for (const account of accounts) {
    console.log(account.address);
  }
});

// You need to export an object to set up your config
// Go to https://hardhat.org/config/ to learn more

/**
 * @type import('hardhat/config').HardhatUserConfig
 */
module.exports = {
  solidity: "0.8.4",
  networks: {
    mumbai: {
      url: API_URL,
      accounts: [`0x${PRIVATE_KEY}`]
    }
  }
};
```

Note that with `dotenv`, we can access variables defined in our `.env` file by using `process.env`.

Inside the [hardhat config], we define a new network called `mumbai` that uses the Alchemy HTTP URL and our MetaMask account to talk to the blockchain.

## Step 14: Compile our contract

To make sure everything is working so far, let’s compile our contract. The `compile` task is one of the built-in hardhat tasks.

From the command line run:

```
npx hardhat compile
```

If all goes well, you should see something like this output in your terminal:

```
thatguyintech@albert new % npx hardhat compile
Compiled 1 Solidity file successfully
```

If you have any issues, please check previous discsussions on  [Ethereum Stackexchange](https://ethereum.stackexchange.com/) using the "Alchemy" and "Polygon" tags, or create your own question!

And if you'd like to chat with others who may have expertise, join the Alchemy Discord: https://alchemy.com/discord

## Step 15: Deploy our contract

We’re finally ready to deploy our smart contract! Navigate to the command line and run:

```bash
npx hardhat run scripts/sample-script.js --network mumbai
```

You should then see output similar to this (with different address string):

```bash
Greeter deployed to: 0x8Fab93D28e52a93d4b00E25Eaa04B64223382f89
```

You can now paste this contract address into https://mumbai.polygonscan.com/ and find details about your deployed contract.

For example, you can see when the contract was deployed, how much the transaction fee cost, and which wallet address was responsible for the deployment.

![Mumbai Polygonscan Example](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gf90snj91w6z5umqofpy.png)

Congrats! You just deployed a smart contract to the Polygon sidechain 🎉

To understand what’s going on under the hood, let’s navigate to the Explorer tab in our [Alchemy dashboard](https://dashboard.alchemyapi.io/explorer). If you have multiple Alchemy apps, make sure to filter by app and select "Polygon Smart Contract".

![Alchemy Explorer](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m0hlw0183udmwiyw5sqr.png)

Here you’ll see a handful of JSON-RPC calls that Hardhat/Ethers made under the hood for us when we called the `.deploy()` function. Two important ones to call out here are [eth_sendRawTransaction](https://docs.alchemy.com/alchemy/apis/ethereum/eth_sendrawtransaction), which is the request to actually write our contract onto the Polygon chain, and [eth_getTransactionByHash](https://docs.alchemy.com/alchemy/apis/ethereum/eth_gettransactionbyhash) which is a request to read information about our transaction given the hash (a typical pattern when sending transactions).

That's all for now! You've learned a little bit about Solidity, set up some key accounts and tooling for building smart contracts, and then deployed your first smart contract to Polygon! You're well on your way to becoming a blockchain developer :) 

If you enjoyed this tutorial, give us a tweet [@AlchemyPlatform](https://twitter.com/AlchemyPlatform)!