How Does Polygon Help Ethereum Scale?

How Does Polygon Help Ethereum Scale?

Introduction

Since its inception in 2014, Ethereum has established itself as the de facto leader of blockchain platforms capable of supporting turing-complete smart contracts.

Ethereum has been instrumental in bringing about a revolution that we now know as web3. The largest decentralized exchange, NFT marketplace, and yield farming protocol all reside on Ethereum. The chain is responsible for handling billions of dollars worth of value, and it has opened up avenues for creators and investors that were previously unfathomable.

Although Ethereum dapps have enjoyed an immense amount of popularity amongst their users, they are nowhere close to achieving mass adoption. The sum of people who have used dapps still number only in the few millions. One of the biggest reasons for this is the scaling handicaps endemic to the chain. It becomes unusable very quickly for everyone barring a few high net-worth users.

Fortunately, there have been serious efforts made by the community to help Ethereum scale. By far, the most popular scaling solution available in the market today is the Polygon POS (Proof of Stake) sidechain. In this article, we are going to explore what Polygon is and how it overcomes Ethereum’s drawbacks. Finally, we will make a side-by-side comparison of both chains’ performances by creating an NFT-minting smart contract.

The Problem with Ethereum

Ethereum, despite its market leader position, suffers from a host of problems:

  1. Low Transaction Throughput: Ethereum can handle only 15 transactions per second. Compared to solutions like Visa or Mastercard, which handle over 25,000 transactions per second, this figure is scant.
  2. High Gas Fees: When a chain can handle few transactions, it must increase processing costs when the transaction volumes are high. Ethereum is notorious for its high gas fees. For instance, not long ago, it reached almost 7000 Gwei during a popular NFT mint (called Otherside). During this period, it would’ve cost you in excess of $500 to perform even the most basic transaction.
  3. Slow Transaction Finality: Ethereum adds a block to its chain approximately once every 15 seconds. Since there are multiple miners competing to mine blocks at the same time, a block cannot be considered final until at least 4-5 blocks have been added on top of it. In essence, it takes more than a minute for a transaction to be considered final. With applications like games and financial tools, such a slow transaction finality is simply not acceptable.

The Solution

In order to achieve mass adoption and acceptance, it is imperative that a solution be developed on top of Ethereum that addresses its most glaring problems. In essence, we need a solution that has the following features:

  1. Low-cost: Even the most computationally intensive transactions shouldn’t cost more than a few cents.
  2. Fast: Transactions are confirmed almost instantly.
  3. EVM Compatible: Developers don’t need to learn new tooling or languages in order to build on the solution.
  4. Interoperable with Ethereum: Easy to deposit and withdraw funds to and from Ethereum and the solution.
  5. Engaged community: A community that is committed to improving the solution over time as well as building user-friendly dapps on top of it.
  6. Sustainable: Any solution looking to reach mass adoption must also be environmentally conscious.

Ethereum core developers are working on Layer 1 scaling fixes, such as sharding, but these solutions are nowhere near completion. We need solutions available today that are easy for anyone to get started on.

Introducing Polygon

The creators of Polygon designed a chain with all the aforementioned features in mind. Since its inception in 2017, the Polygon chain has gone on to become one of the most popular Ethereum scaling solutions.

Technically speaking, Polygon is an Ethereum sidechain. A sidechain is an independent blockchain that is connected to Ethereum via a bridge. Unlike L2s, sidechains do not inherit the security features of the main Ethereum chain. Instead, they implement their own consensus protocols and block parameters. As a result, sidechains aren’t required to post state changes and transaction data to Ethereum (whereas L2s are).

The greater independence of sidechains from Ethereum makes Polygon slightly more centralized but also enables it to achieve extraordinarily high levels of throughput.

The following are the improvements that Polygon has been able to achieve over Ethereum:

  1. High transaction speeds: Polygon is capable of handling up to 65,000 tx/second, comparable to the scale of its centralized rivals.
  2. Low transaction costs: Even the heaviest transactions on Polygon cost only a few cents. In most cases, a 10,000x reduction in cost can be observed vis-à-vis Ethereum.
  3. Instant transaction finality: Polygon’s consensus protocol guarantees that transactions are confirmed almost instantly (less than 2 seconds).
  4. EVM compatible: Polygon is built on the same software as Ethereum. Therefore, Ethereum developers can build on Polygon using the exact same tools.
  5. Strong community: The Polygon team has spent millions of dollars to build a robust community of builders, investors, and users. It is already home to some of the most popular dapps on Ethereum with better UX and much cheaper costs.
  6. Low energy consumption: Polygon uses the Proof-of-Stake protocol, which consumes 99.9% less energy than its PoW counterpart. In fact, Polygon has committed to being carbon negative by the end of 2022, making it one of the largest environment-friendly blockchains in the market today.

