咸鱼

咸鱼是以盐腌渍后,晒干的鱼

0%

7.1、基于H5调用web3.js接口查询余额

启动 ganache-gui

打开就可以了

API

目前(20180607) 还是0.xx(0.20.6)版的,1.0还没有发布。

1
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>

Documentation

初始化项目

新建一个目录 ( 空的web工程 ),新建文件demoHello.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
<style>
.editext{
width: 50%;
}
</style>
</head>
<body>
<div>
<div>
输入服务地址:<input class="editext" id="host" value="http://localhost:7545">
</div>
<div>
输入账号地址:<input class="editext" id="address" value="0x1fdaA44143663f45C54b78c3cA4224Fc1Bb92c53">
</div>

<p id="balance" style="color:red">刷新网页查询余额</p>
</div>

<script>

var host = $("#host").val();
var address = $("#address").val();


var Web3 = require('web3');
var web3 = new Web3();
//default "http://localhost:8545"
web3.setProvider(new web3.providers.HttpProvider(host));

var coinbase = web3.eth.coinbase;
var originalBalance = web3.eth.getBalance(coinbase).toNumber();
console.log(coinbase);
console.log(originalBalance);

var version = web3.version.api;
console.log(version);

var version = web3.version.node;
console.log(version);

var mining = web3.eth.mining;
console.log("节点是否挖矿:"+mining); // true or false

var accounts = web3.eth.accounts;
console.log(accounts);

var number = web3.eth.blockNumber;
console.log("当前区块号:"+number);

var info = web3.eth.getBlock(number);
console.log("区块"+number + "的信息:");
console.log(info);


var balance = web3.eth.getBalance(address);

$("#balance").html("余额:"+balance);
console.log("余额:"+balance); // instanceof BigNumber
console.log("余额stirng:"+balance.toString(10)); // '1000000000000'
console.log("余额number:"+balance.toNumber()); // 1000000000000

</script>
</body>
</html>

在浏览器打开demo.html,正常的话,会在控制台打印:

查询余额.png