Nethereum

使用 Nethereum 为 .NET 应用程序连接到 256 Blocks

Nethereum 是用于以太坊的 .NET 集成库,提供了与以太坊节点、智能合约和更广泛生态系统交互的完整实现。

安装

通过 NuGet 安装 Nethereum:

dotnet add package Nethereum.Web3

或通过包管理器控制台:

Install-Package Nethereum.Web3

快速开始

使用 X-API-Key 标头连接到 256 Blocks:

using Nethereum.Web3;
using Nethereum.JsonRpc.Client;
using System.Net.Http;
 
// Create HttpClient with API key header
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("X-API-Key", "your-api-key");
 
// Create RPC client with custom HttpClient
var rpcClient = new RpcClient(
    new Uri("https://rpc.256blocks.com/ethereum"),
    httpClient
);
 
// Create Web3 instance
var web3 = new Web3(rpcClient);
 
// Get the latest block number
var blockNumber = await web3.Eth.Blocks.GetBlockNumber.SendRequestAsync();
Console.WriteLine($"Latest Block: {blockNumber.Value}");

读取账户余额

using Nethereum.Web3;
using Nethereum.JsonRpc.Client;
using System.Net.Http;
 
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("X-API-Key", "your-api-key");
 
var rpcClient = new RpcClient(
    new Uri("https://rpc.256blocks.com/ethereum"),
    httpClient
);
 
var web3 = new Web3(rpcClient);
 
// Get account balance
var address = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb";
var balance = await web3.Eth.GetBalance.SendRequestAsync(address);
var etherAmount = Web3.Convert.FromWei(balance.Value);
 
Console.WriteLine($"Balance: {etherAmount} ETH");

读取合约数据

using Nethereum.Web3;
using Nethereum.JsonRpc.Client;
using Nethereum.ABI.FunctionEncoding.Attributes;
using Nethereum.Contracts;
using System.Numerics;
using System.Net.Http;
 
// ERC-20 balanceOf function
[Function("balanceOf", "uint256")]
public class BalanceOfFunction : FunctionMessage
{
    [Parameter("address", "account", 1)]
    public string Account { get; set; }
}
 
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("X-API-Key", "your-api-key");
 
var rpcClient = new RpcClient(
    new Uri("https://rpc.256blocks.com/ethereum"),
    httpClient
);
 
var web3 = new Web3(rpcClient);
 
// USDC contract on Ethereum
var contractAddress = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48";
var contract = web3.Eth.GetContractHandler(contractAddress);
 
var balanceOfMessage = new BalanceOfFunction
{
    Account = "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb"
};
 
var balance = await contract.QueryAsync<BalanceOfFunction, BigInteger>(balanceOfMessage);
Console.WriteLine($"USDC Balance: {balance}");

多链支持

通过更改端点连接到不同的链:

// Ethereum Mainnet
var ethClient = new RpcClient(new Uri("https://rpc.256blocks.com/ethereum"), httpClient);
 
// Base
var baseClient = new RpcClient(new Uri("https://rpc.256blocks.com/base"), httpClient);
 
// Arbitrum
var arbClient = new RpcClient(new Uri("https://rpc.256blocks.com/arbitrum"), httpClient);
 
// Polygon
var polygonClient = new RpcClient(new Uri("https://rpc.256blocks.com/polygon"), httpClient);

资源

Nethereum | 256 Blocks