【JS】【每日知识】Web3 API 实践
首先,推荐一个讲述web3&solidity的博客:http://me.tryblockchain.org/index.html;我认为里面的文章写的还不错,官方文档翻译的也很到位。有空的同学可以去看看里面的文章。
博客中《web3.js编译Solidity,发布,调用全部流程(手把手教程)》一文开头写到要安装web3.js,对于已经安装truffle框架的童鞋来说,就不需要安装了,因为truffle框架里已经内置的web3.js。同时,我们要使用web3的时候,就必须到truffle的开发者模式中使用。
要进入truffle开发者模式,首先要cd到合约文件夹。打开命令行,输入:cd F:\soliditycode\demo01;再输入:truffle develop;如图:

进入开发者模式后,会显示你的私链地址:http://127.0.0.1:9545/;还会给出10个账户以及每个账户的私钥。
查看web3的版本信息命令
输入命令:web3.version就可以看到web3的版本信息;而我们继续输入web3.version.api , web3.version.node , web3.version.network , web3.version.ethereum , web3.version.whisper就可以别查看他们的版本信息,如图:

单位转换命令
单位转换命令有两种,一种是把其他单位转成‘位‘,还一种就是把‘位’转成其他单位。输入命令:web3.toWei(10,'ether')和web3.fromWei(1000000000000,'ether'),1 ether=10**18 wei,效果如图:

查看私有链信息和设置私有链命令
设置私有链命令:web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'))
查看私有链信息命令:web3.currentProvider;
如图:

查看账户列表命令
输入命令:web3.setProvider(new web3.providers.HttpProvider('http://localhost:9545'))把私有链地址切换回来;
输入命令:web3.eth.accounts查看账户列表;
查看第一个账户:web3.eth.accounts[0];如图:

查看账户余额命令
输入命令查看第一个账户余额:web3.eth.getBalance(web3.eth.accounts[0]),会发现一个十六进制的表示方式,在命令后加“.toString()”可转成数字表示;
表示的单位是“位”,我们可以和转换单位的命令结合,将单位转换成“以太”,命令:web3.fromWei(web3.eth.getBalance(web3.eth.accounts[0]).toString(),'ether');
如图:

转账命令
输入命令:web3.eth.sendTransaction({from:account1,to:account2,value:web3.toWei(10,'ether')});
在该命令之前要先定义account1和account2,输入命令:var account1 = web3.eth.accounts[0] ; var account2 = web3.eth.accounts[1] ;
转账完后分别查看account1和account2的余额变化;
如图:

以上是 【JS】【每日知识】Web3 API 实践 的全部内容, 来源链接: utcz.com/a/68037.html