aboutsummaryrefslogtreecommitdiffstats
path: root/packages/asset-buyer/src/utils/calculate_liquidity.ts
blob: a8d165b4b97604f70ffa5165302e1935f2bbc069 (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
import { BigNumber } from '@0x/utils';

import { LiquidityForAssetData, OrdersAndFillableAmounts } from '../types';

import { orderUtils } from './order_utils';

export const calculateLiquidity = (ordersAndFillableAmounts: OrdersAndFillableAmounts): LiquidityForAssetData => {
    const { orders, remainingFillableMakerAssetAmounts } = ordersAndFillableAmounts;
    const liquidityInBigNumbers = orders.reduce(
        (acc, order, curIndex) => {
            const availableMakerAssetAmount = remainingFillableMakerAssetAmounts[curIndex];
            if (availableMakerAssetAmount === undefined) {
                throw new Error(`No corresponding fillableMakerAssetAmounts at index ${curIndex}`);
            }

            const tokensAvailableForCurrentOrder = availableMakerAssetAmount;
            const ethValueAvailableForCurrentOrder = orderUtils.getTakerFillAmount(order, availableMakerAssetAmount);
            return {
                tokensAvailableInBaseUnits: acc.tokensAvailableInBaseUnits.plus(tokensAvailableForCurrentOrder),
                ethValueAvailableInWei: acc.ethValueAvailableInWei.plus(ethValueAvailableForCurrentOrder),
            };
        },
        {
            tokensAvailableInBaseUnits: new BigNumber(0),
            ethValueAvailableInWei: new BigNumber(0),
        },
    );

    // Turn into regular numbers
    return {
        tokensAvailableInBaseUnits: liquidityInBigNumbers.tokensAvailableInBaseUnits,
        ethValueAvailableInWei: liquidityInBigNumbers.ethValueAvailableInWei,
    };
};