npm安装web3
C:\Users> D:
D:> mkdir web3Proj
D:\> cd web3Proj
D:\web3Proj> npm init //然后一直回车即可
D:\web3Proj> npm install web3@0.19 //这里安装的是0.19版本,最新的1.*.*版本api发生了很大的变化。
一些相关API
web3.js的所有API默认是同步的,如果想要发出异步请求,可以把一个可选的回调函数作为最后的参数传送给大多数函数。所有回调函数都采用错误优先(error-first)回调方式,如示例代码所示。
在这个目录下建立一个名为index.html的文件,并编辑为下面的代码:
<html>
<script src="./node_modules/web3/dist/web3.min.js"></script>
<script>
if(typeof web3 !== 'undefine'){
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
//sync request
try{
console.log(web3.eth.getBlock(48));
}catch(e){
console.log(e);
}
//async request
//所有回调函数都采用错误优先(error-first)
web3.eth.getBlock(148,function(error,result){
if(!error)
console.log(result);
else
console.error(error);
});
//单位转换
console.log(web3.fromWei("54995135910000000000","ether"));//wei转换为ether
console.log(web3.toWei("13.14","ether"));//ether转换为wei
//gas价格
console.log(web3.eth.gasPrice.toString());
//地址余额(参数为账户地址-16进制字符串)
console.log(web3.eth.getBalance("0x339a7c41459c35a3FFF7E7b31B7bF14390c575AC").toString());
//交易信息(参数为交易号)
console.log(web3.eth.getTransactionReceipt("0xe427507227889843030fbcc2ce7aabc29af0f57e2f6a841b1cd5994f81f8a968"));
//发送以太币(在geth中需要unlock账户,在Ganache中不需要)
var txnHash = web3.eth.sendTransaction({
from:web3.eth.accounts[1],
to:web3.eth.accounts[0],
value:web3.toWei("7","ether")
});
</script>
</html>