About Me
En

/

Vi
Học blockchain P3

Học blockchain P3

Học blockchain P3

🔧 GIAI ĐOẠN 3: KẾT NỐI FRONTEND VỚI BLOCKCHAIN


1. Giới thiệu Ethers.js

  • Ethers.js là thư viện JavaScript giúp kết nối DApp với blockchain qua Ethereum JSON-RPC API.

  • Ưu điểm:

    • Nhẹ và dễ dùng hơn Web3.js.
    • Hỗ trợ TypeScript tốt.
    • Tích hợp sẵn nhiều tiện ích: format ETH, quản lý wallet, parse ABI.

📦 Cài đặt:

npm install ethers

2. Kết nối ví (MetaMask)

Khi người dùng mở DApp, ta cần kết nối với ví để lấy quyền ký giao dịch.

import { ethers } from "ethers"; async function connectWallet() { if (window.ethereum) { const provider = new ethers.BrowserProvider(window.ethereum); await provider.send("eth_requestAccounts", []); // yêu cầu quyền truy cập ví const signer = await provider.getSigner(); console.log("Đã kết nối ví:", await signer.getAddress()); } else { console.log("Vui lòng cài MetaMask"); } }

📌 Lưu ý:

  • eth_requestAccounts mở popup MetaMask yêu cầu user approve.
  • signer đại diện cho user đã kết nối và có thể ký giao dịch.

3. Gửi Transaction

Ví dụ gửi 0.01 ETH từ ví người dùng đến địa chỉ khác:

async function sendTransaction() { const provider = new ethers.BrowserProvider(window.ethereum); const signer = await provider.getSigner(); const tx = await signer.sendTransaction({ to: "0x1234...abcd", // địa chỉ nhận value: ethers.parseEther("0.01") }); console.log("Hash giao dịch:", tx.hash); await tx.wait(); // đợi xác nhận console.log("Giao dịch thành công"); }

4. Gọi hàm Smart Contract

Giả sử contract có ABI và địa chỉ:

const contractAddress = "0xABC123..."; const abi = [ "function getValue() public view returns (uint)", "function setValue(uint _value) public" ]; async function callContract() { const provider = new ethers.BrowserProvider(window.ethereum); const signer = await provider.getSigner(); const contract = new ethers.Contract(contractAddress, abi, signer); // Gọi hàm view (không tốn gas) const value = await contract.getValue(); console.log("Giá trị hiện tại:", value.toString()); // Gọi hàm thay đổi state (tốn gas) const tx = await contract.setValue(42); await tx.wait(); console.log("Đã set value thành 42"); }

5. Lắng nghe Event từ Smart Contract

Nếu contract có event:

event ValueChanged(uint newValue);

Ta lắng nghe từ frontend:

async function listenEvent() { const provider = new ethers.BrowserProvider(window.ethereum); const contract = new ethers.Contract(contractAddress, abi, provider); contract.on("ValueChanged", (newValue) => { console.log("Sự kiện: Giá trị mới =", newValue.toString()); }); }

📌 Lưu ý:

  • Lắng nghe event cần provider không sign (để không popup MetaMask).
  • Event được bắt theo thời gian thực khi blockchain emit.

6. Thực hành mini DApp

  • Bước 1: Deploy smart contract Counter trên Remix.
  • Bước 2: Copy ABI + contract address.
  • Bước 3: Viết HTML + JS frontend dùng Ethers.js.
  • Bước 4: Test tăng giảm counter và xem event.

7. 📚 Tài liệu

Learn blockchain part3

Learn blockchain part3

🔧 GIAI ĐOẠN 3: KẾT NỐI FRONTEND VỚI BLOCKCHAIN


1. Giới thiệu Ethers.js

  • Ethers.js là thư viện JavaScript giúp kết nối DApp với blockchain qua Ethereum JSON-RPC API.

  • Ưu điểm:

    • Nhẹ và dễ dùng hơn Web3.js.
    • Hỗ trợ TypeScript tốt.
    • Tích hợp sẵn nhiều tiện ích: format ETH, quản lý wallet, parse ABI.

📦 Cài đặt:

npm install ethers

2. Kết nối ví (MetaMask)

Khi người dùng mở DApp, ta cần kết nối với ví để lấy quyền ký giao dịch.

import { ethers } from "ethers"; async function connectWallet() { if (window.ethereum) { const provider = new ethers.BrowserProvider(window.ethereum); await provider.send("eth_requestAccounts", []); // yêu cầu quyền truy cập ví const signer = await provider.getSigner(); console.log("Đã kết nối ví:", await signer.getAddress()); } else { console.log("Vui lòng cài MetaMask"); } }

📌 Lưu ý:

  • eth_requestAccounts mở popup MetaMask yêu cầu user approve.
  • signer đại diện cho user đã kết nối và có thể ký giao dịch.

3. Gửi Transaction

Ví dụ gửi 0.01 ETH từ ví người dùng đến địa chỉ khác:

async function sendTransaction() { const provider = new ethers.BrowserProvider(window.ethereum); const signer = await provider.getSigner(); const tx = await signer.sendTransaction({ to: "0x1234...abcd", // địa chỉ nhận value: ethers.parseEther("0.01") }); console.log("Hash giao dịch:", tx.hash); await tx.wait(); // đợi xác nhận console.log("Giao dịch thành công"); }

4. Gọi hàm Smart Contract

Giả sử contract có ABI và địa chỉ:

const contractAddress = "0xABC123..."; const abi = [ "function getValue() public view returns (uint)", "function setValue(uint _value) public" ]; async function callContract() { const provider = new ethers.BrowserProvider(window.ethereum); const signer = await provider.getSigner(); const contract = new ethers.Contract(contractAddress, abi, signer); // Gọi hàm view (không tốn gas) const value = await contract.getValue(); console.log("Giá trị hiện tại:", value.toString()); // Gọi hàm thay đổi state (tốn gas) const tx = await contract.setValue(42); await tx.wait(); console.log("Đã set value thành 42"); }

5. Lắng nghe Event từ Smart Contract

Nếu contract có event:

event ValueChanged(uint newValue);

Ta lắng nghe từ frontend:

async function listenEvent() { const provider = new ethers.BrowserProvider(window.ethereum); const contract = new ethers.Contract(contractAddress, abi, provider); contract.on("ValueChanged", (newValue) => { console.log("Sự kiện: Giá trị mới =", newValue.toString()); }); }

📌 Lưu ý:

  • Lắng nghe event cần provider không sign (để không popup MetaMask).
  • Event được bắt theo thời gian thực khi blockchain emit.

6. Thực hành mini DApp

  • Bước 1: Deploy smart contract Counter trên Remix.
  • Bước 2: Copy ABI + contract address.
  • Bước 3: Viết HTML + JS frontend dùng Ethers.js.
  • Bước 4: Test tăng giảm counter và xem event.

7. 📚 Tài liệu

Tag

Buy Me A Coffee
    Blockchain