1. 거래 수명 주기 처리

1.1. 왜 중요한가?

스마트 계약과 상호작용할 때 가장 취약한 부분은 트랜잭션 전송 속도와 노드로부터 결과가 반환되기를 기다리는 시간입니다. 이는 사용자 경험(UX)에 큰 영향을 미치는 특성입니다. 트랜잭션은 오류, 리버트, 가스 부족 등의 문제를 겪을 수 있으므로, 사용자 인터페이스를 설계할 때는 사용자가 현재 상태를 명확히 알 수 있도록 트랜잭션의 전체 수명 주기를 처리하는 데 주의를 기울여야 합니다.

1.2. Wagmi는 무엇을 하는가?

Wagmi의 React Hooks는 트랜잭션 라이프사이클 관리를 돕는 다양한 기능을 제공합니다. 예:

사용약관

와그미의 사용약관 호크는 호출 시 데이터를 반환합니다 함수 변경하지 않고 상태또한, 훅은 상태 객체(예: 오류, 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>
  )
}

사용계약서

와그미의 사용계약서 훅은 우리에게 반환합니다 데이터 포함하는 객체 해시 호출 후 거래의 함수 그것이 바꾸는 상태 스마트 계약의

데이터
`WriteContractReturnType | undefined`

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

또한, 이 훅은 또한 우리에게 반환합니다. isPending 거래의 보류 상태를 표시하는 데 사용할 수 있는 객체.

또한 Wagmi는 다음과 같은 서비스도 제공합니다. useWaitForTransactionReceipt 트랜잭션 결과를 기다리기 위한 훅 함수, 두 개의 반환 변수를 가짐: isLoading, 성공 여부.

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>
  )
}