前言
通过Web3js开发DApp学习笔记
引入Web3js
1
| <script src="https://cdn.jsdeliver.net/npm/web3@latest/dist/web3.min.js"></script>
|
创建对象
1
| var web3 = new Web3(Web3.gibenProvider || "ws://localhost:8545");
|
获取当前的区块编号
1 2 3
| web3.eth.getBlockNumber().then(function(res) { console.log(res); });
|
获取当前的区块链编号
1 2 3
| web3.eth.getChainId().then(function(res) { console.log(res); });
|
获取账号余额
<public_key>
:钱包公钥
1 2 3
| web3.eth.getBalance("<public_key>").then(function(res) { console.log(res); });
|
以太币单位换算
单位 |
折合wei |
wei |
1wei |
Kwei |
1*10^3wei |
Mwei |
1*10^6wei |
Gwei |
1*10^9wei |
microether |
1*10^12wei |
milliether |
1*10^15wei |
ether |
1*10^18wei |
从wei转换为ether
1
| web3.utils.fromWei(res, "ether");
|
从ether转换为wei
1
| web3.utils.toWei("1", "ether");
|
转账
1 2 3 4 5 6 7
| web3.eth.sendTransaction({ from: "<public_key_from>", to: "<public_key_to>", value: web3.utils.toWei("1", "ether") }).then(function(receipt) { ... });
|
1 2 3 4 5 6 7 8
| web3.eth.requestAccounts().then(function(res) { console.log(res); });
web3.eth.getAccounts().then(function(res) { console.log(res); });
|
连接区块链上的智能合约
<abi>
:在编译完智能合约后,可以在build/contracts/xxx.json
文件中找到abi
字段的值,是一个数组结构
<address>
:在部署完智能合约后得到的合约地址(contract address
),也可以在build/contracts/xxx.json
文件中找到network.address
字段的值
1
| const obj = await new web3.eth.Contract(<abi>, "<address>");
|
调用智能合约中的方法
- 调用合约中的方法时,如果不需要支付燃料费(调用的方法是
view
函数或pure
函数),则无需获取授权账号
call()
:仅访问方法
1
| await obj.methods.方法名().call();
|
- 调用合约中的方法时,如果需要付燃料费,应当由当前授权账号支付,所以要先获取授权账号
send()
:支付燃料费
from
:定义支付燃料费的账号
1 2 3 4 5 6
| var accounts = await web3.eth.requestAccounts();
await obj.methods.方法名().send({ from: accounts[0] });
|
完成
参考文献
哔哩哔哩——千锋教育