1.安裝node 最好v8的可使用ES6語法
2.安裝ganache
ganache介紹:雖然說真實發布必需要使用前文說到的三種方法geth,parity,或其它服務商,可是測試開發環境下,有一款本地基於內存的錢包,不須要等待確認交易,根據操做實時出塊,及其方便,它就是ganache-cli,納尼?你沒聽過它,好吧它的前身就是大名鼎鼎的testrpc,簡直不能太好用呀。php
安裝命令: npm i ganache-cli -g
執行命令: ganache-cli
初始狀態說明:建立10個以太坊帳戶,公鑰私鑰上下對應,默認每一個帳戶100ETH,http端口爲8545。(若是有其它需求能夠閱讀官方githug: https://github.com/trufflesui...)html
var Web3 = require(‘web3’); var web3 = new Web3(new Web3.providers.HttpProvider(「https://localhost:8545」));
說明:好多教程會這麼寫,不能說不對,但有個坑。
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")); }
若是電腦開啓geth或者metamask,web3.currentProvider和ethereumProvider就將會返回geth和metamask而不是我們設置的8545,尤爲是metamask瀏覽器打開自動開啓。前端
老版本命令:node
console.log(web3.eth.getBlockNumber());
新版本命令:git
web3.eth.getBlockNumber().then(console.log);
說明: web3 v1.0大量使用了ES6的語法,不熟悉ES6前端和node後臺有必要儘快補習一下,1.0版方法都使用異步,而且實現了promise語法,then常規使用是放入一個函數第一個參數爲成功返回值,第二個參數爲失敗返回值,將console.log做爲函數,傳入成功的值將直接完成打印。
命令:web3.eth.personal.newAccount(‘!@superpassword').then(console.log);github
先在封裝兩個異步函數,方便使用也避免進入回調地獄,要優雅寫代碼web
發起交易函數
async function sendTransaction(send,rece,ethNum){ await web3.eth.sendTransaction({ from: send, to: rece, value: ethNum }) .then(function(receipt){ console.log(receipt); console.log('send:'); findEth(send).then(function(result){ console.log(result); }); console.log('rec:') findEth(rece).then(function(result){ console.log(result); }); }); }
用公鑰查詢eth數量函數
async function findEth(publicKey){ var ethNum; await web3.eth.getBalance(publicKey).then(function(res){ ethNum = web3.utils.fromWei(res, 'ether'); }); return ethNum; }
主程序函數直接執行
async function tList(){ var accountList; await web3.eth.getAccounts().then((res)=> { accountList = res; }); await sendTransaction(accountList[0], accountList[1], 5000000000000000); console.log(findEth(accountList[0])); console.log(findEth(accountList[1])); } tList();
擴展:因爲ganache-cli的自帶帳號爲已經解鎖帳戶,若是本身建立的帳戶還須要先解鎖,而後才能夠用這種方法交易,解鎖方法以下:
web3.eth.personal.unlockAccount(myPublicKey,'password',600) .then(function(res){ })
說明:參數依次是:公鑰、密碼、解鎖時間以秒爲單位,600秒內不須要解鎖,默認爲300秒。能夠await解鎖,也能夠將交易代碼寫then函數內。
同理:封裝一個異步函數,實際上簽名交易分爲兩個步驟1.簽名一個交易2.發送這個簽名的交易到區塊鏈。npm
async function signTran(sendPri,rec,num){ web3.eth.accounts.signTransaction({ to: rec, value: num, gas: 2000000 }, sendPri) .then(function(res){ web3.eth.sendSignedTransaction(res.rawTransaction) .on('receipt', console.log); }); }
web3.eth.accounts.signTransaction參數依次爲
使用web3.eth.sendSignedTransaction將交易對象下的16進制編碼過的交易碼rawTransaction發送
坑點:複製私鑰必定要手動在前邊加上0x,ganache是沒有給你加的
坑點1:用ws回報錯
坑點2: 前文所說的要開啓person等api的使用json
工具地址:
1.web3官網官方文檔
2.ganache-cli github地址api
常見錯誤:Contract has not been deployed to detected network小狐狸(metamask)干擾,小狐狸設置了全局web3變量,搞以前關閉小狐狸