import { ContractPromise } from '@polkadot/api-contract'; import { useCallback, useState } from 'react'; import { call } from '../../utils/mod.js'; import { ContractOptions } from '../../types/mod.js'; import { useAbiMessage } from './useAbiMessage.js'; import { useExtension } from '../useExtension.js'; import { DecodedContractResult } from '../../types/contracts.js'; export type CallSend = ( args?: unknown[], options?: ContractOptions, caller?: string, ) => Promise | undefined>; export interface UseCall { send: CallSend; isSubmitting: boolean; } export enum CallError { ContractUndefined = 'Contract is undefined', InvalidAbiMessage = 'Invalid ABI Message', NoResponse = 'No response', } export interface UseCallResponse extends UseCall { result?: DecodedContractResult; } export function useCall( contract: ContractPromise | undefined, message: string, ): UseCallResponse { const [result, setResult] = useState>(); const [isSubmitting, setIsSubmitting] = useState(false); const abiMessage = useAbiMessage(contract, message); const { account } = useExtension(); const send = useCallback( async ( args, options, caller, ): Promise | undefined> => { const callingAddress = caller ? caller : account?.address; if (!abiMessage || !contract || !callingAddress) return; try { setIsSubmitting(true); const callResult = await call( contract, abiMessage, callingAddress, args, options, ); setResult(callResult); setIsSubmitting(false); return callResult; } catch (e: unknown) { console.error(e); setIsSubmitting(false); return; } }, [account, abiMessage], ); return { send, isSubmitting, result }; }