在ETH 2.0抵押的一个基本需求是监视其验证者余额,在这个教程中我们将学习如何利用Infura的ETH 2.0 Beacon Chain API编写程序来查询验证者(Validator)的余额。
用自己熟悉的语言学习 以太坊DApp开发 :Java | Php | Python | .Net / C# | Golang | Node.JS | Flutter / Dart
离ETH 2.0的零阶段启动越来越近,在witti以及即将上线的altona测试网上参与抵押的兴趣也越来越高涨 —— 调查报告显示超过65%的受访者表示期望抵押其持有的ETH。
首先我们需要引入axio库并创建一个HTTP客户端,从环境变量加载Infura项目ID:
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://witti.infura.io/',
auth: {
username: process.env.INFURA_PROJECT_ID,
password: '',
},
});
我们需要定义一些网络相关的参数。前两个有助于我们计算当前周期(epoch),最后一个用来将余额单位从gwei转换为我们更熟悉的eth:
const SECONDS_PER_SLOT = 12;
const SLOTS_PER_EPOCH = 32;
const GWEI_PER_ETH = 1000000000;
接下来我们将查询网络的创世数据用来计算当前周期:
(async () => {
let response = await instance.get('node/genesis_time')
const genesisTime = response.data;
const now = Math.floor(Date.now() / 1000)
const currentEpoch = Math.floor((now - genesisTime) / (SECONDS_PER_SLOT * SLOTS_PER_EPOCH))
有了这些代码,我们就可以查询验证者(Validator)的当前余额了,这里我们使用写文章时余额最高的验证者的公钥进行查询:
response = await instance.post('beacon/validators', {
epoch: currentEpoch.toString(),
pubkeys: ["0xb0bfa93603f81ecaf3c450b793e71f7372822cd2002534364493e4e497fb5df16d252ae2fdc6bbc0e74d849f918db393"],
});
const balanceGwei = response.data[0].balance;
const balance = balanceGwei / GWEI_PER_ETH;
console.log(`You have ${balance} Ξ2.0`);
})();
当我们运行这个程序时,就可以看到如下输出:
You have 32.500178823 Ξ2.0
下面是查询ETH 2.0验证者余额的完整代码:
import axios from 'axios';
const instance = axios.create({
baseURL: 'https://witti.infura.io/',
auth: {
username: process.env.INFURA_PROJECT_ID,
password: '',
},
});
const SECONDS_PER_SLOT = 12;
const SLOTS_PER_EPOCH = 32;
const GWEI_PER_ETH = 1000000000;
(async () => {
let response = await instance.get('node/genesis_time')
const genesisTime = response.data;
const now = Math.floor(Date.now() / 1000)
const currentEpoch = Math.floor((now - genesisTime) / (SECONDS_PER_SLOT * SLOTS_PER_EPOCH))
response = await instance.post('beacon/validators', {
epoch: currentEpoch.toString(),
pubkeys: ["0xb0bfa93603f81ecaf3c450b793e71f7372822cd2002534364493e4e497fb5df16d252ae2fdc6bbc0e74d849f918db393"],
});
const balanceGwei = response.data[0].balance;
const balance = balanceGwei / GWEI_PER_ETH;
console.log(`You have ${balance} Ξ2.0`);
})();
原文链接:ETH 2.0验证者余额查询 — 汇智网