以太坊智能合約開發,Web3.js API 中文文檔 ethereum web3.js入門說明
為了讓你的Ðapp運行上以太坊,一種選擇是使用web3.js library提供的web3。
對象。底層實現上,它通過RPC 調用與本地節點通信。web3.js可以與任何暴露了RPC接口的以太坊節點連接。
web3
中有eth
對象 - web3.eth
具體來表示與以太坊區塊鏈之間的交互。shh
對象 - web3.shh
表示Whisper
協議的相關交互。后續我們會繼續介紹其它一些web3協議中的對象。可用的example can be found here
如果你想找一些更復雜的示例,可以看看這里useful Ðapp patterns.
GitHub - ethereum/web3.js at master
https://github.com/ethereum/web3.js/tree/master
入門
添加web3
首先你需要將web3引入到你的工程中,通過如下步驟:
- npm:
npm install web3
- bower:
bower install web3
- metor:
meteor add ethereum:web3
- vanilla:
dist./web3.min.js
然后你需要創建一個web3的實例,設置一個provider
。為了保證你不會覆蓋一個已有的provider
,比如使用Mist時有內置,需要先檢查是否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了。
使用callback
由於這套API被設計來與本地的RPC結點交互,所有函數默認使用同步的HTTP的請求。
如果你想發起一個異步的請求。大多數函數允許傳一個跟在參數列表后的可選的回調函數來支持異步。回調函數支持error first callback的風格。
web3.eth.getBlock(48, function(error, result){ if(!error) console.log(result) else console.error(error); })
批量請求
可以允許將多個請求放入隊列,並一次執行。
注意:批量請求並不會更快,在某些情況下,同時發起多個請求,由於是異步的,會變得更快。但這里的批量請求主要目的是用來保證請求的串行執行。
關於web3.js中的Big Number
的說明
數據類型的返回結果,你將始終會得到一個BigNumber
對象,因為Javascript不能正確的處理BigNumber
,如下面的例子:
"101010100324325345346456456456456456456" // "101010100324325345346456456456456456456" 101010100324325345346456456456456456456 // 1.0101010032432535e+38
所以web3.js依賴BigNumber Library1,且會自動進行引入。
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 max 20 floating points // "13145.23443534645646666646" // you number would be cut after the 20 floating point
-
Big Number 文檔鏈接: https://github.com/MikeMcl/bignumber.js ↩
---------------
官方網站:
http://web3js.readthedocs.io/en/1.0/
Web3.js API 中文文檔
http://web3.tryblockchain.org/