这个和【科学家养成日记#1】读取钱包代币数量 类似,区别是要获得不同链上的币的数量

比如同个钱包地址,获得BSC,FTM,Polygon网络上的原生币数量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
//加载web3的库
const Web3 = require('web3');
//3个不同链的RPC节点,BSC,FTM和Polygon
const rpcUrls = ['https://bsc-dataseed1.binance.org/', 'https://rpcapi.fantom.network', 'https://polygon-rpc.com'];



/**
* 通过小数点多少位,转换对应的数据
* tokenDecimals: 代币的小数点数
*
**/
function getWeiName(tokenDecimals = 18) {
tokenDecimals = Number(tokenDecimals);
let weiName = 'ether';
switch (tokenDecimals) {
case 3:
weiName = "Kwei";
break;
case 6:
weiName = 'mwei';
break;
case 9:
weiName = 'gwei';
break;
case 12:
weiName = 'microether ';
break;
case 15:
weiName = 'milliether';
break;
case 18:
weiName = 'ether';
break;
default:
weiName = 'ether';
break;

}
return weiName;
}

/**
* 获得代币的符号
* @param {*} chainId 网络ID
* @returns 代币的符号
*/
function getChainToken(chainId) {
let token = '';
switch (chainId) {
case 56:
token = 'BNB';
break;
case 137:
token = 'FTM';
break;
case 250:
token = 'MATIC';
break;
default:
token = 'ETH';
break;
}
return token;
}

/**
* 获得钱包原生代币数量
* address: 钱包地址
**/
const getEthBalance = async (address, web3) => {
let result = await web3.eth.getBalance(address);
if (result) {
//经过小数点转换之后的ETH数量
let balance = web3.utils.fromWei(result, getWeiName());
let chainId = await web3.eth.getChainId();
let token = getChainToken(chainId);
return `你的钱包里有:${balance} ${token}`;
} else {
console.error("Getting ETH Balance error.");
}
}

//查看多个链钱包余额
async function main() {
let myWallet = '0x11e78fC4B70014d7B8978287bA3c5103D80dDd06';
for (let rpc of rpcUrls) {
let rpcWeb3 = new Web3(new Web3.providers.HttpProvider(rpc));
let web3 = rpcWeb3;
let balance = await getEthBalance(myWallet, web3);
console.log(balance)
}
}

main()

运行结果:

image.png