0

I'm developing a web application with Blazor WebAssembly. I want to call some functions in my token's contract. I've installed Nethereum.Web nuget package to my project. But I don't want to call a contract from Ethereum Mainnet, it has to be Binance Smart Chain. Can anyone help me?

Frank Zielen
  • 67
  • 10

2 Answers2

2

Yes. You just need to connect to a Binance Smart Chain node instead of Ethereum node. All the other code is just the same.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 10 '22 at 02:40
2

You can use Nethereum.Web3 Nuget package for both, Ethereum and Binance Smart Chain (BSC).

Enclosed you find a C# example connecting to BSC via GetBlock. You can easily setup a free node with GetBlock and obtain your API key with associated endpoint within a few clicks.

In the code snippet the Chromia token contract is used and we request the balance of a sample account. You just need to replace code with your contract of choice.

using System;
using System.Threading.Tasks;
using System.Numerics;
using Nethereum.Web3;

namespace BSC
{
    class Example
    {
        static async Task Main(string[] args)
        {
            // Connect to BSC node
            // Replace XX-XXX-XX with your personal API key (when also using GetBlock)
            var web3 = new Web3("https://bsc.getblock.io/mainnet/?api_key=XX-XXX-XX");

            // Get contract by providing ABI and address of contract
            // Here Chromia token with ABI for balanceOf function only is used for example
            string abi = @"[{""inputs"":[{""internalType"":""address"",""name"":""account"",""type"":""address""}],""name"":""balanceOf"",""outputs"":[{""internalType"":""uint256"",""name"":"""",""type"":""uint256""}],""stateMutability"":""view"",""type"":""function""}]";
            string contractaddress = "0xf9CeC8d50f6c8ad3Fb6dcCEC577e05aA32B224FE";
            var contract = web3.Eth.GetContract(abi, contractaddress);

            // Call function of contract
            // Here balance of a random address is requested for example
            var function = contract.GetFunction("balanceOf");
            string address = "0x8A2279d4A90B6fe1C4B30fa660cC9f926797bAA2";
            BigInteger balance = await function.CallAsync<BigInteger>(address);

            Console.WriteLine("Balance: " + balance);
        }
    }
}
Frank Zielen
  • 67
  • 10