aboutsummaryrefslogtreecommitdiffstats
path: root/packages/instant/src/util/order_coercion.ts
blob: a1b468bafceec80a1482f9ce816974708332e752 (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
import { BigNumber } from '@0x/utils';
import * as _ from 'lodash';

import { maybeBigNumberUtil } from './maybe_big_number';

const coerceBigNumberOrString = (value: any): BigNumber => {
    const bn = maybeBigNumberUtil.toMaybeBigNumber(value);
    return !!bn ? bn : value;
};

// function implies that the signed order already has been validated
export const orderCoercionUtil = {
    // coerces order big number values to the BigNumber version utilized by 0x
    coerceFieldsToBigNumbers(obj: any, fields: string[]): any {
        const result = _.assign({}, obj);
        _.each(fields, field => {
            _.update(result, field, (value: string) => {
                if (_.isUndefined(value)) {
                    throw new Error(`Could not find field '${field}' while converting fields to BigNumber.`);
                }
                return coerceBigNumberOrString(value);
            });
        });
        return result;
    },

    coerceOrderFieldsToBigNumber: (order: any): any => {
        return orderCoercionUtil.coerceFieldsToBigNumbers(order, [
            'makerFee',
            'takerFee',
            'makerAssetAmount',
            'takerAssetAmount',
            'salt',
            'expirationTimeSeconds',
        ]);
    },
    coerceOrderArrayFieldsToBigNumber: (orders: any[]): any[] => {
        return _.map(orders, (value: any) => {
            return orderCoercionUtil.coerceOrderFieldsToBigNumber(value);
        });
    },
};