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 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
6 changes: 6 additions & 0 deletions src/components/Toast/Toast.styled.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,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 @@ -90,6 +90,15 @@ export function ToastSidebar() {
}}
/>
}
description={
toast.description ? (
<div
dangerouslySetInnerHTML={{
__html: toast.description,
}}
/>
) : undefined
}
actions={toast.actions}
dateCreated={
typeof toast.dateCreated === "string"
Expand All @@ -116,6 +125,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 @@ -30,7 +30,7 @@ export const ReviewTransaction = (props: Transaction) => {
txState,
reset,
txLink,
} = useSendTx()
} = useSendTx({ id: props.id })

const isError = isSendError || !!signError
const error = sendError || signError
Expand Down
59 changes: 49 additions & 10 deletions src/sections/transaction/ReviewTransaction.utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useEvmAccount } from "sections/web3-connect/Web3Connect.utils"
import { PermitResult } from "sections/web3-connect/signer/EthereumSigner"
import { useToast } from "state/toasts"
import { H160, getEvmChainById, getEvmTxLink, isEvmAccount } from "utils/evm"
import { defer } from "utils/helpers"
import { getSubscanLinkByType } from "utils/formatting"

type TxMethod = AnyJson & {
Expand Down Expand Up @@ -87,6 +88,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 Down Expand Up @@ -123,18 +132,24 @@ const createResultOnCompleteHandler =
(result: ISubmittableResult) => {
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}`
}

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

onError(error)
} else {
onSuccess(result)
}
Expand All @@ -145,8 +160,10 @@ const createResultOnCompleteHandler =

export const useSendEvmTransactionMutation = (
options: MutationObserverOptions<
ISubmittableResult,
unknown,
ISubmittableResult & {
transactionLink?: string
},
TransactionError,
{
evmTx: TransactionResponse
tx?: SubmittableExtrinsic<"promise">
Expand Down Expand Up @@ -177,7 +194,7 @@ export const useSendEvmTransactionMutation = (
return resolve(evmTxReceiptToSubmittableResult(receipt))
} catch (err) {
const { error } = decodeError(err)
reject(new Error(error))
reject(new TransactionError(error))
} finally {
clearTimeout(timeout)
}
Expand Down Expand Up @@ -279,8 +296,8 @@ export const useSendDispatchPermit = (

export const useSendTransactionMutation = (
options: MutationObserverOptions<
ISubmittableResult,
unknown,
ISubmittableResult & { transactionLink?: string },
TransactionError,
SubmittableExtrinsic<"promise">
> = {},
) => {
Expand Down Expand Up @@ -408,19 +425,40 @@ 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" | "permit" | 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 @@ -429,6 +467,7 @@ export const useSendTx = () => {
setTxType("evm")
},
onSuccess: boundReferralToast.onSuccess,
onError: updateErrorToast,
})

const sendPermitTx = useSendDispatchPermit({
Expand Down
15 changes: 14 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,13 +49,15 @@ 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 @@ -65,6 +68,7 @@ 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 @@ -75,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