我想以编程方式查询地址或地址列表的余额。做这件事最好的方法是什么?
发布于 2020-04-20 11:43:37
要在最新的块中获得0xc466c8ff5dAce08A09cFC63760f7Cc63734501C1的余额,请执行以下操作:
curl -X POST -H 'Content-Type: application/json' -s --data '{"jsonrpc":"2.0","method":"eth_getBalance","params":["0xad23b02673214973e354d41e19999d9e01f3be58", "latest"], "id":1}' https://mainnet-rpc.thundercore.com/输出:{"jsonrpc":"2.0","id":1,"result":"0xde0b6b3a7640000"}
用web3.js获取单个帐户的余额
const Eth = require('web3-eth');
const Web3 = require('web3');
const web3Provider = () => {
return Eth.giveProvider || 'https://mainnet-rpc.thundercore.com';
}
const balance = async (address) => {
const eth = new Eth(web3Provider());
return Web3.utils.fromWei(await eth.getBalance(address));
}样本会话
const address = '0xc466c8ff5dAce08A09cFC63760f7Cc63734501C1';
await balance(address) // -> '1'单位
0xde0b6b3a7640000等于10**18fromWei将10^18 Wei转换为1 Ether,或使用1术语fromWei将10^18 Ella转换为1 TTfromWei(0xde0b6b3a7640000)等于fromWei(10**18) = 1请求批处理查询余额
https://mainnet-rpc.thundercore.com时,将批处理大小限制在30周围下面的类封装web3.js-1.2.6的BatchRequest并使其返回Javascript Promise
class BatchRequest {
constructor(web3) {
this.b = new web3.BatchRequest();
this.results = [];
this.resolve = null;
this.reject = null;
this.resultsFilled = 0;
}
web3BatchRequestCallBack(index, err, result) {
/* if any request in our batch fails, reject the promise we return from `execute` */
if (err) {
this.reject(new Error(`request ${index} failed: ${err}`))
return;
}
this.results[index] = result;
this.resultsFilled++;
if (this.resultsFilled === this.results.length) {
this.resolve(this.results);
}
}
resultPromiseExecutor(resolve, reject) {
this.resolve = resolve;
this.reject = reject;
}
add(method /* web3-core-method.Method */) {
const index = this.results.length;
method.callback = (err, result) => {
this.web3BatchRequestCallBack(index, err, result)
};
this.b.add(method);
this.results.push(undefined);
}
execute() /*: Promise */ {
const p = new Promise((resolve, reject) => { this.resultPromiseExecutor(resolve, reject) });
/* must arrange for resultPromiseExecutor to be called before b.execute */
this.b.execute();
return p;
}
}const balanceBatch = async (addresses) => {
const eth = new Eth(web3Provider());
const b = new BatchRequest(eth);
for (a of addresses) {
b.add(eth.getBalance.request(a));
}
const ellaS = await b.execute();
const ttS = [];
for (e of ellaS) {
ttS.push(Web3.utils.fromWei(e));
}
return ttS;
}batch-balance-test.js
const Web3 = require('web3');
(async() => {
const web3 = new Web3('https://mainnet-rpc.thundercore.com');
const results = await balanceBatch([
'0xc466c8ff5dAce08A09cFC63760f7Cc63734501C1',
'0x4f3c8e20942461e2c3bdd8311ac57b0c222f2b82',
]);
console.log('results:', results);
})();样本会话
$ node batch-balance-test.js
results: [ '1', '84.309961496' ]请参阅这里回购的balance分支中的完整项目设置field-support。
https://stackoverflow.com/questions/61266742
复制相似问题