---
title: "使用web3和infura开发以太坊ethereum区块链"
author: "xiajs"
date: "2018-04-15T01:05:44Z"
tags: []
categories: ["互联网"]
slug: "web3-infura-ethereum"
draft: false
lastmod: "2018-04-15T01:05:44Z"
id: 2418638
url: "https://xiajs.iteye.com/blog/2418638"
---

### web3

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

### []()infura

官网： [https://infura.io/](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](https://github.com/ethereum/wiki/wiki/JavaScript-API)   
demo 简单的etherscan   
![区块高度](https://img-blog.csdn.net/20180224165100510?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2xjaG4=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70)  
![查看ETH地址](https://img-blog.csdn.net/20180224165116485?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2xjaG4=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70)  
![查看TX](https://img-blog.csdn.net/20180224165128240?watermark%2F2%2Ftext%2FaHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2xjaG4=%2Ffont%2F5a6L5L2T%2Ffontsize%2F400%2Ffill%2FI0JBQkFCMA%3D%3D%2Fdissolve%2F70)

Demo Github: [https://github.com/wlchn/ethersee](https://github.com/wlchn/ethersee)