1. トランザクションライフサイクルのハンドリング

1.1. なぜ重要なのか?

スマートコントラクト操作における最大の弱点は、トランザクションの送信速度とノードからの結果返却を待つ時間です。これはユーザー体験(UX)に大きな影響を与える特性です。トランザクションは、エラー、リバート、ガス代不足などの問題に直面する可能性があるため、ユーザーインターフェースを設計する際には、ユーザーが現在のステータスを明確に把握できるように、トランザクションのライフサイクル全体を適切に処理する必要があります。

1.2. Wagmiの役割とは?

WagmiのReact Hooksには、トランザクションライフサイクルの管理を容易にする多くの機能が備わっています。例:

useReadContract

Wagmiの useReadContract フックは、呼び出し時にデータを返します function 変更することなく 状態。さらに、このフックはステータスオブジェクトも返します(例: エラー, isPending)。これにより、ユーザーに対応するトランザクションのステータスを表示できます。

// import BaseError and hook useReadContract
import { type BaseError, useReadContract } from 'wagmi'
// import the smart contract's abi file to get the function's interface
import { abi } from './abi'

function ReadContract() {
  const { 
    data: balance, // assign the returned data to the balance variable
    error, // initialize error variable
    isPending // initialize the isPending variable
  } = useReadContract({
    abi, // abi của function
    functionName: 'balanceOf', // function name you want to call
    args: ['0x03A71968491d55603FFe1b11A9e23eF013f75bCF'], // Pass variables to the function
  })
  
  // If isPending is true, the text "Loading..." is displayed, otherwise it disappears
  if (isPending) return <div>Loading...</div> 
  
  // If there is an error, display the div with error message
  if (error) 
    return ( 
      <div>
        Error: {(error as BaseError).shortMessage || error.message} 
      </div> 
    )  

  return (
    // Displays the balance (if any) after converting to string format
    <div>Balance: {balance?.toString()}</div>
  )
}

useWriteContract

Wagmiの useWriteContract フックは、 data オブジェクトを返します。これには、 hash を呼び出してスマートコントラクトの function を変更した後の 状態 が含まれます。

データ
`WriteContractReturnType | undefined`

デフォルト値: `undefined`
ミューテーションにおいて最後に正常に解決されたデータ。for

さらに、このフックは isPending オブジェクトも返します。これを使用して、トランザクションの保留中のステータスを表示できます。

さらに、Wagmiは以下も提供しています useWaitForTransactionReceipt トランザクション結果を待機するためのフックで、2つの戻り値を返します: isLoading, isSuccess.

以下はWagmi v2のドキュメントからの引用例です:

import * as React from 'react' // import react into file
// import BaseError, and 2 hooks useWaitForTransactionReceipt, useWriteContract from wagmi library
import { 
  type BaseError, 
  useWaitForTransactionReceipt, 
  useWriteContract 
} from 'wagmi'
// import the smart contract's abi file to get the function's interface
import { abi } from './abi'
 
export function MintNFT() {
  const { 
    data: hash, // assign the returned data to a variable named hash
    error, // assign error object to error variable
    isPending, // assign the isPending object to the isPending variable
    writeContract // initialize the writeContract function for use
  } = useWriteContract() 

  // function dùng để submit form
  async function submit(e: React.FormEvent<HTMLFormElement>) { 
    e.preventDefault() 
    const formData = new FormData(e.target as HTMLFormElement) 
    const tokenId = formData.get('tokenId') as string 
    writeContract({
      address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2', // contract address
      abi, // abi of contract
      functionName: 'mint', // function name you want to call
      args: [BigInt(tokenId)], // pass input to function
    })
  } 

  // Call the useWaitForTransactionReceipt hook to initialize the isConfirming and isConfirmed states
  const { isLoading: isConfirming, isSuccess: isConfirmed } = 
    useWaitForTransactionReceipt({ 
      hash, 
    }) 

  // Return format of React
  return (
    <form onSubmit={submit}>
      <input name="address" placeholder="0xA0Cf…251e" required />
      <input name="value" placeholder="0.05" required />
      // If isPending is true, the button will be disabled
      <button 
        disabled={isPending} 
        type="submit"
      >
        {isPending ? 'Confirming...' : 'Mint'} 
        // If isPending is true, display the word "Confirming...", otherwise display the word "Mint"
      </button>
      // If hash is true, the div containing the transaction hash is displayed, otherwise it disappears
      {hash && <div>Transaction Hash: {hash}</div>}
      // If isConfirming is true then display the div with the text "Waiting for confirmation..."
      {isConfirming && <div>Waiting for confirmation...</div>} 
      // If isConfirmed is true, display the div with the text "Transaction confirmed."
      {isConfirmed && <div>Transaction confirmed.</div>}
      // If there is an error, display the div with error message
      {error && ( 
        <div>Error: {(error as BaseError).shortMessage || error.message}</div> 
      )} 
    </form>
  )
}