以太坊钱包开发-003 引入 web3.js 引入 web3.js

钱包 Mar 19, 2020
$ cd myWallet
$ npm install web3

定义 web3 对象

新建 util/web3helper.js,代码如下:

const Web3 = require('web3');

module.exports = {
    getWeb3(){
        const web3 = new Web3(Web3.givenProvider || "http://localhost:8545");
        return web3
    }
}

调用 web3 查询用户列表

新建 controllers/account.js,代码如下:

const web3 = require("../utils/web3helper").getWeb3()

module.exports = {
    async getAccountList (ctx) {
        console.log("version: "+ web3.version)
        const accountList = await web3.eth.getAccounts()
        console.log("accountList..."+accountList)
        ctx.body = accountList
    }
}

修改 router 文件

const router = require('koa-router')()

const accountController = require("../controllers/account")

router.get('/', accountController.getAccountList);

router.post('/', (ctx) => {

    const body = ctx.request.body;
  
    ctx.body = 'Hello Router POST '+ JSON.stringify(body);
    });
module.exports = router

启动私链网络

使用 geth 启动私有网络

$ geth --datadir ~/privatechain/data0 --networkid 110  --rpc console

查看用户列表

重新启动服务 node index.js,访问 http://localhost:3000/ ,显示结果:

["0xb5154C433E9BeDaBfdB3452C10114D5589b4B62F","0xf4E122E28c5C6A84a20C1321147453cd46182464"]

控制台打印结果:

version: 1.0.0-beta.34
accountList...0xb5154C433E9BeDaBfdB3452C10114D5589b4B62F,0xf4E122E28c5C6A84a20C1321147453cd46182464

如果可以正常打印出 version: 1.0.0-beta.34,表示 web3.js 集成成功。

源码地址

https://github.com/didianV5/web3EthWallet/tree/master/003_myWallet

恭喜! 你已经成功订阅了.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.