本文首发于深刻浅出区块链社区 原文连接:Web3.js 0.20.x API 中文版翻译原文已更新,请读者前往原文阅读html
文档原始连接为:https://web3.learnblockchain.cn/0.2x.x/,欢迎你们前往查阅,本文只是节选开头部分的介绍及API列表索引,如下为翻译正文:node
为了开发一个基于以太坊的去中心化应用程序,能够使用web3.js库提供的web3对象, 在底层实现上,web3经过RPC调用与本地节点通讯, web3.js能够与任何暴露了RPC接口的以太坊节点链接。git
web3
包含下面几个对象:github
web3.eth
用来与以太坊区块链及合约的交互web3.shh
用来与Whisper协议相关交互web3.net
用来获取网络相关信息web3
包含一些工具web3使用示例:web
想要学习去中心化应用(DAPP)开发,这门课程不容错过区块链全栈-以太坊DAPP开发实战npm
首先你须要将web3引入到应用工程中,能够经过以下几个方法:api
npm install web3
bower install web3
meteor add ethereum:web3
dist./web3.min.js
而后你须要建立一个web3的实例,设置一个provider。为了保证你不会覆盖一个已有的provider(Mist浏览器或安装了MetaMak的浏览器会提供Provider),须要先检查是否web3实例已存在,示例代码以下:浏览器
if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { // set the provider you want from Web3.providers web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545")); }
成功引入后,你如今能够使用web3
对象的API了。网络
因为这套API被设计来与本地的RPC结点交互,全部函数默认使用同步的HTTP的请求。app
若是你想发起一个异步的请求。大多数函数容许传一个跟在参数列表后的可选的回调函数来支持异步,回调函数支持Error-first回调的风格。
web3.eth.getBlock(48, function(error, result){ if(!error) console.log(JSON.stringify(result)); else console.error(error); })
能够容许将多个请求放入队列,并一次执行。
注意:批量请求并不会更快,在某些状况下,同时发起多个异步请求,也许更快。这里的批量请求主要目的是用来保证请求的串行执行。
var batch = web3.createBatch(); batch.add(https://web3.learnblockchain.cn/0.2x.x/web3.eth.getBalance.request('0x0000000000000000000000000000000000000000', 'latest', callback)); batch.add(https://web3.learnblockchain.cn/0.2x.x/web3.eth.contract(abi).at(address).balance.request(address, callback2)); batch.execute();
若是是一个数据类型的返回结果,一般会获得一个BigNumber对象,由于Javascript不能正确的处理BigNumber,看看下面的例子:
"101010100324325345346456456456456456456" // "101010100324325345346456456456456456456" 101010100324325345346456456456456456456 // 1.0101010032432535e+38
因此web3.js依赖BigNumber Library,且已经自动引入。
var balance = new BigNumber('131242344353464564564574574567456'); // or var balance = web3.eth.getBalance(someAddress); balance.plus(21).toString(10); // toString(10) converts it to a number string // "131242344353464564564574574567477"
下一个例子中,咱们会看到,若是有20位以上的浮点值,仍会致使出错。因此推荐尽可能让账户余额以wei为单位,仅仅在须要向用户展现时,才转换为其它单位。
var balance = new BigNumber('13124.234435346456466666457455567456'); balance.plus(21).toString(10); // toString(10) converts it to a number string, but can only show upto 20 digits // "13145.23443534645646666646" // your number will be truncated after the 20th digit