使用web3和infura开发以太坊ethereum区块链

web3

Github: https://github.com/ethereum/web3.js/ 
web3.js是以太坊提供的一个Javascript库,它封装了以太坊的RPC通信API,提供了一系列与区块链交互方法,使js与以太坊交互变得简单。

infura

官网: https://infura.io/ 
本地安装geth的方法需要花比较多的时间和空间来同步区块,利用infura可以简单很多,infura提供公开以太坊和测试节点,可以利用infura提供的api访问以太坊以及IPFS。去官网只需要提供email注册得到链接即可。

使用web3和infura开发

最常用的操作例如查看一个以太坊地址的ether余额为例(类似etherscan).

通过npm或其他方式引入web3, 并使用infura提供主网/测试网进行初始化。

// xxxx为你在infura申请的地址
web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/xxxxxxxx"));
  • 1
  • 2
  • 3

接下来就可以调用web3的接口了,例如获取一个地址的ether数量

// wei是以太坊上的的最小单位,ether小数点后18位为一个wei
var balanceWei = web3.eth.getBalance("0xC257274276a4E539741Ca11b590B9447B26A8051").toNumber();
// 从wei转换成ether
var balance = web3.fromWei(balanceWei, 'ether');
  • 1
  • 2
  • 3
  • 4

至此便可以从以太坊主网上进行操作了,例如查看区块信息,部署智能合约等。 
具体开发可以参考以太坊JS API: https://github.com/ethereum/wiki/wiki/JavaScript-API 
demo 简单的etherscan 
区块高度
查看ETH地址
查看TX

Demo Github: https://github.com/wlchn/ethersee

猜你喜欢

转载自xiajs.iteye.com/blog/2418638