How to use the web3. js API to transfer money in a page
This article introduces how to use web3. js API in the page for transfer, is my translation of the document web3. js 0.2x Chinese version and blockchain full stack – Ethereum DAPP development actual combat Demo article description.
Writing in the front
Before you read this article, you should be familiar with the concepts of Ethereum, smart contracts, and wallets. If you don’t already, I suggest you read what Ethereum is. In addition, you should have some knowledge of HTML and JavaScript.
Preparation of UI page for transfer
The main UI interface of transfer is shown as follows:
This interface is easy to implement, so I won’t code it here. You can open Demo, right click to see the page source.
User Environment Check
Since you need to use the Web3.js API to transfer money within the page, you should first check whether the wallet is installed in the browser environment and the wallet should be unlocked.
- First check if MetaMask wallet is installed:
window.addEventListener('load'.function() {
if (typeofweb3 ! = ='undefined') {
web3 = new Web3(web3.currentProvider);
if (web3.currentProvider.isMetaMask == true) {
// "MetaMask available"
} else {
// "non-metamask environment"}}else{$("#env").html("No web3? MetaMask!"); }}Copy the code
It is recommended to check the MetaMask when the window is loaded. Of course, if MetaMask is not installed, you can also specify a node Provider to create Web3. You can refer to the web3.js document to introduce Web3
- Check if wallet has been unlocked: Before sending transactions, we should first check the status of the current wallet to check whether the wallet is unlocked (whether the password is entered into MetaMask). Usually, getAccounts under ETH is used to check, getAccounts is a list of accounts that will be returned. If there is data in the current account list, it means that the wallet has been unlocked and the account can be obtained. If the account list is empty, it means that the wallet has not been unlocked.
We can add the following code to the listener function above:
web3.eth.getAccounts(function (err, accounts) {
if (accounts.length == 0) {$("#account").html("Please check if your wallet is unlocked."); }});Copy the code
Send a deal
If the MetaMask wallet is unlocked, we can send the transaction using sendTransaction.
web3.eth.sendTransaction(transactionObject [, callback])
Copy the code
The second argument is the Hash value that the callback function uses to get the transaction sent.
The first parameter is a transaction object, which has several fields:
- From: indicates the account from which the amount is sent
- To: indicates the account to be launched
- Value is the amount of money to be sent
- Gas: Sets the gas limit
- GasPrice: Sets the gas price
If “from” does not exist, it will use the current default account. If “to” and “value” are mandatory fields. An authorization window for MetaMask pops up when the transaction is sent. If gas and gasPrice are not set, they can be set in MetaMask. If the two gas and gas Price are set, MetaMask will use the gas we set.
Therefore, when sending a transaction, the key is to construct such a transaction object, JavaScrpt code is as follows:
// Use the gas Limit and gas price given by Metamask
var fromAccount = $('#fromAccount').val();
var toAccount = $('#toAccount').val();
var amount = $('#amount').val();
// Do a check on the input number
if(web3.isAddress(fromAccount) && web3.isAddress(toAccount) && amount ! =null && amount.length > 0) {var message = {from: fromAccount, to:toAccount, value: web3.toWei(amount, 'ether')};
web3.eth.sendTransaction(message, (err, res) => {
var output = "";
if(! err) { output += res; }else {
output = "Error"; }}}Copy the code
$(‘#fromAccount’).val() is used with JQuery to retrieve user input, and web3.isAddress is used to check if the string is an address before the transaction is actually constructed. In addition, for a transfer to a common external address account, the gas consumption is fixed at 21000.
Run the test
It is important to note that, for security reasons, MetaMask only supports site-accessible pages, i.e. pages accessed through http://, and files :// + file addresses in browsers are not available. So put your code in a directory on your Web server and try it out yourself.
Online Demo address for web3. Learnblockchain. Cn/transDemo. H…
Want to have a good system to learn ethereum DApp development, this video course ethereum DApp development combat should not be missed.
Blockchain in Simple terms – systematic learning of blockchain to create the best blockchain technology blog. Blockchain knowledge planet, the most professional blockchain problem technology community, welcome to join, as star friends benefits, star friends can also join me to create high-quality blockchain technology group, the group gathered more than 300 block chain technology heroes and enthusiasts.