简体   繁体   中英

Nethereum Call Binance Smart Chain contract function like balanceOf or transfer via Blazor WebAssembly

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 Mai.net, it has to be Binance Smart Chain. Can anyone help me?

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);
        }
    }
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM