Files
wagmi-lesson/app/pages/home/HomePage.tsx
2026-03-11 00:10:38 +01:00

82 lines
2.7 KiB
TypeScript

import { useState } from "react";
import { toast } from "react-toastify";
import { formatEther, isHash, type Hash } from "viem";
import { useTransaction } from "wagmi";
export function HomePage() {
const [inputHash, setInputHash] = useState('');
const [confirmedHash, setConfirmedHash] = useState<Hash | undefined>(undefined);
const { data: transaction, isPending, error } = useTransaction({
hash: confirmedHash,
query: {
retry: 1
}
})
function onSubmit(e) {
e.preventDefault();
if (isHash(inputHash)) {
setConfirmedHash(inputHash);
} else {
toast.error('Enter a valid transaction hash!');
}
}
return (
<div className="flex flex-col gap-10">
<div className="bg-white p-5 rounded-xl border border-slate-200 shadow-sm flex flex-col gap-6">
<h1 className="text-lg font-bold">Transaction Explorer</h1>
<p>Enter a transaction hash to get more details...</p>
<form className="flex flex-row gap-5 w-full" onSubmit={onSubmit}>
<input type="text" value={inputHash} onChange={(e) => {
setInputHash(e.target.value);
if (confirmedHash) {
setConfirmedHash(undefined);
}
}} className="w-full border border-gray-300 p-2 rounded-lg" placeholder="Enter hash..." />
<button
type="submit"
disabled={!inputHash}
className="bg-black text-white p-2 px-6 rounded-xl cursor-pointer disabled:opacity-50"
>
Run
</button>
</form>
</div>
{!!confirmedHash && (
<div className="bg-white p-0 rounded-xl overflow-hidden border border-slate-200 shadown-sm flex flex-col gap-6">
<div className="bg-slate-100 px-6 py-4">
<h2 className="text-lg font-bold">Details</h2>
</div>
<div className="p-6 pt-0">
{error && <p>An error occurred. Please enter a valid hash.</p>}
{isPending && <p>Loading details...</p>}
{!!transaction && (
<div className="grid grid-cols-6 w-full gap-y-6">
<div className="opacity-50">Hash</div>
<div className="col-span-5 break-all">{transaction.hash}</div>
<div className="opacity-50">From</div>
<div className="col-span-5">{transaction.from}</div>
<div className="opacity-50">To</div>
<div className="col-span-5">{transaction.to || 'N/A'}</div>
<div className="opacity-50">Value</div>
<div className="col-span-5">{formatEther(transaction.value)} ETH</div>
</div>
)}
</div>
</div>
)}
</div>
);
}