web3.js简单使用
JWLAZY opened this issue · comments
web3.js简单使用
地址: [web3.js](https://github.com/ethereum/web3.js)
简介: 一个链接以太坊节点的javascript库,当然也有其他语言实现的web3,比如web3.py
简单分析
web3.js 只是对以太坊节点暴露出来的接口进行的javascript封装,通过web3.js 可以轻松的实现账户,转账,智能合约等业务方面的功能
简单使用
注意: 本文章使用web3.js 的版本1.0.0-beta.30, web3 1.0版本和0.x 版本差异比较大,而在浏览器中MetaMask使用的0.x版本.
先新建一个web3的实例
const Web3 = require('web3');
const ganache_cli = require('ganache-cli');
const web3 = new Web3(ganache_cli.provider());
1. 获取所有账户
// 获取当前节点所有账号
web3.eth.getAccounts().then(accounts => {
console.log(accounts);
});s
2. 获取账户余额
// 获取当前节点所有账号
web3.eth.getAccounts().then(accounts => {
console.log(accounts);
// 获取账户余额
web3.eth.getBalance(accounts[0]).then(result => {
// web3.utils 提供了一一些常用方法,fromwei方法把单位为wei的值转换为其他单位
console.log(web3.utils.fromWei(result, 'ether'));
})
});
3. 获取区块信息
web3.eth.getBlockNumber().then(number => {
console.log('block:' + number);
})
...
总结
有了web3我们就可以简单的去开发基于区块链节点只上的应用了,后面还可以通过智能合约来开发DAPP.
代码地址: Github
交流地址: telegram