|
| 1 | +import React, { useState } from "react"; |
| 2 | +import { getContract } from "viem"; |
| 3 | + |
| 4 | +import { LarsKristoHellheads__factory } from "providers/evm/contracts/larskristohellheads/LarsKristoHellheads__factory"; |
| 5 | +import evm from "providers/evm"; |
| 6 | + |
| 7 | +import { LarskristoHellheadsContext } from "./LarskristoHellheadsContext"; |
| 8 | +import { |
| 9 | + LarskristoHellheadsContextActions, |
| 10 | + LarskristoHellheadsContextControllerProps, |
| 11 | + LarskristoHellheadsContextType, |
| 12 | + LarskristoHellheadsContractValues, |
| 13 | +} from "./LarskristoHellheadsContext.types"; |
| 14 | + |
| 15 | +export const LarskristoHellheadsContextController = ({ children }: LarskristoHellheadsContextControllerProps) => { |
| 16 | + const [contractValues, setContractValues] = useState<LarskristoHellheadsContractValues>(); |
| 17 | + const [actions, setActions] = useState<LarskristoHellheadsContextActions>({ |
| 18 | + fetchContractValues: { |
| 19 | + isLoading: false, |
| 20 | + }, |
| 21 | + }); |
| 22 | + |
| 23 | + const fetchContractValues = async (address: string) => { |
| 24 | + setActions((prev) => ({ |
| 25 | + ...prev, |
| 26 | + fetchContractValues: { |
| 27 | + isLoading: true, |
| 28 | + }, |
| 29 | + })); |
| 30 | + |
| 31 | + try { |
| 32 | + const contract = getContract({ |
| 33 | + address: address as `0x{string}`, |
| 34 | + abi: LarsKristoHellheads__factory.abi, |
| 35 | + client: evm.client, |
| 36 | + }); |
| 37 | + |
| 38 | + const [name, symbol] = await Promise.all([contract.read.name(), contract.read.symbol()]); |
| 39 | + |
| 40 | + const values: LarskristoHellheadsContractValues = { |
| 41 | + name, |
| 42 | + symbol, |
| 43 | + }; |
| 44 | + |
| 45 | + setContractValues({ ...values }); |
| 46 | + } catch (error) { |
| 47 | + console.error(error); |
| 48 | + } |
| 49 | + |
| 50 | + setActions((prev) => ({ |
| 51 | + ...prev, |
| 52 | + fetchContractValues: { |
| 53 | + isLoading: false, |
| 54 | + }, |
| 55 | + })); |
| 56 | + }; |
| 57 | + |
| 58 | + const props: LarskristoHellheadsContextType = { |
| 59 | + fetchContractValues, |
| 60 | + contractValues, |
| 61 | + actions, |
| 62 | + }; |
| 63 | + |
| 64 | + return <LarskristoHellheadsContext.Provider value={props}>{children}</LarskristoHellheadsContext.Provider>; |
| 65 | +}; |
0 commit comments