如果到开发dapp与以太坊交互有很多方法,这里使用web3与geth交互,web3是以太坊官方提供的一个js的客户端交互工具。可以在nodejs项目引用,同样也可以在html中引入web3.js进行交互,但这种方法安全性较差不建议使用。web3.js最常用的场景还是在nodejs中进行服务器端的编程,可以结合express等框架写出各种形式的应用以及web接口给传统的app使用
sudo npm install web3 -g
mkdir web3
cd web3
npm init
npm install
在执行npm init命令时需要对项目做版本,入口文件等设置,按照设置新建一个入口文件默认是index.js。可以使用下面命令来执行index.js
nodejs index.js
也可以在交互模式下执行js,直接执行nodejs即可
Web3 = require("web3")
var web3 = new Web3(Web3.givenProvider||'http://127.0.0.1:8545');
web3.setProvider('http://127.0.0.1:8545');
console.log('list web3 version:');
console.log(web3.version)
console.log('list all the modules:'+Web3.modules);
getdetail(Web3.modules)
console.log('list utils:'+web3.utils);
getdetail(web3.utils)
console.log('default Account:')
console.log(web3.eth.defaultAccount)
web3.eth.getGasPrice().then(function(r){
console.log('display the gasprice base on the last block:');
console.log(r)
})
web3.eth.getAccounts().then(function(r){
console.log('display all the accounts:');
console.log(r)
})
web3.eth.personal.newAccount('sunbaolong').then(function(r){
console.log('create a new account')
console.log(r)
})
web3.eth.personal.unlockAccount('0xa5d4725d9dc3f7e73818936abe151602ad6d26fa', "sunbaolong").then(function(r){
console.log('unlock account')
console.log(r)
})
web3.eth.sendTransaction({
from: '0xa5d4725d9dc3f7e73818936abe151602ad6d26fa',
to: '0x09f90ceff015e0610a9b9b7d0e3f7c498e0b0f06',
value: '300'
}).then(function(r){
console.log('transaction is send');
console.log(r)
});
其他功能请大家自行实践