A Note on Polygon PoS Security

Unlike other sidechains, Polygon PoS does have a method in which it is able to inherit the security of Ethereum. The Polygon PoS chain utilizes the Plasma Bridge in order to maintain and guarantee a high level of security. Plasma has a unique exit mechanism, basically a set of smart contracts to help move assets and checkpoints for verification, which enables Polygon PoS to leverage Ethereum’s security.

The only drawback here is withdrawals from Polygon to Ethereum through the Plasma Bridge must go through a 7-day withdrawal period. Quicker withdrawals (within 30 minutes to 3 hours) are possible with the PoS Bridge, however, this method is not as secure as using the Plasma Bridge.

Both these bridges are still secure and safe to use, and in most cases should suit a user’s needs just fine. However, if your project requires state-of-the-art security, it is prudent to consider using Polygon L2 solutions such as Zero, Nightfall, and Hermez.

Comparison in Action

Now that we've seen the advantages that Polygon PoS has over Ethereum for certain projects, let's analyze deployment to both chains.

In the following sections of this article, we will create a simple NFT contract and deploy it to Polygon Mumbai and Ethereum Goerli testnets. We will observe how the development process for both chains is nearly identical.

Next, we will analyze NFT contracts that have been deployed previously (by other teams) on Ethereum and Polygon mainnets, and then compare cost and confirmation times.

Overview of the NFT Project

The project that we're going to create is extremely simple. We want to write and deploy an ERC-721 contract that mints a single NFT to the blockchain of our choice.

The first step in such projects is to create the NFT art, its associated metadata, and upload it to IPFS. For this tutorial, we have already done this for you.

You can check out the image uploaded to IPFS here and the associated NFT metadata here.

In case you're interested in learning more about NFT metadata, IPFS, and Pinata, check out this article here.

Creating the NFT Contract

Step 1: Install the MetaMask Extension

In case you haven't already, install the MetaMask extension for your browser. Once installed, MetaMask will guide you through creating your first wallet.

Step 2: Add Goerli and Mumbai Chains to MetaMask

By default, MetaMask comes with the Ethereum mainnet and the Goerli testnet configured. To add the Polygon mainnet and the Mumbai testnet chains, follow the instructions in this document.

Step 3: Get GoerliETH and Mumbai MATIC from a Faucet

Head over to Alchemy's Goerli faucet page and request some free GoerliETH. You may be required to create a free Alchemy account for this.

If all goes well, you should have 0.05 GoerliETH in your wallet when you switch to the Goerli test network.

In the same vein, acquire some free Mumbai MATIC from Polygon's official faucet. If successful, switching to the Mumbai chain should tell you that you have a balance of 0.2 MATIC.

Step 4: Install NPM and Node

We will build our project using JavaScript and node. In case you don't have node and npm installed on your local machine, you can do so here.

You can ensure that everything is working properly by checking the version number of node on your terminal.

$ node -v

Step 5: Create a Node Project and Install Dependencies

Let's set up an empty project repository by running the following commands:

$ mkdir nft-contract && cd nft-contract
$ npm init -y

We will be using Hardhat, an industry-standard Ethereum development environment, to build and deploy our smart contract. Install Hardhat by running:

$ npm install --save-dev hardhat

We can now create a sample Hardhat project by running the following command and choosing Create a basic sample project.

$ npx hardhat

Agree to all the defaults (project root, adding a .gitignore, and installing all sample project dependencies).

To check if everything works properly, run:

$ npx hardhat test

We now have our Hardhat development environment successfully configured. Let us next install the OpenZeppelin contracts package. This will give us access to ERC-721 implementations (the standard for NFTs), on top of which we will build our contract.

$ npm install @openzeppelin/contracts

Step 6: Writing the Smart Contract

Open the repository in your favorite code editor (e.g. VS Code). In the contracts folder, create a new file called NFTContract.sol.

