1. 处理交易生命周期
1.1. 为什么这很重要?
与智能合约交互的最薄弱环节在于发送交易的速度以及等待节点返回结果的时长。这是一个严重影响用户体验(UX)的特征。交易可能会遇到错误、回滚、Gas 不足等问题,因此在设计用户界面时,我们必须妥善处理整个交易生命周期,以便用户能够清晰了解当前状态。
1.2. Wagmi 的作用是什么?
Wagmi 中的 React Hooks 具备许多功能,可帮助你管理交易生命周期。例如:
useReadContract
Wagmi 的 useReadContract hook 会在调用 函数 时返回数据,且不会改变 state。此外,该 hook 还会返回一个状态对象(例如 错误, 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 hook 在调用会更改智能合约 data 的 hash 后,会返回一个包含交易 函数 对象。 state 的
data
`WriteContractReturnType | undefined`
默认为 `undefined`
该 mutation 上一次成功解析的 data。此外,该 hook 还为我们返回一个 isPending 对象,我们可以利用它来显示交易的挂起(pending)状态。
此外,Wagmi 还提供了一个 useWaitForTransactionReceipt Hook,用于等待交易结果,它包含 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>
)
}