Integrasi TypeChain
Penjelasan
TypeChain adalah tool yang menghasilkan definisi tipe TypeScript otomatis dari ABI contract hasil kompilasi, memberi type-safety penuh saat memanggil fungsi contract dari kode TypeScript — nama fungsi, tipe parameter, dan tipe return value semuanya tervalidasi oleh compiler TypeScript, mengurangi kesalahan seperti salah nama fungsi atau salah tipe argumen yang baru ketahuan saat runtime. Di project Hardhat, TypeChain terintegrasi lewat plugin `@typechain/hardhat` yang otomatis menghasilkan file typing di folder `typechain-types/` setiap kali `npx hardhat compile` dijalankan, tanpa langkah manual tambahan setelah instalasi dan konfigurasi awal.
Contoh Konsep
// hardhat.config.ts
import "@typechain/hardhat";
// Setelah `npx hardhat compile`, typing otomatis tersedia:
import { Counter__factory } from "../typechain-types";
import { ethers } from "hardhat";
async function main() {
const factory: Counter__factory = await ethers.getContractFactory("Counter");
const counter = await factory.deploy();
// TypeScript tahu persis tipe parameter dan return value
await counter.setNumber(42n);
const value: bigint = await counter.number();
}
Praktikum
Install plugin @typechain/hardhat pada project TypeScript, tambahkan importnya di hardhat.config.ts, lalu jalankan compile dan cek folder typechain-types yang dihasilkan.
Ketik/edit bebas di sini untuk latihan — kode ini tidak dijalankan.
Tips
Commit folder typechain-types ke .gitignore, bukan ke repository — folder ini selalu regenerasi otomatis saat compile, sama seperti artifacts/.