How to build and deploy a smart contract on Polygon zkEVM?
Tags: polygonzkevm, technicalguide
Published: 2023-12-01 08:26:38

<p>Polygon zkEVM is a preferred choice for prominent dApps such as QuickSwap, Celer cBridge, and Coinstats because of its ability to offer a fully Ethereum-equivalent <a href="https://www.zeeve.io/blog/what-are-zero-knowledge-proofs-and-why-are-they-important-for-blockchain/">zero-knowledge ecosystem</a> for near-infinite scalability, reduced gas fees, and <a href="https://www.zeeve.io/blog/blockchain-interoperability-key-for-global-blockchain-adoption/">interoperability</a>. If you are planning to build your dApp on the <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">Polygon zkEVM ecosystem</a>, this article provides a step-by-step process for deploying a smart contract on the Polygon zkEVM.&nbsp;</p>
<h2 id="h-why-choose-polygon-zkevm-for-your-dapps">Why choose Polygon zkEVM for your dApps?</h2>
<p><a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">Polygon zkEVM</a> is a zero-knowledge based Layer-2 rollup scaling solution designed to offer massive scalability while maintaining enterprise-grade security, <a href="https://www.zeeve.io/blog/blockchain-interoperability-key-for-global-blockchain-adoption/">interoperability</a>, and quick finality for the decentralized applications running on its ecosystem. Powered by cryptographic zk-proofs, Polygon zkEVM computes all the transactions off-chain, produces validity proofs, and publishes them on the mainnet. With this innovative approach, <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">Polygon zkEVm</a> allows dApps to maintain EVM-equivalency, inherit security from the underlying Layer-1, and leverage ZKP-powered scalability.&nbsp;</p>
<figure class="wp-block-image aligncenter size-large"><a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/"><img src="https://www.zeeve.io/wp-content/uploads/2023/11/Blog-Banner-1-1-1024x130.png" alt="" class="wp-image-49913"/></a></figure>
<p>Learn&nbsp; more on: <a href="https://www.zeeve.io/blog/how-polygon-zkevm-is-becoming-a-game-changer-for-decentralized-applications/">How Polygon zkEVM is becoming a game changer for decentralized applications?</a></p>
<h2 id="h-building-and-deploying-smart-contract-on-polygon-zkevm">Building and deploying smart contract on Polygon zkEVM&nbsp;</h2>
<p>There are multiple ways to deploy a smart contract on the Polygon zkEVM ecosystem. For example, you can deploy using <a href="https://wiki.polygon.technology/docs/zkevm/guides/using-hardhat/" rel="nofollow">Hardhat</a>, <a href="https://wiki.polygon.technology/docs/zkevm/guides/using-foundry/" rel="nofollow">Foundry</a>, and Remix. For this guide, let’s consider Remix IDE-based deployment.</p>
<h3 id="h-prerequisites">Prerequisites</h3>
<p><strong>System requirements:&nbsp;</strong></p>
<p>RAM: Minimum- 32 GB, recommended- 64GB.<br>CPU: Minimum- 8-core, recommended- 16-core.<br>Storage: at least- Minimum 2.5TB SSD, recommended 5TB SSD<br>Recommended bandwidth- 1Gbit/s</p>
<p><strong>Node-</strong> zkEVM full node.</p>
<p><strong>Wallets</strong>- Any <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">Polygon zkEVM</a>-compatible wallet like Metamask or Coinbase wallet.&nbsp;</p>
<p><strong>Tools-</strong> Remix.IDE for development, testing, debugging, and deployment of Polygon zkEVM smart contract. <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">Polygon zkEVM</a> block explorer for checking the transactions.</p>
<p>Assuming that you have all the prerequisites, let’s start the deployment process.&nbsp;</p>
<p>Note that these steps represent Polygon zkEVM testnet deployment. You can follow exactly the same steps for deploying smart contracts on Polygon zkEVM Mainnet..&nbsp;</p>
<h3 id="h-step-1-configuring-the-polygon-zkevm-network">Step:1 Configuring the Polygon zkEVM Network</h3>
<p>To deploy your dApp on Polygon zkEVM, you first need access to the network. To do this, you need a RPC endpoint, which you can either deploy through the traditional programming-based process or the no-code way.&nbsp;<br><a href="https://www.zeeve.io/">Zeeve</a> allows you to <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">deploy Polygon zkEVM node via low-code</a>, do-it-yourself method within a few clicks. Plus, the node infrastructure at Zeeve is highly optimized for load balancing, 10x faster response time, rapid synchronization, and 99.95% uptime.</p>
<p>Once your node is deployed, you will get a public RPC url and chain ID. Add all these details to your Metamask wallet, including the testnet explorer url; <a href="https://testnet-zkevm.polygonscan.com">https://testnet-zkevm.polygonscan.com</a>.&nbsp;</p>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/azk486dzhl8vutydzg3h.png)
<p>Click on Save to add <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">Polygon zkEVM Network</a> to your wallet’s network list. Reload the page and navigate to the ‘Select a network’ option from the wallet. A drop-down menu with all the added networks will appear. Select Polygon zkEVM testnet and switch to the network.&nbsp;</p>
<h3 id="h-step-2-funding-your-metamask-wallet-with-test-tokens">Step:2 Funding your Metamask wallet with test tokens&nbsp;</h3>
<p>Now that you have configured the Polygon zkEVM network is configured, it’s time to fund your wallet with some test tokens. These tokens will be used to pay <a href="https://www.zeeve.io/blog/how-to-deploy-a-smart-contract-with-brownie/">smart contract</a> transaction fees during the deployment process. Before you request tokens, ensure that you are a member of <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-blockchain/">Polygon</a> discord server, because it needs authentication. Now, to get test tokens, navigate to the <a href="https://faucet.polygon.technology/">Polygon zkETH Faucet</a>, select Polygon zkEVM as network, select token-type, and add wallet address.</p>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xetf8hirc422anj9lbyx.png)
<p>Click on ‘Submit’. The faucet will now ask you to confirm the details once again. After that, ETH will be transferred to your wallet within 5 minutes. If you want, you can check the <a href="https://testnet-zkevm.polygonscan.com/tx/0xa4eddaacfc3dc530c7dd4fbe1854f122c0d249af775b3a964cb76e96a87296a7">transaction details on the explorer</a>.&nbsp;</p>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4np5ldh7b25qyeu4fpi8.png)
<h3 id="h-step-3-building-the-smart-contract">Step:3 Building the Smart contract&nbsp;</h3>
<p>The next step is to create the <a href="https://www.zeeve.io/blog/how-to-deploy-a-smart-contract-with-brownie/">smart contract</a>. For this guide, let’s build a card game-related contract similar to the popular game like Blackjack or 21. Here, the player’s objective is to obtain a hand of cards with total value close to 21 without overcalling.<br>The key functions of our smart contract code include:</p>
<li>CardValue Struct: Defines properties of a playing card, such as its symbol (suit), card (rank), and weightage (numerical value).</li>
<li>Mapping and Arrays: The contract has a mapping– ‘deck’ that associates each card index with its CardValue. Plus, it includes arrays for the card ranks, their associated weightage values, and the card suits.</li>
<li>Card Deck Initialization: The contract initializes the deck of cards by iterating across the card rank’s arrays and suits, creating a deck of 52 cards with their weightage values.</li>
<li>pickCardFromDeck Function: This function generates a random card index based on a combination of the caller's address and the current block's timestamp. Hence, it returns a random card index between 0 and 51.</li>
<li>hit Function: This function represents a player drawing a card from the deck. It uses the pickCardFromDeck function to select a random card, adds it to the player's hand array, and logs the drawn card's rank and suit. Plus, this function also determines the current total value of the player's hand and logs whether the player has won (reached 21), lost (exceeded 21), or should continue the game.</li>
<li>readHandValue Function: This function calculates and returns the total weightage of the player's hand by determining the weightage values of the cards in their hand. It also logs the total weightage in the hand.</li>
<p>The below <a href="https://www.zeeve.io/blog/how-to-deploy-a-smart-contract-with-brownie/">smart contract</a> is just an example. You can write your own dApp-specific smart contract, such as for DeFi app, crypto gaming app, bridges, wallet, etc, and deploy it to the <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">Poygon zkEVM</a> using these same methods, just the contract code will change.</p>
<pre class="wp-block-code has-background" style="background-color:#f7f7f7;font-size:16px"><code>// SPDX-License-Identifier: GPL-3.0
pragma solidity &gt;=0.7.0 &lt;0.9.0;

