Langkau ke kandungan utama

Bantu menterjemahkan halaman ini

๐ŸŒ

Anda sedang melihat halaman ini dalam Bahasa Inggeris kerana kami belum menterjemahkannya lagi. Bantu kami untuk menterjemahkan kandungan ini.

Halaman terjemahan

No bugs here!๐Ÿ›

This page is not being translated. We've intentionally left this page in English for now.

Set up web3.js to use the Ethereum blockchain in JavaScript

web3.js
javascript
Beginner
โœ๏ธjdourlens
๐Ÿ“šEthereumDev
๐Ÿ“†11 April 2020
โฑ๏ธ3 minute read
Tip author 0x19dE91Af973F404EDF5B4c093983a7c6E3EC8ccE

In this tutorial, weโ€™ll see how to get started with web3.js to interact with the Ethereum blockchain. Web3.js can be used both in frontends and backends to read data from the blockchain or make transactions and even deploy smart contracts.

The first step is to include web3.js in your project. To use it in a web page, you can import the library directly using a CDN like JSDeliver.

1<script src="https://cdn.jsdelivr.net/npm/web3@latest/dist/web3.min.js"></script>
2

If you prefer installing the library to use in your backend or a frontend project that uses build you can install it using npm:

npm install web3 --save

Then to import Web3.js into a Node.js script or Browserify frontend project, you can use the following line of JavaScript:

1const Web3 = require("web3")
2
๐Ÿ“‹ Salin

Now that we included the library in the project we need to initialize it. Your project needs to be able to communicate with the blockchain. Most Ethereum librairies communicate with a node through RPC calls. To initiate our Web3 provider, weโ€™ll instantiate a Web3 instance passing as the constructor the URL of the provider. If you have a node or ganache instance running on your computer it will look like this:

1const web3 = new Web3("http://localhost:8545")
2
๐Ÿ“‹ Salin

If youโ€™d like to directly access a hosted node you can use Infura or the free ones provided by Cloudflare:

1const web3 = new Web3("https://cloudflare-eth.com")
2
๐Ÿ“‹ Salin

To test that we correctly configured our Web3 instance, weโ€™ll try to retrieve the latest block number using the getBlockNumber function. This function accepts a callback as a parameter and returns the block number as an integer.

1var Web3 = require("web3")
2const web3 = new Web3("https://cloudflare-eth.com")
3
4web3.eth.getBlockNumber(function (error, result) {
5 console.log(result)
6})
7
๐Ÿ“‹ Salin

If you execute this program, it will simply print the latest block number: the top of the blockchain. You can also use await/async function calls to avoid nesting callbacks in your code:

1async function getBlockNumber() {
2 const latestBlockNumber = await web3.eth.getBlockNumber()
3 console.log(latestBlockNumber)
4 return latestBlockNumber
5}
6
7getBlockNumber()
8
๐Ÿ“‹ Salin

You can see all the functions available on the Web3 instance in the official web3.js documentation.

Most of Web3 libraries are asynchronous because in the background the library makes JSON RPC calls to the node which send backs the result.

If you are working in the browser, some wallets directly inject a Web3 instance and you should try to use it whenever possible especially if you plan to interact with the userโ€™s Ethereum address to make transactions.

Here is the snippet to detect if a MetaMask wallet is available and try to enable it if it is. It will later allow you to read the userโ€™s balance and enable them to validate transactions youโ€™d like to make them do on the Ethereum blockchain:

1if (window.ethereum != null) {
2 state.web3 = new Web3(window.ethereum)
3 try {
4 // Request account access if needed
5 await window.ethereum.enable()
6 // Acccounts now exposed
7 } catch (error) {
8 // User denied account access...
9 }
10}
11
Tunjukkan semua
๐Ÿ“‹ Salin

Alternatives to web3.js like Ethers.js do exist but weโ€™ll focus all our JavaScript tutorials on web3.js as it is the official library to interact with Ethereum in the browser. In the next tutorial weโ€™ll see how to easily listen to new incoming blocks on the blockchain and see what they contains.

Suntingan terakhir: , Invalid DateTime
Edit halaman

Was this page helpful?

Kali terakhir laman web dikemas kini: 23 September 2022

Guna Ethereum

  • Cari dompet
  • Dapatkan ETH
  • Aplikasi tidak berpusat (dapps)
  • Layer 2
  • Jalankan nod
  • Stablecoins
  • Stake ETH

Ekosistem

  • Hab komuniti
  • Yayasan Ethereum
  • Blog Yayasan Ethereum
  • Program Bantuan Ekosistem
  • Ethereum bug bounty program
  • Program Geran Ekosistem
  • Aset Jenama Ethereum
  • Devcon