'use client' import { FC, useEffect, useState } from 'react' import { Button } from '@/components/ui/button' import { Card, CardContent } from '@/components/ui/card' import { Form, FormControl, FormItem, FormLabel } from '@/components/ui/form' import { Input } from '@/components/ui/input' import { ContractIds } from '@/deployments/deployments' import { contractTxWithToast } from '@/utils/contract-tx-with-toast' import { contractQuery, decodeOutput, useInkathon, useRegisteredContract, } from '@scio-labs/use-inkathon' import { useForm } from 'react-hook-form' import toast from 'react-hot-toast' type UpdateGreetingValues = { newMessage: string } export const GreeterContractInteractions: FC = () => { const { api, activeAccount, activeSigner } = useInkathon() const { contract, address: contractAddress } = useRegisteredContract(ContractIds.Greeter) const [greeterMessage, setGreeterMessage] = useState() const [fetchIsLoading, setFetchIsLoading] = useState() const [updateIsLoading, setUpdateIsLoading] = useState() const form = useForm() const { register, reset, handleSubmit } = form // Fetch Greeting const fetchGreeting = async () => { if (!contract || !api) return setFetchIsLoading(true) try { const result = await contractQuery(api, '', contract, 'greet') const { output, isError, decodedOutput } = decodeOutput(result, contract, 'greet') if (isError) throw new Error(decodedOutput) setGreeterMessage(output) } catch (e) { console.error(e) toast.error('Error while fetching greeting. Try again…') setGreeterMessage(undefined) } finally { setFetchIsLoading(false) } } useEffect(() => { fetchGreeting() }, [contract]) // Update Greeting const updateGreeting = async ({ newMessage }: UpdateGreetingValues) => { if (!activeAccount || !contract || !activeSigner || !api) { toast.error('Wallet not connected. Try again…') return } // Send transaction setUpdateIsLoading(true) try { await contractTxWithToast(api, activeAccount.address, contract, 'setMessage', {}, [ newMessage, ]) reset() } catch (e) { console.error(e) } finally { setUpdateIsLoading(false) fetchGreeting() } } if (!api) return null return ( <>

Greeter Smart Contract

{/* Fetched Greeting */} Fetched Greeting {/* Update Greeting */}
Update Greeting
{/* Contract Address */}

{contract ? contractAddress : 'Loading…'}

) }