Ta có thể sử dụng CDN của Web3.js hoặc cài đặt thông qua câu lệnh sau:
yarn add web3
Ganache Network
Sử dụng đoạn code sau để kết nối đến Ganache network:
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider(`http://127.0.0.1:7545/`));
// Log the current block number to the console
web3.eth
.getBlockNumber()
.then((result: string) => {
console.log('Current block number: ' + result);
})
.catch((error: any) => {
console.error(error);
});
Chạy đoạn code trên để thực hiện kết nối.
Sepolia Network
Nếu muốn sử dụng Sepolia testnet thông qua Infura provider1 thì code như sau:
require('dotenv').config();
const { INFURA_API_KEY } = process.env;
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider(`https://sepolia.infura.io/v3/${INFURA_API_KEY}`));
// Log the current block number to the console
web3.eth
.getBlockNumber()
.then((result: string) => {
console.log('Current block number: ' + result);
})
.catch((error: any) => {
console.error(error);
});
Do Infura không hỗ trợ ký giao dịch nên cần thêm vào một tài khoản vào local wallet2 để thực hiện việc đó:
require('dotenv').config();
const { INFURA_API_KEY, PRIVATE_KEY } = process.env;
const Web3 = require('web3');
// Add an account to wallet
const account = web3.eth.accounts.wallet.add(PRIVATE_KEY);
Footnotes
-
Tham khảo thêm về cách thiết lập Infura provider: Infura Provider. ↩
-
Tham khảo: Using Local Wallet | web3.js (web3js.org) ↩