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变量,搞以前关闭小狐狸