Skip to content

Commit

Permalink
simple wagmi token hook
Browse files Browse the repository at this point in the history
gets the token's name on connection

Signed-off-by: Stefan <[email protected]>
  • Loading branch information
elmariachi111 committed Jan 8, 2023
1 parent f6c55f6 commit 35e7bff
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
7 changes: 6 additions & 1 deletion apps/frontend/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
# frontend app
# 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)
29 changes: 29 additions & 0 deletions apps/frontend/hooks/useTokenContract.ts
Original file line number Diff line number Diff line change
@@ -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<string, { address: string }> = {
foundry: {
address: "0x5fbdb2315678afecb367f032d93f642f64180aa3",
},
}

export function useTokenContract() {
const { isConnected } = useAccount()
const { chain } = useNetwork()
const { data: signer } = useSigner()

const [contract, setContract] = useState<Token>()
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 }
}
12 changes: 12 additions & 0 deletions apps/frontend/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -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<string>()

useEffect(() => {
if (!token) return
;(async () => {
setContractName(await token.name())
})()
}, [token])

return (
<Flex>
<Text>{address}</Text>
<Text>{contractName}</Text>
</Flex>
)
}

0 comments on commit 35e7bff

Please sign in to comment.