返回章节列表
第 04 章进阶
写入合约与交易处理
发送交易、处理交易状态和 Gas 估算
6 课时3小时
概述
写入链上数据需要发送交易。本章讲解完整的交易生命周期管理。
交易生命周期
一笔交易的完整流程: 1. **准备阶段**: 构造交易参数、估算 Gas 2. **签名阶段**: 用户在钱包中确认签名 3. **广播阶段**: 交易发送到网络 4. **确认阶段**: 等待区块确认 5. **完成阶段**: 交易被打包,状态更新
代码示例
ERC20 代币转账
完整的 ERC20 转账组件,包含状态管理和错误处理
typescript
1'use client'2 3import { useWriteContract, useWaitForTransactionReceipt } from 'wagmi'4import { parseUnits } from 'viem'5import { useState } from 'react'6 7const erc20Abi = [8 {9 name: 'transfer',10 type: 'function',11 stateMutability: 'nonpayable',12 inputs: [13 { name: 'to', type: 'address' },14 { name: 'amount', type: 'uint256' },15 ],16 outputs: [{ type: 'bool' }],17 },18] as const19 20export function TransferToken() {21 const [to, setTo] = useState('')22 const [amount, setAmount] = useState('')23 24 const { writeContract, data: hash, isPending, error } = useWriteContract()25 26 const { isLoading: isConfirming, isSuccess } = useWaitForTransactionReceipt({27 hash,28 })29 30 async function handleTransfer() {31 writeContract({32 address: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48',33 abi: erc20Abi,34 functionName: 'transfer',35 args: [to as `0x${string}`, parseUnits(amount, 6)],36 })37 }38 39 return (40 <div className="space-y-4">41 <input42 placeholder="接收地址"43 value={to}44 onChange={(e) => setTo(e.target.value)}45 className="w-full p-2 border rounded"46 />47 <input48 placeholder="数量"49 value={amount}50 onChange={(e) => setAmount(e.target.value)}51 className="w-full p-2 border rounded"52 />53 <button54 onClick={handleTransfer}55 disabled={isPending || isConfirming}56 className="w-full py-2 bg-blue-500 text-white rounded disabled:opacity-50"57 >58 {isPending ? '等待签名...' : isConfirming ? '确认中...' : '转账'}59 </button>60 {isSuccess && (61 <p className="text-green-500">62 交易成功!63 <a href={`https://etherscan.io/tx/${hash}`} target="_blank">64 查看交易65 </a>66 </p>67 )}68 {error && <p className="text-red-500">{error.message}</p>}69 </div>70 )71}