diff options
author | Steve Klebanoff <steve.klebanoff@gmail.com> | 2019-01-09 00:57:36 +0800 |
---|---|---|
committer | Steve Klebanoff <steve.klebanoff@gmail.com> | 2019-01-11 05:41:28 +0800 |
commit | a9fad77eb4375439767f9aa1fcbfa12716f41ed3 (patch) | |
tree | fcd6668f24e527bbbba60e66a3f47bc830fce588 /packages/asset-buyer | |
parent | 2111ea159e48206a63f311dfc1ed56a3925603c7 (diff) | |
download | dexon-0x-contracts-a9fad77eb4375439767f9aa1fcbfa12716f41ed3.tar.gz dexon-0x-contracts-a9fad77eb4375439767f9aa1fcbfa12716f41ed3.tar.zst dexon-0x-contracts-a9fad77eb4375439767f9aa1fcbfa12716f41ed3.zip |
Implement liquidity checking w/ testing
Diffstat (limited to 'packages/asset-buyer')
-rw-r--r-- | packages/asset-buyer/package.json | 1 | ||||
-rw-r--r-- | packages/asset-buyer/src/asset_buyer.ts | 67 | ||||
-rw-r--r-- | packages/asset-buyer/src/types.ts | 8 | ||||
-rw-r--r-- | packages/asset-buyer/test/asset_buyer_test.ts | 168 | ||||
-rw-r--r-- | packages/asset-buyer/test/utils/mocks.ts | 66 |
5 files changed, 307 insertions, 3 deletions
diff --git a/packages/asset-buyer/package.json b/packages/asset-buyer/package.json index 401aec120..9ddeb2c60 100644 --- a/packages/asset-buyer/package.json +++ b/packages/asset-buyer/package.json @@ -65,6 +65,7 @@ "shx": "^0.2.2", "tslint": "5.11.0", "typedoc": "0.13.0", + "typemoq": "^2.1.0", "typescript": "3.0.1" }, "publishConfig": { diff --git a/packages/asset-buyer/src/asset_buyer.ts b/packages/asset-buyer/src/asset_buyer.ts index 934410c55..511c99fb1 100644 --- a/packages/asset-buyer/src/asset_buyer.ts +++ b/packages/asset-buyer/src/asset_buyer.ts @@ -16,6 +16,7 @@ import { BuyQuote, BuyQuoteExecutionOpts, BuyQuoteRequestOpts, + LiquidityForAssetData, OrderProvider, OrderProviderResponse, OrdersAndFillableAmounts, @@ -25,12 +26,42 @@ import { assert } from './utils/assert'; import { assetDataUtils } from './utils/asset_data_utils'; import { buyQuoteCalculator } from './utils/buy_quote_calculator'; import { orderProviderResponseProcessor } from './utils/order_provider_response_processor'; +import { orderUtils } from './utils/order_utils'; interface OrdersEntry { ordersAndFillableAmounts: OrdersAndFillableAmounts; lastRefreshTime: number; } +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 { + tokensAvailableInUnitAmount: acc.tokensAvailableInUnitAmount.plus(tokensAvailableForCurrentOrder), + ethValueAvailableInWei: acc.ethValueAvailableInWei.plus(ethValueAvailableForCurrentOrder), + }; + }, + { + tokensAvailableInUnitAmount: new BigNumber(0), + ethValueAvailableInWei: new BigNumber(0), + }, + ); + + // Turn into regular numbers + return { + tokensAvailableInUnitAmount: liquidityInBigNumbers.tokensAvailableInUnitAmount.toNumber(), + ethValueAvailableInWei: liquidityInBigNumbers.ethValueAvailableInWei.toNumber(), + }; +}; + export class AssetBuyer { public readonly provider: Provider; public readonly orderProvider: OrderProvider; @@ -138,10 +169,10 @@ export class AssetBuyer { // get the relevant orders for the makerAsset and fees // if the requested assetData is ZRX, don't get the fee info const [ordersAndFillableAmounts, feeOrdersAndFillableAmounts] = await Promise.all([ - this._getOrdersAndFillableAmountsAsync(assetData, shouldForceOrderRefresh), + this.getOrdersAndFillableAmountsAsync(assetData, shouldForceOrderRefresh), isMakerAssetZrxToken ? Promise.resolve(constants.EMPTY_ORDERS_AND_FILLABLE_AMOUNTS) - : this._getOrdersAndFillableAmountsAsync(zrxTokenAssetData, shouldForceOrderRefresh), + : this.getOrdersAndFillableAmountsAsync(zrxTokenAssetData, shouldForceOrderRefresh), shouldForceOrderRefresh, ]); if (ordersAndFillableAmounts.orders.length === 0) { @@ -177,6 +208,36 @@ export class AssetBuyer { const buyQuote = this.getBuyQuoteAsync(assetData, assetBuyAmount, options); return buyQuote; } + public async getLiquidityForAssetDataAsync( + assetData: string, + options: Partial<BuyQuoteRequestOpts> = {}, + ): Promise<LiquidityForAssetData> { + const { feePercentage, shouldForceOrderRefresh, slippagePercentage } = _.merge( + {}, + constants.DEFAULT_BUY_QUOTE_REQUEST_OPTS, + options, + ); + assert.isString('assetData', assetData); + assert.isValidPercentage('feePercentage', feePercentage); + assert.isBoolean('shouldForceOrderRefresh', shouldForceOrderRefresh); + assert.isNumber('slippagePercentage', slippagePercentage); + + const assetPairs = await this.orderProvider.getAvailableMakerAssetDatasAsync(assetData); + if (!assetPairs.includes(assetData)) { + return { + tokensAvailableInUnitAmount: 0, + ethValueAvailableInWei: 0, + }; + } + + const ordersAndFillableAmounts = await this.getOrdersAndFillableAmountsAsync( + assetData, + shouldForceOrderRefresh, + ); + + return calculateLiquidity(ordersAndFillableAmounts); + } + /** * Given a BuyQuote and desired rate, attempt to execute the buy. * @param buyQuote An object that conforms to BuyQuote. See type definition for more information. @@ -261,7 +322,7 @@ export class AssetBuyer { /** * Grab orders from the map, if there is a miss or it is time to refresh, fetch and process the orders */ - private async _getOrdersAndFillableAmountsAsync( + public async getOrdersAndFillableAmountsAsync( assetData: string, shouldForceOrderRefresh: boolean, ): Promise<OrdersAndFillableAmounts> { diff --git a/packages/asset-buyer/src/types.ts b/packages/asset-buyer/src/types.ts index 3b573edca..84434aa7f 100644 --- a/packages/asset-buyer/src/types.ts +++ b/packages/asset-buyer/src/types.ts @@ -121,3 +121,11 @@ export interface OrdersAndFillableAmounts { orders: SignedOrder[]; remainingFillableMakerAssetAmounts: BigNumber[]; } + +/** + * Represents available liquidity for a given assetData + */ +export interface LiquidityForAssetData { + tokensAvailableInUnitAmount: number; + ethValueAvailableInWei: number; +} diff --git a/packages/asset-buyer/test/asset_buyer_test.ts b/packages/asset-buyer/test/asset_buyer_test.ts new file mode 100644 index 000000000..a109d1ae8 --- /dev/null +++ b/packages/asset-buyer/test/asset_buyer_test.ts @@ -0,0 +1,168 @@ +import { orderFactory } from '@0x/order-utils/lib/src/order_factory'; +import { Web3ProviderEngine } from '@0x/subproviders'; +import { SignedOrder } from '@0x/types'; +import { BigNumber } from '@0x/utils'; +import { Web3Wrapper } from '@0x/web3-wrapper'; +import * as chai from 'chai'; +import 'mocha'; +import * as TypeMoq from 'typemoq'; + +import { AssetBuyer } from '../src'; +import { constants } from '../src/constants'; +import { LiquidityForAssetData, OrderProvider, OrdersAndFillableAmounts } from '../src/types'; + +import { chaiSetup } from './utils/chai_setup'; +import { + mockAvailableAssetDatas, + mockedAssetBuyerWithOrdersAndFillableAmounts, + orderProviderMock, +} from './utils/mocks'; + +chaiSetup.configure(); +const expect = chai.expect; + +const FAKE_SRA_URL = 'https://fakeurl.com'; +const FAKE_ASSET_DATA = '0xf47261b00000000000000000000000001dc4c1cefef38a777b15aa20260a54e584b16c48'; +const TOKEN_DECIMALS = 18; +const WETH_DECIMALS = constants.ETHER_TOKEN_DECIMALS; + +const baseUnitAmount = (unitAmount: number, decimals = TOKEN_DECIMALS): BigNumber => { + return Web3Wrapper.toBaseUnitAmount(new BigNumber(unitAmount), decimals); +}; + +const expectLiquidityResult = async ( + web3Provider: Web3ProviderEngine, + orderProvider: OrderProvider, + ordersAndFillableAmounts: OrdersAndFillableAmounts, + expectedLiquidityResult: LiquidityForAssetData, +) => { + const mockedAssetBuyer = mockedAssetBuyerWithOrdersAndFillableAmounts( + web3Provider, + orderProvider, + FAKE_ASSET_DATA, + ordersAndFillableAmounts, + ); + const liquidityResult = await mockedAssetBuyer.object.getLiquidityForAssetDataAsync(FAKE_ASSET_DATA); + expect(liquidityResult).to.deep.equal(expectedLiquidityResult); +}; + +describe('AssetBuyer', () => { + describe('getLiquidityForAssetDataAsync', () => { + const mockWeb3Provider = TypeMoq.Mock.ofType(Web3ProviderEngine); + const mockOrderProvider = orderProviderMock(); + + beforeEach(() => { + mockWeb3Provider.reset(); + mockOrderProvider.reset(); + }); + + afterEach(() => { + mockWeb3Provider.verifyAll(); + mockOrderProvider.verifyAll(); + }); + + describe('validation', () => { + it('should ensure assetData is a string', async () => { + const assetBuyer = AssetBuyer.getAssetBuyerForStandardRelayerAPIUrl( + mockWeb3Provider.object, + FAKE_SRA_URL, + ); + + expect(assetBuyer.getLiquidityForAssetDataAsync(false as any)).to.be.rejectedWith( + 'Expected assetData to be of type string, encountered: false', + ); + }); + }); + + it('should return 0s when asset pair not supported', async () => { + mockAvailableAssetDatas(mockOrderProvider, FAKE_ASSET_DATA, []); + + const assetBuyer = new AssetBuyer(mockWeb3Provider.object, mockOrderProvider.object); + const liquidityResult = await assetBuyer.getLiquidityForAssetDataAsync(FAKE_ASSET_DATA); + expect(liquidityResult).to.deep.equal({ + tokensAvailableInUnitAmount: 0, + ethValueAvailableInWei: 0, + }); + }); + + describe('assetData is supported', () => { + // orders + const sellTwoTokensFor1Weth: SignedOrder = orderFactory.createSignedOrderFromPartial({ + makerAssetAmount: baseUnitAmount(2), + takerAssetAmount: baseUnitAmount(1, WETH_DECIMALS), + }); + const sellTenTokensFor10Weth: SignedOrder = orderFactory.createSignedOrderFromPartial({ + // tslint:disable-next-line:custom-no-magic-numbers + makerAssetAmount: baseUnitAmount(10), + // tslint:disable-next-line:custom-no-magic-numbers + takerAssetAmount: baseUnitAmount(10, WETH_DECIMALS), + }); + + beforeEach(() => { + mockAvailableAssetDatas(mockOrderProvider, FAKE_ASSET_DATA, [FAKE_ASSET_DATA]); + }); + + it('should return 0s when no orders available', async () => { + const ordersAndFillableAmounts: OrdersAndFillableAmounts = { + orders: [], + remainingFillableMakerAssetAmounts: [], + }; + const mockedAssetBuyer = mockedAssetBuyerWithOrdersAndFillableAmounts( + mockWeb3Provider.object, + mockOrderProvider.object, + FAKE_ASSET_DATA, + ordersAndFillableAmounts, + ); + + const liquidityResult = await mockedAssetBuyer.object.getLiquidityForAssetDataAsync(FAKE_ASSET_DATA); + expect(liquidityResult).to.deep.equal({ + tokensAvailableInUnitAmount: 0, + ethValueAvailableInWei: 0, + }); + }); + + it('should return correct computed value when orders provided with full fillableAmounts', async () => { + const orders: SignedOrder[] = [sellTwoTokensFor1Weth, sellTenTokensFor10Weth]; + const remainingFillableMakerAssetAmounts: BigNumber[] = orders.map(o => o.makerAssetAmount); + const mockedAssetBuyer = mockedAssetBuyerWithOrdersAndFillableAmounts( + mockWeb3Provider.object, + mockOrderProvider.object, + FAKE_ASSET_DATA, + { + orders, + remainingFillableMakerAssetAmounts, + }, + ); + + const expectedTokensAvailable = orders[0].makerAssetAmount.plus(orders[1].makerAssetAmount); + const expectedEthValueAvailable = orders[0].takerAssetAmount.plus(orders[1].takerAssetAmount); + + const liquidityResult = await mockedAssetBuyer.object.getLiquidityForAssetDataAsync(FAKE_ASSET_DATA); + expect(liquidityResult).to.deep.equal({ + tokensAvailableInUnitAmount: expectedTokensAvailable.toNumber(), + ethValueAvailableInWei: expectedEthValueAvailable.toNumber(), + }); + }); + + it('should return correct computed value with one partial fillableAmounts', async () => { + const ordersAndFillableAmounts = { + orders: [sellTwoTokensFor1Weth], + remainingFillableMakerAssetAmounts: [baseUnitAmount(1)], + }; + + const expectedResult = { + tokensAvailableInUnitAmount: baseUnitAmount(1).toNumber(), + // tslint:disable-next-line:custom-no-magic-numbers + ethValueAvailableInWei: baseUnitAmount(0.5, WETH_DECIMALS).toNumber(), + }; + + await expectLiquidityResult( + mockWeb3Provider.object, + mockOrderProvider.object, + ordersAndFillableAmounts, + expectedResult, + ); + }); + }); + }); +}); diff --git a/packages/asset-buyer/test/utils/mocks.ts b/packages/asset-buyer/test/utils/mocks.ts new file mode 100644 index 000000000..fe0d0cbf4 --- /dev/null +++ b/packages/asset-buyer/test/utils/mocks.ts @@ -0,0 +1,66 @@ +import { Web3ProviderEngine } from '@0x/subproviders'; +import * as TypeMoq from 'typemoq'; + +import { AssetBuyer } from '../../src/asset_buyer'; +import { OrderProvider, OrderProviderResponse, OrdersAndFillableAmounts } from '../../src/types'; + +// Implementing dummy class for using in mocks, see https://github.com/florinn/typemoq/issues/3 +class OrderProviderClass implements OrderProvider { + // tslint:disable-next-line:prefer-function-over-method + public async getOrdersAsync(): Promise<OrderProviderResponse> { + return Promise.resolve({ orders: [] }); + } + // tslint:disable-next-line:prefer-function-over-method + public async getAvailableMakerAssetDatasAsync(takerAssetData: string): Promise<string[]> { + return Promise.resolve([]); + } +} + +export const orderProviderMock = () => { + return TypeMoq.Mock.ofType(OrderProviderClass, TypeMoq.MockBehavior.Strict); +}; + +export const mockAvailableAssetDatas = ( + mockOrderProvider: TypeMoq.IMock<OrderProviderClass>, + assetData: string, + availableAssetDatas: string[], +) => { + mockOrderProvider + .setup(op => op.getAvailableMakerAssetDatasAsync(TypeMoq.It.isValue(assetData))) + .returns(() => { + return Promise.resolve(availableAssetDatas); + }) + .verifiable(TypeMoq.Times.once()); +}; + +const partiallyMockedAssetBuyer = ( + provider: Web3ProviderEngine, + orderProvider: OrderProvider, +): TypeMoq.IMock<AssetBuyer> => { + const rawAssetBuyer = new AssetBuyer(provider, orderProvider); + const mockedAssetBuyer = TypeMoq.Mock.ofInstance(rawAssetBuyer, TypeMoq.MockBehavior.Loose, false); + mockedAssetBuyer.callBase = true; + return mockedAssetBuyer; +}; + +const mockGetOrdersAndAvailableAmounts = ( + mockedAssetBuyer: TypeMoq.IMock<AssetBuyer>, + assetData: string, + ordersAndFillableAmounts: OrdersAndFillableAmounts, +): void => { + mockedAssetBuyer + .setup(a => a.getOrdersAndFillableAmountsAsync(assetData, false)) + .returns(() => Promise.resolve(ordersAndFillableAmounts)) + .verifiable(TypeMoq.Times.once()); +}; + +export const mockedAssetBuyerWithOrdersAndFillableAmounts = ( + provider: Web3ProviderEngine, + orderProvider: OrderProvider, + assetData: string, + ordersAndFillableAmounts: OrdersAndFillableAmounts, +): TypeMoq.IMock<AssetBuyer> => { + const mockedAssetBuyer = partiallyMockedAssetBuyer(provider, orderProvider); + mockGetOrdersAndAvailableAmounts(mockedAssetBuyer, assetData, ordersAndFillableAmounts); + return mockedAssetBuyer; +}; |