Skip to content

feat: Toast for tx lifecycle #259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4,326 changes: 1,889 additions & 2,437 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

11 changes: 9 additions & 2 deletions src/components/sharedComponents/TransactionButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@ import { type Hash, type TransactionReceipt } from 'viem'
import { useWaitForTransactionReceipt } from 'wagmi'

import { withWalletStatusVerifier } from '@/src/components/sharedComponents/WalletStatusVerifier'
import { useTransactionNotification } from '@/src/lib/toast/TransactionNotificationProvider'

interface TransactionButtonProps extends ComponentProps<'button'> {
confirmations?: number
labelSending?: string
onMined?: (receipt: TransactionReceipt) => void
transaction: () => Promise<Hash>
transaction: {
(): Promise<Hash>
methodId?: string
}
}

/**
Expand Down Expand Up @@ -40,6 +44,7 @@ const TransactionButton = withWalletStatusVerifier<TransactionButtonProps>(
const [hash, setHash] = useState<Hash>()
const [isPending, setIsPending] = useState<boolean>(false)

const { watchTx } = useTransactionNotification()
const { data: receipt } = useWaitForTransactionReceipt({
hash: hash,
confirmations,
Expand All @@ -60,7 +65,9 @@ const TransactionButton = withWalletStatusVerifier<TransactionButtonProps>(
const handleSendTransaction = async () => {
setIsPending(true)
try {
const hash = await transaction()
const txPromise = transaction()
watchTx({ txPromise, methodId: transaction.methodId })
const hash = await txPromise
setHash(hash)
} catch (error: unknown) {
console.error('Error sending transaction', error instanceof Error ? error.message : error)
Expand Down
25 changes: 25 additions & 0 deletions src/lib/toast/ToastNotification.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { Hash } from 'viem'

import { ExplorerLink } from '@/src/components/sharedComponents/ExplorerLink'
import { useWeb3Status } from '@/src/hooks/useWeb3Status'

export const ToastNotification = ({
hash,
message,
}: {
message: JSX.Element | string
hash?: Hash
showClose?: boolean
}) => {
const { readOnlyClient } = useWeb3Status()
const chain = readOnlyClient?.chain

if (!chain) return null

return (
<div>
<div>{message}</div>
{hash && <ExplorerLink chain={chain} hashOrAddress={hash} />}
</div>
)
}
180 changes: 180 additions & 0 deletions src/lib/toast/TransactionNotificationProvider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,180 @@
import { createContext, type FC, type PropsWithChildren, useContext } from 'react'

import toast from 'react-hot-toast'
import {
Hash,
type ReplacementReturnType,
type SignMessageErrorType,
type TransactionExecutionError,
} from 'viem'

import { ExplorerLink } from '@/src/components/sharedComponents/ExplorerLink'
import { useWeb3Status } from '@/src/hooks/useWeb3Status'
import { ToastNotification } from '@/src/lib/toast/ToastNotification'

type WatchSignatureArgs = {
successMessage?: string
message: JSX.Element | string
signaturePromise: Promise<Hash>
onToastId?: (toastId: string) => void
showSuccessToast?: boolean
}

type WatchHashArgs = {
message?: string
successMessage?: string
errorMessage?: string
hash: Hash
toastId?: string
}

type WatchTxArgs = { txPromise: Promise<Hash>; methodId?: string }

type TransactionContextValue = {
watchSignature: (args: WatchSignatureArgs) => void
watchHash: (args: WatchHashArgs) => void
watchTx: (args: WatchTxArgs) => void
}

const TransactionContext = createContext<TransactionContextValue | undefined>(undefined)

export const TransactionNotificationProvider: FC<PropsWithChildren> = ({ children }) => {
const { readOnlyClient } = useWeb3Status()
const chain = readOnlyClient?.chain

async function watchSignature({
message,
onToastId,
showSuccessToast = true,
signaturePromise,
successMessage = 'Signature received!',
}: WatchSignatureArgs) {
const toastId = toast.loading(() => <ToastNotification message={message} />)
onToastId?.(toastId)

try {
await signaturePromise
if (showSuccessToast) {
toast.success(<ToastNotification message={successMessage} />, {
id: toastId,
})
}
} catch (e) {
const error = e as TransactionExecutionError | SignMessageErrorType
let message = error.message || 'An error occurred'
if ('shortMessage' in error) {
message = error.shortMessage
}
toast.error(<ToastNotification message={message} />, { id: toastId })
}
}

async function watchHash({
errorMessage = 'Transaction was reverted!',
hash,
message = 'Transaction sent',
successMessage = 'Transaction has been mined!',
toastId,
}: WatchHashArgs) {
if (!chain) {
console.error('Chain is not defined')
return
}

if (!readOnlyClient) {
console.error('ReadOnlyClient is not defined')
return
}

toast.loading(() => <ToastNotification message={message} />, {
id: toastId,
})

try {
let replacedTx = null as ReplacementReturnType | null
const receipt = await readOnlyClient.waitForTransactionReceipt({
hash,
onReplaced: (replacedTxData) => (replacedTx = replacedTxData),
})

if (replacedTx !== null) {
if (['replaced', 'cancelled'].includes(replacedTx.reason)) {
toast.error(
<div>
<div>Transaction has been {replacedTx.reason}!</div>
<ExplorerLink chain={chain} hashOrAddress={replacedTx.transaction.hash} />
</div>,
{ id: toastId },
)
} else {
toast.success(
<div>
<div>{successMessage}</div>
<ExplorerLink chain={chain} hashOrAddress={replacedTx.transaction.hash} />
</div>,
{ id: toastId },
)
}
return
}

if (receipt.status === 'success') {
toast.success(
<div>
<div>{successMessage}</div>
<ExplorerLink chain={chain} hashOrAddress={hash} />
</div>,
{ id: toastId },
)
} else {
toast.error(
<div>
<div>{errorMessage}</div>
<ExplorerLink chain={chain} hashOrAddress={hash} />
</div>,
{ id: toastId },
)
}
} catch (error) {
console.error('Error watching hash', error)
}
}

async function watchTx({ methodId, txPromise }: WatchTxArgs) {
const transactionMessage = methodId ? `Transaction for calling ${methodId}` : 'Transaction'

let toastId: string = ''
await watchSignature({
message: `Signature requested: ${transactionMessage}`,
signaturePromise: txPromise,
showSuccessToast: false,
onToastId: (id) => (toastId = id),
})

const hash = await txPromise
await watchHash({
hash,
toastId,
message: `${transactionMessage} is pending to be mined ...`,
successMessage: `${transactionMessage} has been mined!`,
errorMessage: `${transactionMessage} has reverted!`,
})
}

return (
<TransactionContext.Provider value={{ watchTx, watchHash, watchSignature }}>
{children}
</TransactionContext.Provider>
)
}

// eslint-disable-next-line react-refresh/only-export-components
export function useTransactionNotification() {
const context = useContext(TransactionContext)
if (context === undefined) {
throw new Error(
'useTransactionNotification must be used within a TransactionNotificationProvider',
)
}
return context
}
23 changes: 13 additions & 10 deletions src/routes/__root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Footer } from '@/src/components/sharedComponents/Footer'
import { Header } from '@/src/components/sharedComponents/Header'
import { TanStackReactQueryDevtools } from '@/src/components/sharedComponents/TanStackReactQueryDevtools'
import { TanStackRouterDevtools } from '@/src/components/sharedComponents/TanStackRouterDevtools'
import { TransactionNotificationProvider } from '@/src/lib/toast/TransactionNotificationProvider'
import { Web3Provider } from '@/src/providers/Web3Provider'
import Styles from '@/src/styles'

Expand All @@ -24,19 +25,21 @@ function Root() {
<Styles />
<Web3Provider>
<ModalProvider>
<Wrapper>
<Header />
<Main>
<Outlet />
</Main>
<Footer />
<TanStackReactQueryDevtools />
<TanStackRouterDevtools />
</Wrapper>
<TransactionNotificationProvider>
<Wrapper>
<Header />
<Main>
<Outlet />
</Main>
<Footer />
<TanStackReactQueryDevtools />
<TanStackRouterDevtools />
</Wrapper>
<Toaster />
</TransactionNotificationProvider>
<ModalContainer />
</ModalProvider>
</Web3Provider>
<Toaster />
<Analytics />
</ThemeProvider>
)
Expand Down
2 changes: 1 addition & 1 deletion src/utils/getExplorerLink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const getExplorerLink = ({ chain, explorerUrl, hashOrAddress }: GetExplor
if (isHash(hashOrAddress)) {
return explorerUrl
? `${explorerUrl}/tx/${hashOrAddress}`
: `${chain.blockExplorers?.default}/tx/${hashOrAddress}`
: `${chain.blockExplorers?.default.url}/tx/${hashOrAddress}`
}

throw new Error('Invalid hash or address')
Expand Down
Loading