Lanjut ke konten utama

Menyiapkan web3.js untuk menggunakan blockchain Ethereum di JavaScript

web3.jsjavascript
Pemula
jdourlens
EthereumDev(opens in a new tab)
11 April 2020
3 bacaan singkat minute read
comp-tutorial-metadata-tip-author 0x19dE91Af973F404EDF5B4c093983a7c6E3EC8ccE

Dalam tutorial ini, kita akan melihat cara memulai web3.js(opens in a new tab) untuk berinteraksi dengan blockchain Ethereum. Web3.js dapat digunakan baik di frontend maupun backend untuk membaca data dari blockchain atau membuat transaksi dan bahkan menggunakan kontrak pintar.

Langkah pertama adalah memasukkan web3.js dalam proyek Anda. Untuk menggunakannya dalam halaman web, Anda dapat mengimpor pustakanya secara langsung menggunakan CDN seperti JSDeliver.

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

Jika Anda lebih suka menginstal pustaka untuk menggunakannya di backend Anda atau proyek frontend yang menggunakan build, Anda dapat menginstalnya menggunakan 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")
Salin

Karena kita memasukkan pustaka dalam proyek, kita perlu menginisialisasinya. Your project needs to be able to communicate with the blockchain. Kebanyakan pustaka Ethereum berkomunikasi dengan node melalui pemanggilan RPC. To initiate our Web3 provider, we’ll instantiate a Web3 instance passing as the constructor the URL of the provider. Jika Anda memiliki node atau instance ganache yang beroperasi di komputer Anda(opens in a new tab) itu akan tampak seperti ini:

1const web3 = new Web3("http://localhost:8545")
Salin

If you’d like to directly access a hosted node you can use Infura or the free ones provided by Cloudflare(opens in a new tab):

1const web3 = new Web3("https://cloudflare-eth.com")
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})
Salin

Jika Anda mengeksekusi program ini, ini hanya akan mencetak nomor blok terakhir: bagian teratas dari 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()
Salin

You can see all the functions available on the Web3 instance in the official web3.js documentation(opens in a new tab).

Kebanyakan dari pustaka Web3 bersifat asinkron karena pada latar belakang, pustaka membuat JSON RPC memanggil node yang mengirimkan kembali hasilnya.

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. Nantinya dompet ini akan memungkinkan Anda membaca saldo pengguna dan mengaktifkannya untuk memvalidasi transaksi yang Anda ingin dilakukannya di blockchain Ethereum:

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 // Accounts now exposed
7 } catch (error) {
8 // User denied account access...
9 }
10}
Tampilkan semua
Salin

Alternatif untuk web3.js seperti Ethers.js(opens in a new tab) memang ada tetapi kami akan memfokuskan semua tutorial JavaScript kami untuk web3.js karena ini adalah pustaka resmi untuk berinteraksi dengan Ethereum di browser. Dalam tutorial berikutnya, kita akan melihat cara mudah untuk mendengar blok yangbaru masuk di blockchain dan melihat apa isinya(opens in a new tab).

Terakhir diedit: @yeremiaryangunadi(opens in a new tab), 16 Januari 2024

Apakah tutorial ini membantu?