Skip to content
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

Display error explanation for failed transaction #1220

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 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
6 changes: 6 additions & 0 deletions src/components/Toast/Toast.styled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,12 @@ export const STitle = styled(Title)`
& .referralDesc {
color: ${theme.colors.white};
}

& strong,
& b {
font-weight: 700;
font-family: "ChakraPetchBold";
}
`

export const SClose = styled(Close)`
Expand Down
3 changes: 3 additions & 0 deletions src/components/Toast/Toast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { ToastVariant } from "state/toasts"
type Props = {
variant?: ToastVariant
title?: string | ReactNode
description?: string | ReactNode
link?: string
actions?: ReactNode
index?: number
Expand All @@ -31,6 +32,7 @@ type Props = {
export const Toast: FC<Props> = ({
variant = "info",
title,
description,
link,
actions,
index,
Expand All @@ -56,6 +58,7 @@ export const Toast: FC<Props> = ({
<ToastContent
variant={variant ?? "info"}
title={title}
description={description}
link={link}
actions={actions}
onClick={onClick}
Expand Down
24 changes: 18 additions & 6 deletions src/components/Toast/ToastContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { Spinner } from "components/Spinner/Spinner"
export function ToastContent(props: {
variant: Maybe<ToastVariant>
title?: string | ReactNode
description?: string | ReactNode
link?: string
actions?: ReactNode
meta?: ReactNode
Expand Down Expand Up @@ -45,13 +46,24 @@ export function ToastContent(props: {
</SIcon>
<div sx={{ flex: "column", gap: 4, justify: "center" }}>
<div sx={{ flex: "row", justify: "space-between", align: "flex-end" }}>
<STitle>
{typeof props.title === "string" ? (
<p dangerouslySetInnerHTML={{ __html: props.title }} />
) : (
props.title
<div>
<STitle>
{typeof props.title === "string" ? (
<p dangerouslySetInnerHTML={{ __html: props.title }} />
) : (
props.title
)}
</STitle>
{props.description && (
<STitle sx={{ mt: 2 }}>
{typeof props.description === "string" ? (
<p dangerouslySetInnerHTML={{ __html: props.description }} />
) : (
props.description
)}
</STitle>
)}
</STitle>
</div>

{props.actions}
</div>
Expand Down
18 changes: 18 additions & 0 deletions src/components/Toast/sidebar/ToastSidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,15 @@ export function ToastSidebar() {
}}
/>
}
description={
toast.description ? (
<div
dangerouslySetInnerHTML={{
__html: toast.description,
}}
/>
) : undefined
}
actions={toast.actions}
dateCreated={
typeof toast.dateCreated === "string"
Expand All @@ -115,6 +124,15 @@ export function ToastSidebar() {
}}
/>
}
description={
toast.description ? (
<div
dangerouslySetInnerHTML={{
__html: toast.description,
}}
/>
) : undefined
}
actions={toast.actions}
dateCreated={
typeof toast.dateCreated === "string"
Expand Down
50 changes: 21 additions & 29 deletions src/sections/trade/sections/otc/modals/PlaceOrder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,13 @@ import { AssetsModalContent } from "sections/assets/AssetsModal"
import { getFixedPointAmount } from "utils/balance"
import { BN_10 } from "utils/constants"
import { FormValues } from "utils/helpers"
import { useStore } from "state/store"
import { ToastMessage, useStore } from "state/store"
import { OrderAssetSelect } from "./cmp/AssetSelect"
import { OrderAssetRate } from "./cmp/AssetXRate"
import { PartialOrderToggle } from "./cmp/PartialOrderToggle"
import { useRpcProvider } from "providers/rpcProvider"
import { useAccount } from "sections/web3-connect/Web3Connect.utils"
import { TOAST_MESSAGES } from "state/toasts"

type PlaceOrderProps = {
assetOut?: u32 | string
Expand Down Expand Up @@ -109,6 +110,24 @@ export const PlaceOrder = ({
assetInMeta.decimals,
).decimalPlaces(0, 1)

const toast = TOAST_MESSAGES.reduce((memo, type) => {
const msType = type === "onError" ? "onLoading" : type
memo[type] = (
<Trans
t={t}
i18nKey={`otc.order.place.toast.${msType}`}
tOptions={{
amount: values.amountOut,
symbol: assetOutMeta.symbol,
}}
>
<span />
<span className="highlight" />
</Trans>
)
return memo
}, {} as ToastMessage)

await createTransaction(
{
tx: api.tx.otc.placeOrder(
Expand All @@ -125,34 +144,7 @@ export const PlaceOrder = ({
onClose()
form.reset()
},
toast: {
onLoading: (
<Trans
t={t}
i18nKey="otc.order.place.toast.onLoading"
tOptions={{
amount: values.amountOut,
symbol: assetOutMeta.symbol,
}}
>
<span />
<span className="highlight" />
</Trans>
),
onSuccess: (
<Trans
t={t}
i18nKey="otc.order.place.toast.onSuccess"
tOptions={{
amount: values.amountOut,
symbol: assetOutMeta.symbol,
}}
>
<span />
<span className="highlight" />
</Trans>
),
},
toast,
},
)
}
Expand Down
2 changes: 1 addition & 1 deletion src/sections/transaction/ReviewTransaction.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ export const ReviewTransaction = (props: Transaction) => {
data,
txState,
reset,
} = useSendTx()
} = useSendTx({ id: props.id })

const isError = isSendError || !!signError
const error = sendError || signError
Expand Down
53 changes: 45 additions & 8 deletions src/sections/transaction/ReviewTransaction.utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useMountedState } from "react-use"
import { useEvmAccount } from "sections/web3-connect/Web3Connect.utils"
import { useToast } from "state/toasts"
import { H160, getEvmTxLink, isEvmAccount } from "utils/evm"
import { defer } from "utils/helpers"

type TxMethod = AnyJson & {
method: string
Expand Down Expand Up @@ -86,6 +87,14 @@ export function getTransactionJSON(tx: SubmittableExtrinsic<"promise">) {

export class UnknownTransactionState extends Error {}

export class TransactionError extends Error {
docs: string = ""
method: string = ""
constructor(public error: string) {
super(error)
}
}

function evmTxReceiptToSubmittableResult(txReceipt: TransactionReceipt) {
const isSuccess = txReceipt.status === 1
const submittableResult: ISubmittableResult = {
Expand All @@ -110,7 +119,7 @@ export const useSendEvmTransactionMutation = (
ISubmittableResult & {
transactionLink?: string
},
unknown,
TransactionError,
{
evmTx: TransactionResponse
tx?: SubmittableExtrinsic<"promise">
Expand Down Expand Up @@ -149,7 +158,7 @@ export const useSendEvmTransactionMutation = (
})
} catch (err) {
const { error } = decodeError(err)
reject(new Error(error))
reject(new TransactionError(error))
} finally {
clearTimeout(timeout)
}
Expand All @@ -169,7 +178,7 @@ export const useSendEvmTransactionMutation = (
export const useSendTransactionMutation = (
options: MutationObserverOptions<
ISubmittableResult & { transactionLink?: string },
unknown,
TransactionError,
SubmittableExtrinsic<"promise">
> = {},
) => {
Expand Down Expand Up @@ -197,19 +206,25 @@ export const useSendTransactionMutation = (

if (result.isCompleted) {
if (result.dispatchError) {
let docs = ""
let method = ""
let errorMessage = result.dispatchError.toString()

if (result.dispatchError.isModule) {
const decoded = api.registry.findMetaError(
result.dispatchError.asModule,
)
errorMessage = `${decoded.section}.${
decoded.method
}: ${decoded.docs.join(" ")}`
docs = decoded.docs.join(" ")
method = decoded.method
errorMessage = `${decoded.section}.${decoded.method}: ${docs}`
}

const error = new TransactionError(errorMessage)
error.docs = docs
error.method = method

clearTimeout(timeout)
reject(new Error(errorMessage))
reject(error)
} else {
const transactionLink = await link.mutateAsync({
blockHash: result.status.asInBlock.toString(),
Expand Down Expand Up @@ -307,17 +322,38 @@ const useBoundReferralToast = () => {
}
}

export const useSendTx = () => {
const useErrorToastUpdate = (id: string) => {
const { edit } = useToast()

return (err: TransactionError) => {
if (err?.method) {
defer(() => {
edit(id, {
description: (
<p>
<strong>{err.method}</strong>
{err.docs ? ` - ${err.docs}` : ""}
</p>
),
})
})
}
}
}

export const useSendTx = ({ id }: { id: string }) => {
const [txType, setTxType] = useState<"default" | "evm" | null>(null)

const boundReferralToast = useBoundReferralToast()
const updateErrorToast = useErrorToastUpdate(id)

const sendTx = useSendTransactionMutation({
onMutate: (tx) => {
boundReferralToast.onLoading(tx)
setTxType("default")
},
onSuccess: boundReferralToast.onSuccess,
onError: updateErrorToast,
})

const sendEvmTx = useSendEvmTransactionMutation({
Expand All @@ -326,6 +362,7 @@ export const useSendTx = () => {
setTxType("evm")
},
onSuccess: boundReferralToast.onSuccess,
onError: updateErrorToast,
})

const activeMutation = txType === "default" ? sendTx : sendEvmTx
Expand Down
18 changes: 17 additions & 1 deletion src/sections/transaction/ReviewTransactionToast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export function ReviewTransactionToast(props: {
if (isSuccess) {
// toast should be still present, even if ReviewTransaction is unmounted
toastRef.current.success({
id: props.id,
title: props.toastMessage?.onSuccess ?? (
<p>{t("liquidity.reviewTransaction.toast.success")}</p>
),
Expand All @@ -48,12 +49,16 @@ export function ReviewTransactionToast(props: {
if (isError) {
if (error instanceof UnknownTransactionState) {
toastRef.current.unknown({
id: props.id,
link: props.link,
title: props.toastMessage?.onError ?? (
<p>{t("liquidity.reviewTransaction.toast.unknown")}</p>
),
})
} else {
toastRef.current.error({
id: props.id,
link: props.link,
title: props.toastMessage?.onError ?? (
<p>{t("liquidity.reviewTransaction.toast.error")}</p>
),
Expand All @@ -63,6 +68,8 @@ export function ReviewTransactionToast(props: {

if (isLoading) {
toRemoveId = toastRef.current.loading({
id: props.id,
link: props.link,
title: props.toastMessage?.onLoading ?? (
<p>{t("liquidity.reviewTransaction.toast.pending")}</p>
),
Expand All @@ -72,7 +79,16 @@ export function ReviewTransactionToast(props: {
return () => {
if (toRemoveId) toastRef.current.remove(toRemoveId)
}
}, [t, props.toastMessage, isError, error, isSuccess, isLoading, props.link])
}, [
t,
props.toastMessage,
isError,
error,
isSuccess,
isLoading,
props.link,
props.id,
])

return null
}
Loading
Loading