Quickstart .NET (C#)
This quickstart guide is deprecated.
Introduction​
This tutorial will teach you how to set up a server-side dapp to query blockchain data, such as NFTs, tokens, balances, transfers, transactions, etc., from any .NET application. \n\nThis tutorial dapp works on almost any blockchain, including Ethereum, Polygon, BNB Chain, Avalanche, Cronos, and many more!
The Steps We Will Take​
- Create a C# dapp
- Import and set up the latest Moralis .NET SDK
- Integrate your application with Moralis services
- Read any blockchain data from any blockchain
Prerequisites​
- Create a Moralis account
- Install and set up Visual Studio
Create a C# Dapp​
For this part of the tutorial, we will create a dapp that displays the native balance, ERC-20 tokens, and NFTs for any address and EVM chain! The complete code for this project can be found here.
- Open Visual Studio and create a new project
- Select C# Console as the template:
- Configure your new project by entering the name of the project and location. For this demo, we use "MoralisDemo" as the project name.
- Enter additional information and click on the "create" button. For this demo, we select ".NET 6.0" as the framework:
- Visual Studio will generate a basic C# Console project.
Import and Set Up the Latest Moralis .NET SDK​
- Open "NuGet Package Manager" by selecting Tools > NuGet Package Manager > Manage NuGet Packages for Solution...:
- Checkmark Include prerelease and browse for Moralis.
- Select the latest Moralis package and click on the Install button:
Integrate Your Dapp with Moralis Services​
- In the Solution Explorer window, open the
Program.cs
file. - Select the contents of this file and delete them.
- Add the following
using
statements:
using Moralis;
using Moralis.Web3Api.Models;
- Add
namespace
,class
, and basic public staticMain
. - Within the
Main
function, setMoralisClient.ConnectionData
with the values specific to your dapp. You can find your Moralis dapp information by signing into your Moralis account.
namespace ConsoleDemo
{
internal class Program
{
static void Main(string[] args)
{
// Setup Moralis
MoralisClient.ConnectionData = new Moralis.Models.ServerConnectionData()
{
ApiKey = "YOUR MORALIS WEB3API KEY"
};
}
}
}
- Under the
Main
function, create a staticasync
function calledDisplayCryptoData
. This function should accept two parametersaddress
(string) andchainId
(ChainList). The return type should beTask
.
internal static async Task DisplayCryptoData(string address, ChainList chainId)
{
}
- The application will accept two arguments, the address and the chain ID. It is a good idea to make sure these are passed in and are valid before using them. At the top of the
Main
function, add code that validates the arguments. - Now, add code to execute the
DisplayCryptoData
function. Since this is anasync
function, it needs to be called within aTask.Run
statement. YourMain
function should now be similar to:
static void Main(string[] args)
{
if (args.Length < 2)
{
Console.Write("Usage: ConsoleDemo.exe ADDRESS CLIENT_ID");
return;
}
string address = args[0];
int chainId = 1;
if (!int.TryParse(args[1], out chainId))
{
Console.Error.WriteLine("CHAIN_ID must be a number.");
}
// Setup Moralis
MoralisClient.ConnectionData = new Moralis.Models.ServerConnectionData()
{
ApiKey = "YOUR MORALIS WEB3API KEY"
};
Task.Run(async () =>
{
await DisplayCryptoData(address, (ChainList)chainId);
}).Wait();
}
Read Any Blockchain Data From Any Blockchain​
- Within the
DisplayCryptoData
function, start by displaying the address specified:
Console.WriteLine($"For address: {address}...\n");
Fetch and Display Native Balance​
- Retrieve the native balance by calling the Moralis SDK. Use the
GetNativeBalance
operation of the Web3Api Account endpoint to retrieve this information.
// Load native balance for address
NativeBalance bal = await MoralisClient.Web3Api.Account.GetNativeBalance(address, chainId);
- Format and display the native balance:
double nativeBal = 0;
double.TryParse(bal.Balance, out nativeBal);
Console.WriteLine($"Your native balance is {nativeBal / Math.Pow(10,18)}");
Fetch and Display ERC-20 Token Balances​
- Next, use the Moralis SDK to retrieve the ERC-20 token balances owned by the specified address. Use the
GetTokenBalances
operation of the Web3Api Account endpoint to retrieve this list:
// Load ERC-20 Token List for address
List<Erc20TokenBalance> erc20Balnaces = await MoralisClient.Web3Api.Account.GetTokenBalances(address, chainId);
- If ERC-20 tokens were returned, format and display these. Otherwise, print "NONE".
Console.WriteLine("\n\nYour ERC 20 Tokens:");
if (erc20Balnaces != null && erc20Balnaces.Count > 0)
{
// Print out each token with symbol and balance.
foreach (Erc20TokenBalance tb in erc20Balnaces)
{
Console.WriteLine($"\t{tb.Symbol} - {tb.Name}: {tb.NativeTokenBalance}");
}
}
else
{
Console.WriteLine("\tNone");
}
Fetch and Display NFTs with Metadata​
- Finally, use the Moralis SDK to retrieve the NFT tokens owned by the specified address. For this demo, we will limit it to the first ten. Use the
GetNFTs
operation of the Web3Api Account endpoint to retrieve this list:
// Load first 10 NFTs for the address
NftOwnerCollection nfts = await MoralisClient.Web3Api.Account.GetNFTs(address, (ChainList)chainId, "", null, 10);
- If a set of NFTs was returned, display the name, balance, and metadata for each. Your entire
DisplayCryptoData
* function should look similar to:
internal static async Task DisplayCryptoData(string address, ChainList chainId)
{
try
{
Console.WriteLine($"For address: {address}...\n");
// Load native balance for address
NativeBalance bal = await MoralisClient.Web3Api.Account.GetNativeBalance(address, chainId);
double nativeBal = 0;
double.TryParse(bal.Balance, out nativeBal);
Console.WriteLine($"Your native balance is {nativeBal / Math.Pow(10,18)}");
// Load ERC-20 Token List for address
List<Erc20TokenBalance> erc20Balnaces = await MoralisClient.Web3Api.Account.GetTokenBalances(address, chainId);
Console.WriteLine("\n\nYour ERC 20 Tokens:");
if (erc20Balnaces != null && erc20Balnaces.Count > 0)
{
// Print out each token with symbol and balance.
foreach (Erc20TokenBalance tb in erc20Balnaces)
{
Console.WriteLine($"\t{tb.Symbol} - {tb.Name}: {tb.NativeTokenBalance}");
}
}
else
{
Console.WriteLine("\tNone");
}
// Load first 10 NFTs for the address
NftOwnerCollection nfts = await MoralisClient.Web3Api.Account.GetNFTs(address, (ChainList)chainId, "", null, 10);
Console.WriteLine("\n\nYour NFTs:");
if (nfts != null && nfts.Result.Count > 0)
{
// Print out each token with symbol and balance.
foreach (NftOwner nft in nfts.Result)
{
Console.WriteLine($"\t{nft.Name}: {nft.Amount}\n\tMetaData: {nft.Metadata}\n\n");
}
}
else
{
Console.WriteLine("\tNone");
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex);
}
}
If you run it as is in Visual Studio, your output should be similar to:
Usage: ConsoleDemo.exe ADDRESS CLIENT_ID
.
In Solution Explorer, right-click on Properties _then select _Debug > General and click on the Open debug launch profile link:
In Command Line Arguments, enter your wallet address and chain ID.
Now, when you run your dapp, your data is displayed!