区块链入门基础课:零基础玩转以太坊开发(四)获取钱包信息

今天我们要讨论的是如何获取钱包信息。及对交易计算细节处理的类的解释。有需要的朋友们可以收藏关注一下。

今天我们直接开始。。

获取钱包信息是一个比较简单的过程,以下是一些步骤和示例代码,说明如何完成这一操作:

一:导入命名空间

using Nethereum.Web3;
using Nethereum.RPC.Eth.DTOs;
using System.Threading.Tasks;

 二:创建Web3实例

var web3 = new Web3("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");

三:定义钱包地址

string walletAddress = "你的钱包地址";

四:.获取钱包余额

public async Task<Wei> GetWalletBalance()
{
    var balance = await web3.Eth.GetBalance.SendRequestAsync(walletAddress);
    return balance;
}

这里需要注意的是,这将返回一个Task<Wei>类型的结果,其中Wei是ETH的最小单位。

在Nethereum库中,Wei类是一个用于表示以太坊中最小单位“wei”的数值类型。以太坊中的所有价值转移都是以wei为单位进行的,1 Ether等于10^18 wei。这意味着即使是极小的金额也可以被精确地处理。

wei类示例:

using Nethereum.RPC.Eth.DTOs;
​
// 创建一个Wei实例
var amount = new Wei(new BigInteger(1000000000000000000)); // 等于1 Ether
​
// 将Wei转换为十进制的Ether
decimal etherAmount = amount.ToDecimal(EthUnit.Ether); // 结果为1.0M
​
// Wei之间的运算
var total = amount + new Wei(new BigInteger(500000000000000000)); // 结果为1.5 Ether
​
// Wei和BigInteger之间的运算
total += 500000000000000000; // 结果为2.0 Ether
​
// 比较运算
bool isEqual = total == new Wei(2 * 1000000000000000000); // 结果为true

五:转换余额为ETH

public async Task<decimal> GetWalletBalanceInEther()
{
    var balanceWei = await GetWalletBalance();
    var balanceEther = balanceWei.Value.ToDecimal(EthUnit.Ether);
    return balanceEther;
}

Wei单位的余额可能非常大,通常你会想将其转换为更易读的Ether单位。Nethereum提供了Wei类的方法来帮助你进行转换。

总结:

using System;
using System.Threading.Tasks;
using Nethereum.Web3;
using Nethereum.RPC.Eth.DTOs;
​
class Program
{
    static async Task Main(string[] args)
    {
        var web3 = new Web3("https://mainnet.infura.io/v3/YOUR_PROJECT_ID");
        string walletAddress = "0xYourWalletAddressHere";
​
        var balance = await GetWalletBalance(web3, walletAddress);
        Console.WriteLine($"钱包余额为: {balance} ETH");
    }
​
    public static async Task<decimal> GetWalletBalance(Web3 web3, string walletAddress)
    {
        var balanceWei = await web3.Eth.GetBalance.SendRequestAsync(walletAddress);
        return balanceWei.Value.ToDecimal(EthUnit.Ether);
    }
}

注意,上面的代码实际场景中应替换YOUR_PROJECT_ID你的钱包地址(0x开头)为你的Infura项目ID和你想要查询的实际钱包地址。如果你使用的是自己的以太坊节点,那么你应该提供你的节点URL而不是Infura的URL。

  • 19
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值