truffle里面的web3.js使用(ETH收发)

    1、新建一个工程文件名称为heyuethree,进入该工程文件夹,用truffle init初始化它

mkdir heyuethree
cd heyuethree
truffle init

    2、查看truffle里的web3.js版本,如图(1)所示。

truffle version

图(1) 查看truffle里的web3.js版本

    由图(1)可知,web3.js的版本为v1.2.1,使用手册:
https://web3js.readthedocs.io/en/v1.2.1/web3-utils.html

    注意,该版本与0.2x.x版本(老版本)区别很大,很多函数都进行了迁移和更改。
    web3.js老版本(v0.2x.x以下):
https://github.com/ethereum/web3.js/blob/0.20.7/DOCUMENTATION.md
    web3.js新版本(v1.2.x以上):
https://web3js.readthedocs.io/en/v1.2.1/index.html
    对于v1.2.0以上版本,可以点击页面下方[Read the Docs],选中自己想要的版本即可,也可以下载到本地,如图(2)所示:


图(2) 在[Read the Docs]里选中不同的版本,并下载

    3、使用truffle develop进入truffle开发模式

truffle develop

    4、查看eth的所有账户,如图(3)所示。

var accounts;
web3.eth.getAccounts().then(function (acc) {
    
    accounts = acc});
accounts;

    5、查看指定账户
比如查看第一个账户accounts[0]、第二个账户accounts[1]的以太坊余额,如图(3)所示。

accounts[0];
accounts[1];

图(3) 查看指定的账户

    6、账户accounts[0]给accounts[1]转10个ETH,并查看余额,如图(4)所示。

var bigNum = web3.utils.toWei('10','ether')
web3.eth.sendTransaction({
    
    from: accounts[0],to: accounts[1],value: bigNum}).then(console.log);
web3.eth.getBalance(accounts[0]);
web3.eth.getBalance(accounts[1]);

图(4) accounts[0]发送10ETH给accounts[1]

猜你喜欢

转载自blog.csdn.net/sanqima/article/details/109271340