aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/buy_quote_updater.ts
blob: 4f97622e127dabfc81ffc79142e17cbb443178a3 (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
import { AssetBuyer, AssetBuyerError, BuyQuote } from '@0x/asset-buyer';
import { BigNumber } from '@0x/utils';
import { Web3Wrapper } from '@0x/web3-wrapper';
import * as _ from 'lodash';
import { Dispatch } from 'redux';
import { oc } from 'ts-optchain';

import { Action, actions } from '../redux/actions';
import { AffiliateInfo, ERC20Asset } from '../types';
import { assetUtils } from '../util/asset';
import { errorFlasher } from '../util/error_flasher';
import { errorReporter } from '../util/error_reporter';

export const buyQuoteUpdater = {
    updateBuyQuoteAsync: async (
        assetBuyer: AssetBuyer,
        dispatch: Dispatch<Action>,
        asset: ERC20Asset,
        assetUnitAmount: BigNumber,
        options: { setPending: boolean; dispatchErrors: boolean; affiliateInfo?: AffiliateInfo },
    ): Promise<void> => {
        // get a new buy quote.
        const baseUnitValue = Web3Wrapper.toBaseUnitAmount(assetUnitAmount, asset.metaData.decimals);
        if (options.setPending) {
            // mark quote as pending
            dispatch(actions.setQuoteRequestStatePending());
        }
        const feePercentage = oc(options.affiliateInfo).feePercentage();
        let newBuyQuote: BuyQuote | undefined;
        try {
            newBuyQuote = await assetBuyer.getBuyQuoteAsync(asset.assetData, baseUnitValue, { feePercentage });
        } catch (error) {
            const errorMessage = assetUtils.assetBuyerErrorMessage(asset, error);

            if (_.isUndefined(errorMessage)) {
                // This is an unknown error, report it to rollbar
                errorReporter.report(error);
            }

            if (options.dispatchErrors) {
                dispatch(actions.setQuoteRequestStateFailure());
                errorFlasher.flashNewErrorMessage(dispatch, errorMessage || 'Error fetching price, please try again');
            }
            return;
        }
        // We have a successful new buy quote
        errorFlasher.clearError(dispatch);
        // invalidate the last buy quote.
        dispatch(actions.updateLatestBuyQuote(newBuyQuote));
    },
};