开发工具:vscode
实现中获取Vitalik地址的ETH
余额的功能
https://www.wtf.academy/docs/ethers-101/HelloVitalik/
1.打开vscode,创建一个文件夹。或者在本地创建好文件夹选择打开:
2.在控制面板下的TERMINAL中输入:npm install ethers --save
注:这里输入这行代码会自动下载最新版的ethers.js 但是最新版的js与文档中的方法不一致,所以会导致运行失败:
ethers.formatEther is not a function
需要改为:
console.log(`ETH Balance of vitalik: ${ethers.utils.formatEther(balance)} ETH`);
如果想跟文档中一样,就下载5.6.9版本,命令行为:npm install ethers@5.6.9
下载好的目录如下:
因为是新建的目录,所以需要在package.json文件中输入 "type": "module":
3. 新建一个js文件,图中我新建了一个名为hello.js的文件,在文件中输入或者粘贴进文档中的代码:
import { ethers } from "ethers";
const provider = ethers.getDefaultProvider();
const main = async () => {
const balance = await provider.getBalance(`vitalik.eth`);
console.log(`ETH Balance of vitalik: ${ethers.utils.formatEther(balance)} ETH`);
}
main()
接下来就可以运行了,在TERMINAL中输入:node hello.js,即可看到效果:
注:中间有一个坑 ,会报错:
Error: ENS name not configured (operation="resolveName(\"vitalik.eth\")", code=UNSUPPORTED_OPERATION, version=providers/5.7.1)
at Logger.makeError (d:\sunflowerCode\etherjs\node_modules\@ethersproject\logger\lib\index.js:238:21)
at Logger.throwError (d:\sunflowerCode\etherjs\node_modules\@ethersproject\logger\lib\index.js:247:20)
at FallbackProvider.<anonymous> (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:1980:36)
at step (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:48:23)
at Object.next (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:29:53)
at fulfilled (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:20:58)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
reason: 'ENS name not configured',
code: 'UNSUPPORTED_OPERATION',
operation: 'resolveName("vitalik.eth")'
解决方法:在 alchemy或者 infura中注册,然后生成自己的key,我用alchemy,代码如下:
import { ethers } from "ethers";
const provider = ethers.getDefaultProvider();
const main = async () => {
// const ethers = require("ethers");
const provider = new ethers.providers.JsonRpcProvider("https://eth-mainnet.g.alchemy.com/v2/你的key");
const balance = await provider.getBalance(`vitalik.eth`);
console.log(`ETH Balance of vitalik: ${ethers.utils.formatEther(balance)} ETH`);
}
main()
即可获得运行效果:
ETH Balance of vitalik: 356.103908103441132271 ETH