1. 트랜잭션 라이프사이클 처리

1.1. 왜 중요할까요?

스마트 컨트랙트 상호작용에서 가장 취약한 부분은 트랜잭션 전송 속도와 노드로부터 결과를 반환받기까지 대기하는 시간입니다. 이는 사용자 경험(UX)에 큰 영향을 미치는 특성입니다. 트랜잭션은 오류, 런타임 되돌리기(revert), 가스 부족 등의 문제를 겪을 수 있으므로, 사용자 인터페이스를 설계할 때는 사용자가 현재 상태를 명확히 알 수 있도록 전체 트랜잭션 라이프사이클을 세심하게 처리해야 합니다.

1.2. Wagmi는 어떤 역할을 하나요?

Wagmi의 React 훅은 트랜잭션 라이프사이클을 관리하는 데 도움이 되는 다양한 기능을 제공합니다. 예:

useReadContract

Wagmi의 useReadContract 훅은 호출 시 데이터를 반환합니다 함수 변경 없이 상태. 또한, 이 훅은 상태 객체도 반환하므로(예: error, 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 스마트 컨트랙트의 함수 을(를) 변경하는 상태 을(를) 호출한 후의 트랜잭션

데이터
`WriteContractReturnType | undefined`

기본값은 `undefined`
마지막으로 성공적으로 해결된 데이터 변경 변경에 대한

또한, 이 훅은 트랜잭션의 대기 상태를 표시하는 데 사용할 수 있는 isPending 객체도 반환합니다.

또한, Wagmi는 2개의 반환 변수와 함께 트랜잭션 결과를 대기할 수 있는 useWaitForTransactionReceipt 훅도 제공합니다: 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>
  )
}