Use of web3.js in truffle (ETH sending and receiving)

    1. Create a new project file named heyuethree, enter the project folder, and initialize it with truffle init

mkdir heyuethree
cd heyuethree
truffle init

    2. Check the web3.js version in truffle, as shown in Figure (1).

truffle version

Figure (1) View the web3.js version in truffle

    As shown in Figure (1), the version of web3.js is v1.2.1, and the manual:
https://web3js.readthedocs.io/en/v1.2.1/web3-utils.html

    Note that this version is very different from the 0.2xx version (old version), and many functions have been migrated and changed.
    Old version of web3.js (below v0.2x.x):
https://github.com/ethereum/web3.js/blob/0.20.7/DOCUMENTATION.md
    New version of web3.js (above v1.2.x) :
Https://web3js.readthedocs.io/en/v1.2.1/index.html
    For versions above v1.2.0, you can click [Read the Docs] at the bottom of the page, select the version you want, or download it to Locally, as shown in Figure (2):


Figure (2) Select different versions in [Read the Docs] and download

    3. Use truffle develop to enter truffle development mode

truffle develop

    4. View all accounts of eth, as shown in Figure (3).

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

    5. View the specified account For
example, view the Ethereum balance of the first account accounts[0] and the second account accounts[1], as shown in Figure (3).

accounts[0];
accounts[1];

Figure (3) View the specified account

    6. Transfer 10 ETH from account accounts[0] to accounts[1], and check the balance, as shown in Figure (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]);

Figure (4) accounts[0] sends 10ETH to accounts[1]

Guess you like

Origin blog.csdn.net/sanqima/article/details/109271340