diff --git a/apps/frontend/README.md b/apps/frontend/README.md index 5c64ce6..b30b2e5 100644 --- a/apps/frontend/README.md +++ b/apps/frontend/README.md @@ -1 +1,6 @@ -# frontend app \ No newline at end of file +# frontend app + +build and deploy *packages/contracts* first. Take a note of the deployed contracts' address. +Copy `.env.example` to `.env` and add alchemy / infura keys + +the local contract address is currently hardwired in `useTokenContract` (0x5fbdb2315678afecb367f032d93f642f64180aa3) diff --git a/apps/frontend/hooks/useTokenContract.ts b/apps/frontend/hooks/useTokenContract.ts new file mode 100644 index 0000000..6bc2479 --- /dev/null +++ b/apps/frontend/hooks/useTokenContract.ts @@ -0,0 +1,29 @@ +import { useState } from "react" + +import { Token, TokenFactory } from "@app/contracts" +import { useEffect } from "react" +import { useAccount, useNetwork, useSigner } from "wagmi" + +const config: Record = { + foundry: { + address: "0x5fbdb2315678afecb367f032d93f642f64180aa3", + }, +} + +export function useTokenContract() { + const { isConnected } = useAccount() + const { chain } = useNetwork() + const { data: signer } = useSigner() + + const [contract, setContract] = useState() + useEffect(() => { + if (!isConnected || !chain?.network || !signer) return + + const contractAddress = config[chain.network]?.address + if (!contractAddress) return + + setContract(TokenFactory.connect(contractAddress, signer)) + }, [chain?.network, isConnected, signer]) + + return { contract } +} diff --git a/apps/frontend/pages/index.tsx b/apps/frontend/pages/index.tsx index fe02f24..4227d50 100644 --- a/apps/frontend/pages/index.tsx +++ b/apps/frontend/pages/index.tsx @@ -1,12 +1,24 @@ import { Flex, Text } from "@chakra-ui/react" +import { useEffect, useState } from "react" import { useAccount } from "wagmi" +import { useTokenContract } from "../hooks/useTokenContract" export default function Home() { const { address } = useAccount() + const { contract: token } = useTokenContract() + const [contractName, setContractName] = useState() + + useEffect(() => { + if (!token) return + ;(async () => { + setContractName(await token.name()) + })() + }, [token]) return ( {address} + {contractName} ) }