const { expect } =require("chai");const { ethers } =require("hardhat");describe("Greeter12",function () {it("Should return the new greeting once it's changed",asyncfunction () {constGreeter=awaitethers.getContractFactory("Greeter");// const greeter = await Greeter.deploy("Hello, world!");// await greeter.deployed();//expect(await greeter.greet()).to.equal("Hello, world!");constgreeter=awaitGreeter.attach("0x5FbDB2315678afecb367f032d93F642f64180aa3");constsetGreetingTx=awaitgreeter.setGreeting("Hola, mundo!");// wait until the transaction is minedawaitsetGreetingTx.wait();consta=awaitgreeter.greet()//console.log(a)expect(awaitgreeter.greet()).to.equal("Hola, mundo!"); });});
之後輸入
npx hardhat test --network localhost
Artifacts
部署合約或 compile 後會產生此資料夾,裡面包含一些 json 檔案,為合約的 ABI
使用 Mainnet fork 測試
使用 mainnet 特定 block data 來測試合約
例如以下獲取主網特定地址的 USDC 餘額
const { ethers } =require("hardhat");const { expect } =require("chai");describe("USDC Balance Check",function () {it("Should return the USDC balance of the address",asyncfunction () {constusdcAddress="0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"; // USDC Contract AddressconstaddressToCheck="0x7713974908Be4BEd47172370115e8b1219F4A5f0"; // Address whose balance you want to check// USDC Contract ABI (Simplified; use the full ABI from Etherscan)constusdcAbi= ["function balanceOf(address owner) view returns (uint256)"];// Connect to the USDC contractconstusdcContract=newethers.Contract(usdcAddress, usdcAbi,ethers.provider);// Fetch the balanceconstbalance=awaitusdcContract.balanceOf(addressToCheck);// Log the balance (optional)console.log("USDC Balance:",balance.toString());// 也可手動改變地址 ETH 餘額constmainnetAccount= addressToCheck; // Replace with a mainnet account addressawaithre.network.provider.request({ method:"hardhat_impersonateAccount", params: [mainnetAccount], });awaithre.network.provider.send("hardhat_setBalance", [ mainnetAccount,"0x8AC7230489E80000000",// 40960 ETH ]);constethBalance=awaitethers.provider.getBalance(addressToCheck);// Log the balance (optional)console.log("ETH Balance:",ethers.formatEther(ethBalance),"ETH");// Assert (for example, checking if the balance is greater than a certain amount)expect(balance).to.be.gt(ethers.parseUnits("100",6)); // Check if balance is greater than 100 USDC });});
測試檔案內設置區塊時間
const { ethers } =require("hardhat");// Fast forward time by 7 days for testingawaitethers.provider.send("evm_increaseTime", [7*24*60*60]);awaitethers.provider.send("evm_mine");
import { ethers } from"hardhat";asyncfunctionmain() {constEthStaker=awaitethers.deployContract("EthStaker");awaitEthStaker.waitForDeployment();console.log(`EthStaker deployed to ${EthStaker.target}` );}// We recommend this pattern to be able to use async/await everywhere// and properly handle errors.main().catch((error) => {console.error(error);process.exitCode =1;});
之後輸入
npx hardhat run scripts/deploy.ts --network someTestnet