Introduction
Polygon Network, which is (formally known as Matic Network) is a Layer2 scaling solution for Ethereum Network. It basically aims to address the scalability issue which is present in Ethereum Network by providing a framework to connect different sidechains to Ethereum's main chain. This Layer2 Polygon chain is becoming popular these days at a tremendous rate. Polygon offers high transaction throughput, low fees, and a fast confirmation process, making it an attractive choice for developers and users.
In this article, we will focus on connecting to the Polygon chain using our Polygon RPC URL in C# and making common functions to "retrieve the account balance of a user" and "send some MATIC from one user to another user". We focused on using the C# (.dot) NET framework for this due to some reasons like - Wide Developer Adoption, Interoperability, Smart Contract Support, and Security and Performance.
Connect with Polygon Network
This Blockchain has two networks which are Polygon Mainnet and Polygon Testnet. As the name suggests, the Testnet is used by the developers for testing purposes, as it is not advisable to spend actual money every time we start developing and testing. Once the development is completed, the entire process is shifted to the mainnet, where actual money gets involved.
Before starting the connection process with Polygon Network using C#, we need a few things to set up first.
Connect with Alchemy
Connecting to Polygon or any other blockchain is not impossible, but to actually do so, we need to have our node API key, which will be needed to connect to the Network. To get the API key using Alchemy, follow the steps mentioned below -
Step 1. Sign up / Log In to Alchemy
We need to have our Alchemy account; if you already have an account, then congratulation; you can go and Log In to your account by clicking here. If you are new and haven't heard about Alchemy, no worries. Just sign up for Alchemy through- here. Fill out the form, then Log In to the account. After login, the page should look like this,
Step 2. Create New App on Alchemy
After getting Logged In, we need to create a new app; in the above picture, where we have our ID logged In, you can find a button called Create App, press that, and then a pop-up would appear.
Here, we need to provide a unique name to the app; you can provide any name you like; after that, we need to select the chain with which we will connect, and after selecting the chain, we need to select the Network we would be using.
Here, we are connecting to the "Polygon" chain, and the Network we'll be using is the Polygon Mumbai Testnet. After selecting the Network and the chain, press the "Create App" button.
After we create a new app, it will be shown in our Alchemy dashboard
Connect with Metamask
To connect with any blockchain, we need an account that consists of the private key, public key, account address, and passphrase. Metamask is a crypto wallet and a gateway to blockchain apps. To sign transactions, we need to establish an account, here, we are setting up a Metamask wallet account. You can download the Metamask wallet extension from here. After downloading and installing, follow the steps below -
Step 1. Create Wallet Account using Metamask
After installing, follow the steps the wallet provides to set up a Metamask wallet. After creating the wallet, your wallet would have 0 ETH balance and would be connected to an Ethereum chain; now, we need to add a Polygon chain address and connect to the Polygon network.
Step 2. Add Polygon Testnet Network in Metamask wallet
To connect to the Polygon Network, click on the button where Network will be shown, in this case, the "Ethereum Mainnet" button, and then browse to the "Add Network" button and click it; this will open a window.
By clicking on the Add Network button, a window will open; at the bottom of the page, click on Add Network manually. This will allow us to add a network manually by using the RPC URL and chain ID.
Step 3. Add Polygon Testnet Network using RPC Url
Now Provide the information which is asked to add the Network. To add the Network, we need the RPC URL with our API key, which was created earlier when we were configuring with Alchemy. To get the API key, we need to Sign In to our Alchemy account, and after that, click on the view key on the dashboard to view the API key.
After getting the API key, get back to the step to add the Polygon Testnet network; fill in the below section and click on the "Save" button to add the Network.
- Network Name - "Polygon Mumbai Testnet"
- New RPC URL - https://polygon-mumbai.g.alchemy.com/v2/you_api_key
- Chain ID - 80001
- Currency Symbol - "MATIC"
After filling out this information, click the Save button to save the Network.
After adding the polygon network, we will get our Polygon Testnet ID which will be connected to the Polygon Mumbai Testnet chain. After adding our ID, the metamask wallet would look like this, where the address of the account is given at the top; we can copy the address of our account from the wallet by pressing the copy button.
Step 4. Getting MATIC for Polygon Testnet Account
Matic is the Fungible token currency that is being used in the Polygon Network(mainnet + testnet). To sign any transaction, we need to spend some MATIC tokens. After creating the wallet for the first time on Metamask and connecting to the polygon testnet chain, we receive, 0 MATIC tokens in the beginning, but we will be needing MATIC tokens to sign any transaction or to send tokens to others. Thus, when using the Polygon Mumbai Testnet, we can receive MATIC faucets, also referred to as fake MATIC tokens, for use. This is possible because Polygon Mumbai Testnet is for developers to use and test their dApps and code as to how efficiently their code is functioning on the Blockchain because the functioning of the Mumbai testnet and main MATIC mainnet are the same. Thus, allowing the use of faucets or fake tokens allows the developers to save the actual currency, which would have been used on the testnet chain for Testing if not for MATIC faucets.
Getting Matic for our Polygon account is easy. All we need is the account address, which we can simply copy from our Metamask wallet, as shown above.
After copying the account address, we need to visit some website that offers free faucets for testing, like Polygon Faucet, where we need to select our Network and paste our account address, and then click on the Submit button.
Press the Confirm button on the next page and wait for some time; the faucet will soon arrive; go to your metamask wallet and check. You will receive the faucet, which will be shown in your account.
With this, we have primarily set up everything needed to connect to the polygon using C#; now, we can start coding.
Connecting to Polygon chain using C#
C# (pronounced "C sharp") is a modern, general-purpose programming language developed by Microsoft. It was introduced in the early 2000s as part of the .NET framework and has since become one of the most popular programming languages for building various applications. C# provides a package named "Nethereum" which we can use to connect and communicate with Ethereum and Ethereum-based blockchains, such as Polygon. We are using C# to connect to the Polygon Blockchain due to various benefits like,
Benefits
-
Wide Developer Adoption: C# is a popular programming language with a large community of developers. It has been widely adopted for building various applications, including blockchain-based ones. This means plenty of resources, libraries, and frameworks are available to support C# developers in their blockchain development journey.
-
Interoperability: C# is designed to work seamlessly with the .NET framework, which provides a rich set of tools and libraries for application development. It allows you to integrate blockchain functionality into existing C# applications or develop new blockchain applications from scratch, leveraging the power of the .NET ecosystem.
-
Smart Contract Support: With the Nethereum library, which provides a C# implementation for interacting with Ethereum-based blockchains, you can easily interact with smart contracts deployed on the Polygon chain. This enables you to read data from smart contracts, write data to them, and execute functions defined within the smart contracts, all using C# code.
-
Security and Performance: C# is a statically typed language that emphasizes strong type-checking and compile-time verification. This can help reduce programming errors and enhance the security and reliability of your blockchain applications. Additionally, C# is known for its performance optimizations and efficient memory management, which can be beneficial when dealing with the complexities of blockchain transactions and data.
C# Polygon Implementation
To connect to the Polygon chain using C#, follow the steps outlined below,
Step 1. Set up a new C# Project
Open up your Visual Studio 2022 and click on Create a new Project to set up a new project using which we will be communicating with the Polygon Testnet.
Next, we need to select "Console App(.NET Framework)" in the next window and then click on the "Next" button.
.
Configure your project window will be opened; here, we need to provide a unique name for our project and click on the "Create" button; in this case, we are keeping the name Polygon_Chain_Implementaion; you can keep the same.
Step 2. Adding Required NuGet Packages
Click on Project >> Manage NuGet Packages to add new NewGet Packages required for the project.
Search for a package named Netherum.web3 and install that package to the current project.
Step 3. Connect to the Polygon Network
To connect to the polygon network, simply write the code inside the main class, using the RPC URL to connect to the chain. Retrieve your RPC URL API Key from Alchemy as demonstrated above; after that, connect to the chain using that URL and API key since we will be using Nethereum.Web3 package, so we need to include the library before coding.
using Nethereum.Web3;
namespace Polygon_Chain_Implementation
{
internal class Program
{
static async Task Main(string[] args)
{
try
{
string Api_key = "{RPC URL API KEY from Alchemy}";
string rpcUrl = $"https://polygon-mumbai.g.alchemy.com/v2/{Api_key}";
var web3 = new Web3(rpcUrl);
if (web3.Eth.ChainId.SendRequestAsync().Result.ToString() == "80001")
{
Console.WriteLine("Connected");
}
else
{
Console.WriteLine("Not Connected");
}
Console.ReadLine();
} catch
{
Console.WriteLine("Not Connected");
Console.ReadLine();
}
}
}
}
In the above code, we are connecting to the Polygon network and checking whether we are connected to the polygon chain with id 80001 or not. If we provide the above code with the correct RPC URL and API key, it will connect to the Polygon Network and print "Connected" in Console. Otherwise, it won't connect to the correct Network and print "Not Connected" in Console.
Step 4. Retreive Account Balance
To retrieve an account balance of an account, we need to have the account address we can get from the metamask wallet, as discussed above. After having the account address, you can just implement the code written below and call the function "GetAccountBalance()" and pass the instance of Web3 as a parameter to get the account balance.
static async Task GetAccountBalance(Web3 web3)
{
try
{
string accountAddress = "your_account_address";
var balance = await web3.Eth.GetBalance.SendRequestAsync(accountAddress);
var maticAmount = Web3.Convert.FromWei(balance.Value);
//Balance in Wei
Console.WriteLine($"Available balance of account address : {accountAddress} is : {balance} Wei ");
//Balance in Matic
Console.WriteLine($"Available balance of account address : {accountAddress} is : {maticAmount} Matic ");
}
catch(Exception ex)
{
Console.WriteLine(ex.Message );
}
}
We can call this function inside the if the condition of the main function where we are checking the connection,
if (web3.Eth.ChainId.SendRequestAsync().Result.ToString() == "80001")
{
Console.WriteLine("Connected");
GetAccountBalance(web3).Wait(); // calling GetAccountBalance from Main
}
The above method GetAccountBalance will return the account balance in Wei, which is the smallest unit to represent the amount in the Ethereum-based blockchain. So after getting the amount in Wei, we are converting the amount to MATIC and show the result to the Console. To do that, we are using a predefined function available in Web3 i.e. "Web3.Convert.FromWei()", this will return the amount to "Ether" or, in our case, "Matic"
Step 5. Send MATIC tokens from one user to another
To send MATIC from one account to another, we need the account address of the receiver and the private key of the sender. To obtain the private key of the sender i.e. in our case, we will use the Metamask wallet again. Open up your Matamask wallet now. To get on More options, click on the three dots at the top of the wallet page. Then browse to the Account Details button.
After clicking on "Account details" a window will pop up; click on Export private key to access your private key.
After clicking on the Export private key, a window will pop up asking for your Metamask password; provide your password to access your private key. Copy the private key.
Now we can start with the coding section; go to your visual studio code 2022; here, we will create a function named SendmaticTokens() to send Matic tokens.
But, to send Tokens, we need to connect to the wallet account. Thus we need to import another library,
using Nethereum.Web3.Accounts;
After Importing Netehereum.Web3.Accounts write down the code below to transfer MATIC tokens
static async Task SendMaticTokens()
{
try
{
string senderPrivateKey = "Your's / Matic Sender's Private Key";
string receiverAddress = "Receiver's Account Address";
string Api_key = "{RPC URL API KEY from Alchemy}";
string rpcUrl = $"https://polygon-mumbai.g.alchemy.com/v2/{Api_key}";
var account = new Account(senderPrivateKey); // Instance of sender's account using sender's private key
var Accountweb3 = new Web3(account, rpcUrl); // Connecting with the account and Polygon Testnet chain
var ammountToSend = (decimal)0.001; //{Ammount to be send in decimal in Matic }
var transaction = await Accountweb3.Eth.GetEtherTransferService().TransferEtherAndWaitForReceiptAsync(receiverAddress, ammountToSend);
Console.WriteLine($"\nTransaction Hash : {transaction.TransactionHash.ToString()}"); //Transaction Hash
}
catch (Exception ex)
{
if (ex.InnerException != null)
{
Console.WriteLine("Inner Exception: " + ex.InnerException.Message);
}
Console.WriteLine("Exception Message: " + ex.Message);
}
}
Here, we are using the Private key exported from our Metamask wallet to sign the Transaction. We are first creating an instance of the account using the Private key and RPC URL; then, we are sending the amount using the sender's accounts instance to the receiver's account address. At last, we are printing the transaction hash of the receipt. We can call this function in the Main method.
Output
Using the transaction Hash, we are printing over here; we can visit the Polygonscan block explorer to check the transaction status.
We can check our balance in our wallet. The transaction activity won't be shown as we are not signing the transaction using our Metamask wallet, but we can confirm our balance change by looking at the available total account balance, which would be shown at the top centre of the wallet.
Conclusion
The article offers a comprehensive guide for developers interested in connecting to the Polygon network using C#. It covers the essential steps, from setting up Alchemy and connecting with Metamask to configuring the Polygon Testnet network. By leveraging C# for Polygon implementation, developers can benefit from its widespread adoption, interoperability, smart contract support, security, and performance.
The article provides clear explanations and code examples, enabling developers to retrieve account balances and send MATIC tokens on the Polygon network. This resource serves as a valuable reference for anyone seeking to work with Polygon using C#, offering a practical approach and highlighting the advantages of this programming language.
Following the instructions outlined in the article, developers can seamlessly integrate Polygon functionality into their C# applications, expanding their capabilities and tapping into the Polygon ecosystem.
FAQ's
Q1. What is the purpose of Polygon Network?
A - The purpose of the Polygon Network is to address the scalability issues of the Ethereum Network by providing a Layer 2 scaling solution. It allows the connection of different sidechains to Ethereum's main chain, offering high transaction throughput, low fees, and fast confirmation times.
Q2 - Why is Polygon becoming popular?
A - Polygon is becoming popular due to its ability to address the scalability issues of the Ethereum Network. It offers a solution for faster and cheaper transactions, making it attractive to developers and users. Additionally, Polygon provides a seamless bridge to Ethereum, allowing users to leverage the security and ecosystem of the Ethereum Network.
Q3 - What is Alchemy, and why is it needed to connect to Polygon?
A - Alchemy is a platform that provides developer tools and infrastructure for blockchain applications. It offers APIs and developer-friendly features that simplify the process of connecting and interacting with blockchain networks like Polygon. Alchemy is needed to connect to Polygon because it provides the RPC (Remote Procedure Call) URL, which is essential for establishing a connection with the Polygon Network.
Q4 - Why is C# used for connecting to the Polygon Network?
A - C# is used for connecting to the Polygon Network due to its wide developer adoption, interoperability with the .NET framework, smart contract support through libraries like Nethereum, and its focus on security and performance. C# provides a robust programming language and tooling for building blockchain applications, making it a popular choice for developers.