aboutsummaryrefslogtreecommitdiffstats
path: root/packages/asset-buyer/src/utils/buy_quote_calculator.ts
blob: e05ab1e5501c452ad8fe1fa96a1b46ab9265b719 (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
import { marketUtils } from '@0xproject/order-utils';
import { BigNumber } from '@0xproject/utils';

import { constants } from '../constants';
import { AssetBuyerError, AssetBuyerOrdersAndFillableAmounts, BuyQuote } from '../types';

export const buyQuoteCalculator = {
    calculate(
        ordersAndFillableAmounts: AssetBuyerOrdersAndFillableAmounts,
        assetBuyAmount: BigNumber,
        feePercentage: number,
        slippagePercentage: number,
    ): BuyQuote {
        const {
            orders,
            feeOrders,
            remainingFillableMakerAssetAmounts,
            remainingFillableFeeAmounts,
        } = ordersAndFillableAmounts;
        const slippageBufferAmount = assetBuyAmount.mul(slippagePercentage).round();
        const { resultOrders, remainingFillAmount } = marketUtils.findOrdersThatCoverMakerAssetFillAmount(
            orders,
            assetBuyAmount,
            {
                remainingFillableMakerAssetAmounts,
                slippageBufferAmount,
            },
        );
        if (remainingFillAmount.gt(constants.ZERO_AMOUNT)) {
            throw new Error(AssetBuyerError.InsufficientAssetLiquidity);
        }
        // TODO: optimization
        // update this logic to find the minimum amount of feeOrders to cover the worst case as opposed to
        // finding order that cover all fees, this will help with estimating ETH and minimizing gas usage
        const { resultFeeOrders, remainingFeeAmount } = marketUtils.findFeeOrdersThatCoverFeesForTargetOrders(
            resultOrders,
            feeOrders,
            {
                remainingFillableMakerAssetAmounts,
                remainingFillableFeeAmounts,
            },
        );
        if (remainingFeeAmount.gt(constants.ZERO_AMOUNT)) {
            throw new Error(AssetBuyerError.InsufficientZrxLiquidity);
        }
        const assetData = orders[0].makerAssetData;
        // TODO: critical
        // calculate minRate and maxRate by calculating min and max eth usage and then dividing into
        // assetBuyAmount to get assetData / WETH, needs to take into account feePercentage as well
        return {
            assetData,
            orders: resultOrders,
            feeOrders: resultFeeOrders,
            minRate: constants.ZERO_AMOUNT,
            maxRate: constants.ZERO_AMOUNT,
            assetBuyAmount,
            feePercentage,
        };
    },
};