Skip to content

Instantly share code, notes, and snippets.

@kmjones1979
Last active July 2, 2024 23:20
Show Gist options
  • Save kmjones1979/519a8b774ca3fa4b5b2db85b1432cec6 to your computer and use it in GitHub Desktop.
Save kmjones1979/519a8b774ca3fa4b5b2db85b1432cec6 to your computer and use it in GitHub Desktop.
A full example of a page for Scaffold-ETH that sends tokens using hooks and components
"use client";
import { useState } from "react";
import type { NextPage } from "next";
import { formatEther, parseEther } from "viem";
import { useAccount } from "wagmi";
import { Address, AddressInput, EtherInput } from "~~/components/scaffold-eth";
import { useScaffoldReadContract, useScaffoldWriteContract } from "~~/hooks/scaffold-eth";
const Home: NextPage = () => {
const { address: connectedAddress } = useAccount();
// get the users balance
const { data: userBalance } = useScaffoldReadContract({
contractName: "YourContract",
functionName: "balanceOf",
args: [connectedAddress],
});
// convert the balance to ether
const userBalanceEth = formatEther(userBalance ?? 0n);
// create state for the address input
const [address, setAddress] = useState("");
// create state for the amount input
const [ethAmount, setEthAmount] = useState("");
// async function to send WIF
const { writeContractAsync: writeYourContractAsync } = useScaffoldWriteContract("YourContract");
return (
<>
{!connectedAddress && (
<div className="flex justify-center p-3">
<div className="card bg-base-100 w-96 shadow-xl">
<div className="card-body">
<h2 className="card-title">Wallet Details:</h2>
<p>No wallet connected.</p>
</div>
</div>
</div>
)}
{connectedAddress && (
<div className="flex justify-center p-3">
<div className="card bg-base-100 w-96 shadow-xl">
<div className="card-body">
<h2 className="card-title">Wallet Details:</h2>
<p>
Address: <Address address={connectedAddress} />
</p>
<p>Balance: {userBalanceEth} WIF</p>
<AddressInput onChange={setAddress} value={address} placeholder="Input your address" />
<EtherInput value={ethAmount} onChange={amount => setEthAmount(amount)} />
<button
className="btn btn-primary"
onClick={async () => {
try {
await writeYourContractAsync({
functionName: "transfer",
args: [address, parseEther(ethAmount)],
value: 0,
});
} catch (e) {
console.error("Error sending WIF:", e);
}
}}
>
Send
</button>
</div>
</div>
</div>
)}
</>
);
};
export default Home;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment