aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/error.ts
blob: 39c563c75642f828a49a8a39075c023dcca68a61 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { AssetBuyerError } from '@0x/asset-buyer';
import { Dispatch } from 'redux';

import { Action, actions } from '../redux/actions';
import { Asset, ZeroExInstantError } from '../types';

import { assetUtils } from './asset';

class ErrorFlasher {
    private _timeoutId?: number;
    public flashNewError(dispatch: Dispatch<Action>, error: any, delayMs: number = 7000): void {
        this._clearTimeout();

        // dispatch new message
        dispatch(actions.setError(error));

        this._timeoutId = window.setTimeout(() => {
            dispatch(actions.hideError());
        }, delayMs);
    }
    public clearError(dispatch: Dispatch<Action>): void {
        this._clearTimeout();
        dispatch(actions.hideError());
    }
    private _clearTimeout(): void {
        if (this._timeoutId) {
            window.clearTimeout(this._timeoutId);
        }
    }
}

const humanReadableMessageForError = (error: Error, asset?: Asset): string | undefined => {
    const hasInsufficientLiquidity =
        error.message === AssetBuyerError.InsufficientAssetLiquidity ||
        error.message === AssetBuyerError.InsufficientZrxLiquidity;
    if (hasInsufficientLiquidity) {
        const assetName = assetUtils.bestNameForAsset(asset, 'of this asset');
        return `Not enough ${assetName} available`;
    }

    if (
        error.message === AssetBuyerError.StandardRelayerApiError ||
        error.message.startsWith(AssetBuyerError.AssetUnavailable)
    ) {
        const assetName = assetUtils.bestNameForAsset(asset, 'This asset');
        return `${assetName} is currently unavailable`;
    }

    if (error.message === AssetBuyerError.SignatureRequestDenied) {
        return 'You denied this transaction';
    }
    if (error.message === ZeroExInstantError.InsufficientETH) {
        return "You don't have enough ETH";
    }

    return undefined;
};

export const errorUtil = {
    errorFlasher: new ErrorFlasher(),
    errorDescription: (error?: any, asset?: Asset): { icon: string; message: string } => {
        let bestMessage: string | undefined;
        if (error instanceof Error) {
            bestMessage = humanReadableMessageForError(error, asset);
        }
        return {
            icon: '😢',
            message: bestMessage || 'Something went wrong...',
        };
    },
};