BlockChain區塊鏈
  • 本書簡介
  • 區塊鏈運作原理
  • Bitcoin介紹
    • 簡介
    • Bitcoin其他知識
  • Bitcoin原理與實作
  • BitcoinJS
    • BTC 地址格式種類
    • 從 Mnemonic 轉為地址
  • Serverless 架構實作
  • Docker常用指令
  • ethereum初探
    • ethereum歷史
    • EVM
  • ethereum PoS 節點架設
  • ethereum(Docker)
  • ethereum(Geth)
    • Parity
  • ethereum(智能合約)
    • 合約測試 Unit Test
    • DAO
    • 可升級合約
    • 使用合約進行 multiswap
    • 合約安全
    • 開發工具
    • Hardhat 教學
      • Hardhat 寫測試
    • ERC-721 範例
      • 白名單機制
    • OpenZeppelin 合約 library
    • Truffle
    • 合約部屬
    • solidity 教學
  • ethereum(Dapp)
    • 相關 SDK
    • Multicall
    • Ethers.js 使用
    • Remix IDE
    • web3.js 使用
    • 在網頁上使用 web3 並操作區塊鏈
      • solidity筆記
  • Hyperledger Fabric
  • blockchainDB
  • 挖礦程式使用教學
    • 門羅幣/Monero (XMR)
  • Bitfinex API 使用
  • FTX API
  • CCXT 通用交易所 API
  • Solana 教學
  • Ethereum BigQuery
  • The Graph
    • yaml 定義
    • mapping 語法
    • Schema 定義
    • Query 範例
    • Unit test
  • DeFi 筆記
    • MEV 相關
    • Dex 聚合
    • Yearn
    • Curve
    • Uniswap
      • Swap 互動
    • AAVE、Compound
      • Compound 原理
      • AAVE 合約開發
Powered by GitBook
On this page
  • 獲取地址餘額
  • 獲取 function gas 與 gas price
  • 時間機器
  • Event 參數
  • 測試 Require

Was this helpful?

  1. ethereum(智能合約)
  2. Hardhat 教學

Hardhat 寫測試

獲取地址餘額

const ownerAddress = await owner.getAddress();
const initialOwnerBalance = await ethers.provider.getBalance(ownerAddress);

獲取 function gas 與 gas price

現在的 etherjs v6 版本使用 js 原生 BIgInt 即可。

// 呼叫 function 後獲取 receipt,即可獲取到 gasUser, gasPrice
const stakeTx = await staker.connect(owner).stake();
const stakeReceipt = await stakeTx.wait();
const stakeGasUsed = BigInt(stakeReceipt.gasUsed) * BigInt(stakeReceipt.gasPrice);
it("Should unstake correctly after the unbonding period", async function () {
    const ownerAddress = await owner.getAddress();
    const initialOwnerBalance = await ethers.provider.getBalance(ownerAddress);

    // Stake
    const stakeTx = await staker.connect(owner).stake({ value: ethers.parseEther("1") });
    const stakeReceipt = await stakeTx.wait();

    const stakeGasUsed = BigInt(stakeReceipt.gasUsed) * BigInt(stakeReceipt.gasPrice);
    const afterStakeBalance = BigInt(initialOwnerBalance) - BigInt(ethers.parseEther("1")) - BigInt(stakeGasUsed);

    expect(await ethers.provider.getBalance(ownerAddress)).to.equal(afterStakeBalance);
  });

時間機器

可設置當前時間

// Fast forward time by 7 days for testing
await ethers.provider.send("evm_increaseTime", [7 * 24 * 60 * 60]);
await ethers.provider.send("evm_mine");

Event 參數

記得 await 放在 expect 前

await expect(<Contract instance>.connect(addr1).test(tokenId)).to.emit(<Contract instance>, <Event name>)
.withArgs(addr1.address, tokenId, 1);

測試 Require

await expect(<Contract instance>.connect(addr1).test(tokenId))
.to.be.revertedWith(<require 後的第二個參數>);
PreviousHardhat 教學NextERC-721 範例

Last updated 1 year ago

Was this helpful?