We are going to create a very simple ERC-721 contract that mints a single NFT when deployed (i.e. within the constructor). Add the following code to the file:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

contract NFTContract is ERC721URIStorage {

    constructor() ERC721("Panda NFT", "PNFT") {

        // Mint NFT
        _mint(msg.sender, 0);

        // Set metadata
        _setTokenURI(0, "ipfs://QmUyZoK21qb8YknXGfDB34RTY8vMqPb6Bsj9U9iLEnyrZR");

    }
}

Step 7: Deploy the Contract Locally

Let's now write a script to deploy and test the contract locally. In the scripts folder, create a new file called run.js and add the following code:

const hre = require("hardhat");

async function main() {

  const contractFactory = await hre.ethers.getContractFactory("NFTContract");
  const contract = await contractFactory.deploy();

  await contract.deployed();

  console.log("Contract deployed to:", contract.address);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
});

Now run the following command on your terminal:

$ npx hardhat run scripts/run.js

Step 8: Deploy the Contract to Goerli

In order to deploy the contract to Goerli, we have to add the network to the hardhat.config.js file. Replace the module.exports object at the end of the file with the following:

module.exports = {
  solidity: "0.8.4",
  networks: {
    goerli: {
      url: "https://ethereum-goerli-rpc.allthatnode.com/",
      accounts: ["<-- WALLET PRIVATE KEY -->"]
    }
  }
};

Replace the placeholder with your MetaMask wallet's private key. (This can be found in Account Details.) Take care to never share this key or file publicly.

To deploy to the Goerli testnet, run the following command:

npx hardhat run scripts/run.js --network goerli

If all goes well, your terminal will display the address of the deployed contract on the Goerli network. Head over to https://goerli.etherscan.io and search for your contract address to view your contract.

You can find the contract that we deployed here.

Step 9: Deploy the Contract to Mumbai

Let's now deploy our contract to the Polygon Mumbai network. The best part of this step is that we have to change absolutely nothing in our contract or the run script. The only thing we need to add is the mumbai network to hardhat.config.js.

module.exports = {
  solidity: "0.8.4",
  networks: {
    goerli: {
      url: "https://ethereum-goerli-rpc.allthatnode.com/",
      accounts: ["<-- WALLET PRIVATE KEY -->"]
    },
    mumbai: {
      url: "https://rpc-mumbai.maticvigil.com",
      accounts: ["<-- WALLET PRIVATE KEY -->"]
    }
  }
};

Deploy to Mumbai by running:

npx hardhat run scripts/run.js --network mumbai

You can search for your contract address at https://mumbai.polygonscan.com. You can find our contract here.

You can also search for your Goerli and Mumbai NFTs on OpenSea Testnets. For example, here is the NFT we minted on the Mumbai network.

Comparing Cost and Time

By now, it should be abundantly clear that developing for Ethereum and the Polygon sidechain is nearly identical.

But what are the cost and time implications?

We won't be able to answer these questions with the contracts we deployed since we were operating on testnets using fake money.

But not to worry. We have deployed these contracts to the Ethereum and Polygon mainnets on your behalf. Let’s take a look at the performance.

Ethereum

You can check out the deployed NFT contract on Ethereum here and the contract creation transaction here.

Despite the recent drops in Ethereum prices (in terms of USD) and average gas prices (in terms of gwei), you can see that contract deployment cost around 0.02 ETH or $40.

The time to confirm this Ethereum transaction was approximately 40 seconds.

Polygon

You can check out the deployed NFT contract on Polygon here and the contract creation transaction here.

Notice that we paid 0.06 MATIC when MATIC was trading at $0.94. Therefore, we paid $0.06 to deploy the contract.

The time to confirm this transaction was 6 seconds.

In essence, this contract was confirmed almost 7 times faster and with a cost reduction of 1000x!

Conclusion

Ethereum is easily the most important smart contract blockchain in existence. However, it faces huge obstacles when it comes to scale and transaction costs.

Hopefully, this article has made a strong case for why Polygon is an excellent panacea to Ethereum's scalability problems. By operating as a PoS sidechain, it significantly increases processing speeds and reduces costs.

For Ethereum developers, building on Polygon requires almost zero additional upskilling. Ethereum tools are compatible with both environments. To start building on Polygon, check out the documentation here.