import "hardhat/console.sol";

contract Casino {

    struct CardValue {
        string symbol;
        string card;
        uint8 weightage;
    }

    mapping (uint =&gt; CardValue) deck;

    string&#91;] cards = &#91;"ace", "king", "queen", "jack", "10", "9", "8", "7", "6", "5", "4", "3", "2"];
    uint8&#91;13] weightage = &#91;10, 10, 10, 10, 10, 9, 8, 7, 6, 5, 4, 3, 2];
    string&#91;] suits = &#91;"spades", "hearts", "diamonds", "clubs"];

    CardValue&#91;] hand;

    constructor() {
        uint16 DeckIndex=0;
        for (uint16 cardIndex = 0; cardIndex &lt; cards.length; cardIndex++) 
        {
            for (uint16 suitIndex = 0; suitIndex &lt; suits.length; suitIndex++) 
            {
                deck&#91;DeckIndex] = CardValue(
                    {
                        symbol: suits&#91;suitIndex],
                        card: cards&#91;cardIndex],
                        weightage: weightage&#91;cardIndex]
                    }
                );
                DeckIndex++;
            }
        }
    }

    function pickCardFromDeck() internal view returns(uint) {
        uint randNo = 0;
        randNo = uint (keccak256(abi.encodePacked (msg.sender, block.timestamp)))%52;
        return randNo;
     }

    function hit() public {
        CardValue memory drawnCard = deck&#91;pickCardFromDeck()];
        hand.push(drawnCard);
        console.log("Your new card is -", drawnCard.card, "of", drawnCard.symbol);
        if (readHandValue() == 21) {
            console.log("You've won");
        } else if (readHandValue() &gt; 21) {
            console.log("You have lost");
        } else {
            console.log("Would you like to hit again?");
        }
    }

    function readHandValue() public view returns(uint16) {
        uint16 cardWeightage = 0;
        for (uint16 cardIndex = 0; cardIndex &lt; hand.length; cardIndex++) 
        {
            cardWeightage += hand&#91;cardIndex].weightage;
        }
        console.log("Total Weightage =", cardWeightage);

        return cardWeightage;
    }

}</code></pre>
<p>Open <a href="https://remix.ethereum.org/">Remix IDE</a>, click on WORKSPACES and then create a new workspace by clicking on +create option. Within this workspace, create a new file and let’s name it Newcardgame.sol.&nbsp;</p>
<p>Next, paste the above smart contract code into the file.</p>
<p>Note that the above code is not fully compiled. Therefore, let’s first compile this in Solidity. Paste the entire code into the Remix console, run the ‘Solidity Compiler’ (as you can see in the below image). You will see a green check mark, upon successful compilation.&nbsp;</p>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rbenpwqjd7xvcs2rcpnc.png)
<h3 id="h-step-4-deploying-the-smart-contract-on-polygon-zkevm">Step:4 Deploying the Smart contract on Polygon zkEVM</h3>
<p>Finally, let’s deploy the compiled Solidity smart contract on the <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">Polygon zkEVM</a> testnet. Navigate through the ‘Deploy &amp; Run Transactions’ tab on the Remix and add all the essential details such as Environment, Account address, Gas limit configuration, etc.</p>
<p>For our setup, we have added the following details:</p>
<li>Environment: Injected Provider- MetaMask.</li>
<li>Account address: 0x218d2Ab3152e29227d0CCc11764F9666f5d97faC.&nbsp;</li>
<li>Gas limit is set to default, 3M.&nbsp;</li>
<li>The contract name will appear automatically, which is ‘Casino-New card game. Sol’ in our case.&nbsp;</li>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/32xiepp3017gur1ipeiu.png)
<p>Click on ‘Deploy’ and confirm the transaction from your Metamask wallet. Once confirmed, the contract will be deployed in a few seconds. Also, as you can see in the below image, an output representing the successful smart contract transaction will appear at the bottom of the Remix console with a green check mark.</p>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q4ndhxwyrnzo5xtis85t.png)
<p>And, that’s done! Congratulations on successfully deploying the smart contract on Polygon zkEVM. For further verification of deployment, you can check the transactions on the <a href="https://explorer.public.zkevm-test.net/">Polygon zkEVM block explorer</a>.&nbsp;</p>
<h3 id="h-step-5-calling-functions-from-the-deployed-smart-contract">Step:5 Calling functions from the deployed smart contract&nbsp;</h3>
<p>Let’s test our Polygon zkEVM smart contract by calling some of its functions. For example, we are calling ‘hit’ and ‘readHandvalue’ functions listed at the bottom of the Remix.IDE console.&nbsp;</p>
<p>Click on <strong><em>hit</em> </strong>to call this function. It will draw additional cards and check if you win or lose. The result will appear in the console.&nbsp;</p>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fh4fmtp783g009xftchw.png)
<p>Similarly, click on <strong><em>readHandvalue</em></strong><em> </em>to call this function. This determines the game's outcome by checking the total weightage.&nbsp; If the hand value touches 21, it’s a win; if it exceeds 21, it’s a loss. Again, the results will appear in the console.&nbsp;</p>

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/68cqxud8qvue837qx5ay.png)
<p>As you can see, we just interacted with our Polygon zkEVM smart contract by calling some of its functions! You can call more functions, make changes in the code, or re-deploy this contract to offer more specific dApp functionalities.&nbsp;</p>
<h2 id="h-wrapping-up">Wrapping Up</h2>
<p>As discussed, you can build and deploy smart contracts on <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">Polygon zkEVM</a> for your project-specific dApps using these same steps. And, if you come across any challenges or you have any questions, feel free to connect with blockchain experts at <a href="https://www.zeeve.io/">Zeeve</a>. We are committed to simplifying your <a href="https://www.zeeve.io/blockchain-protocols/deploy-polygon-zkevm-node/">Polygon zkEVM-based deployment</a> with scalable nodes, secure RPC endpoints, ready plugins, multi-cloud support, and 24*7 resource monitoring. For more details about how <a href="https://www.zeeve.io/">Zeeve</a> is enabling seamless deployment of Polygon zkEVM dApps, drop us an email or <a href="https://www.zeeve.io/talk-to-an-expert/">schedule a one-to-one call</a> for a detailed discussion.&nbsp;</p>