import { Code, Divider, Flex, Icon, useClipboard, useToast, } from "@chakra-ui/react"; import type { TransactionError } from "@thirdweb-dev/sdk"; import { createContext, useCallback, useContext, useEffect, useState, } from "react"; import { FiAlertTriangle, FiCheck, FiCopy, FiHelpCircle } from "react-icons/fi"; import { Button, Drawer, Heading, LinkButton, Text } from "tw-components"; import { AddressCopyButton } from "tw-components/AddressCopyButton"; import { ComponentWithChildren } from "types/component-with-children"; import { parseErrorToMessage } from "utils/errorParser"; interface ErrorContext { onError: (error: unknown, errorTitle?: string) => void; dismissError: () => void; } const ErrorContext = createContext({ onError: () => undefined, dismissError: () => undefined, }); type EnhancedTransactionError = TransactionError & { title: string; }; export const ErrorProvider: ComponentWithChildren = ({ children }) => { const toast = useToast(); const [currentError, setCurrentError] = useState(); const dismissError = useCallback(() => setCurrentError(undefined), []); const onError = useCallback((err: unknown, title = "An error occurred") => { if (isTransactionError(err)) { (err as any).title = title; setCurrentError(err as EnhancedTransactionError); } else { toast({ position: "bottom", variant: "solid", title, description: parseErrorToMessage(err), status: "error", duration: 9000, isClosable: true, }); } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); const { onCopy, hasCopied, setValue } = useClipboard( currentError?.message || "", ); useEffect(() => { if (currentError?.message) { setValue(currentError?.message); } }, [currentError?.message, setValue]); return ( <> Error: Failed to send transaction From To Chain / Chain ID {currentError?.info.network.name} ( {currentError?.info.network.chainId}) Root cause {currentError?.reason} Need help with this error? } > Visit our support site Copying the error message will let you report this error with all its details to our team. {children} ); }; export function useErrorHandler() { return useContext(ErrorContext); } function isError(value: unknown): value is Error { return value instanceof Error; } function isTransactionError(error: unknown): error is TransactionError { return error instanceof Object && "reason" in error && "info" in error; }