Skip to content
This repository has been archived by the owner on Jul 9, 2021. It is now read-only.

Commit

Permalink
streamline SwapQuoter and remove instant-only functions
Browse files Browse the repository at this point in the history
  • Loading branch information
xianny committed Oct 8, 2020
1 parent 0013c4e commit 4d2264c
Show file tree
Hide file tree
Showing 12 changed files with 411 additions and 1,271 deletions.
8 changes: 5 additions & 3 deletions contracts/integrations/test/aggregation/fill_test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { MarketBuySwapQuote, MarketSellSwapQuote, Orderbook, SwapQuoter } from '@0x/asset-swapper';
import { blockchainTests, expect, Numberish } from '@0x/contracts-test-utils';
import { assetDataUtils } from '@0x/order-utils';
import { FillResults, SignedOrder } from '@0x/types';
import { FillResults, MarketOperation, SignedOrder } from '@0x/types';
import { BigNumber, logUtils } from '@0x/utils';
import * as _ from 'lodash';

Expand Down Expand Up @@ -155,10 +155,11 @@ blockchainTests.live('Aggregator Mainnet Tests', env => {
const fillAmount = fromTokenUnits(takerSymbol, new BigNumber(fillValue).div(tokens[takerSymbol].price));
it(`sell ${toTokenUnits(takerSymbol, fillAmount)} ${takerSymbol} for ${makerSymbol}`, async () => {
const [quote, takerOrders] = await Promise.all([
swapQuoter.getMarketSellSwapQuoteAsync(
swapQuoter.getSwapQuoteAsync(
tokens[makerSymbol].address,
tokens[takerSymbol].address,
fillAmount,
MarketOperation.Sell,
{ gasPrice: GAS_PRICE },
),
getTakerOrdersAsync(takerSymbol),
Expand Down Expand Up @@ -199,10 +200,11 @@ blockchainTests.live('Aggregator Mainnet Tests', env => {
const fillAmount = fromTokenUnits(makerSymbol, new BigNumber(fillValue).div(tokens[makerSymbol].price));
it(`buy ${toTokenUnits(makerSymbol, fillAmount)} ${makerSymbol} with ${takerSymbol}`, async () => {
const [quote, takerOrders] = await Promise.all([
swapQuoter.getMarketBuySwapQuoteAsync(
swapQuoter.getSwapQuoteAsync(
tokens[makerSymbol].address,
tokens[takerSymbol].address,
fillAmount,
MarketOperation.Buy,
{ gasPrice: GAS_PRICE },
),
getTakerOrdersAsync(takerSymbol),
Expand Down
12 changes: 7 additions & 5 deletions packages/asset-swapper/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ const ONE_MINUTE_MS = ONE_SECOND_MS * ONE_MINUTE_SECS;
const DEFAULT_PER_PAGE = 1000;
const ZERO_AMOUNT = new BigNumber(0);

export const DEFAULT_INFO_LOGGER: LogFunction = (obj, msg) =>
logUtils.log(`${msg ? `${msg}: ` : ''}${JSON.stringify(obj)}`);
export const DEFAULT_WARNING_LOGGER: LogFunction = (obj, msg) =>
logUtils.warn(`${msg ? `${msg}: ` : ''}${JSON.stringify(obj)}`);

const DEFAULT_ORDER_PRUNER_OPTS: OrderPrunerOpts = {
expiryBufferMs: 120000, // 2 minutes
permittedOrderFeeTypes: new Set<OrderPrunerPermittedFeeTypes>([
Expand All @@ -50,6 +55,8 @@ const DEFAULT_SWAP_QUOTER_OPTS: SwapQuoterOpts = {
rfqt: {
takerApiKeyWhitelist: [],
makerAssetOfferings: {},
infoLogger: DEFAULT_INFO_LOGGER,
warningLogger: DEFAULT_WARNING_LOGGER,
},
};

Expand Down Expand Up @@ -90,11 +97,6 @@ const DEFAULT_RFQT_REQUEST_OPTS: Partial<RfqtRequestOpts> = {
makerEndpointMaxResponseTimeMs: 1000,
};

export const DEFAULT_INFO_LOGGER: LogFunction = (obj, msg) =>
logUtils.log(`${msg ? `${msg}: ` : ''}${JSON.stringify(obj)}`);
export const DEFAULT_WARNING_LOGGER: LogFunction = (obj, msg) =>
logUtils.warn(`${msg ? `${msg}: ` : ''}${JSON.stringify(obj)}`);

export const constants = {
ETH_GAS_STATION_API_URL,
PROTOCOL_FEE_MULTIPLIER,
Expand Down
796 changes: 335 additions & 461 deletions packages/asset-swapper/src/swap_quoter.ts

Large diffs are not rendered by default.

29 changes: 0 additions & 29 deletions packages/asset-swapper/src/utils/calculate_liquidity.ts

This file was deleted.

50 changes: 10 additions & 40 deletions packages/asset-swapper/src/utils/market_operation_utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,20 +349,25 @@ export class MarketOperationUtils {
}

/**
* gets the orders required for a market sell operation by (potentially) merging native orders with
* gets the orders required for a market sell or buy operation by (potentially) merging native orders with
* generated bridge orders.
* @param nativeOrders Native orders.
* @param takerAmount Amount of taker asset to sell.
* @param fillAmount Amount of taker asset to sell (when getting sell orders) or amount of maker asset to buy (when getting buy orders)
* @param marketOperation Buy or Sell
* @param opts Options object.
* @return object with optimized orders and a QuoteReport
*/
public async getMarketSellOrdersAsync(
public async getMarketOrdersAsync(
nativeOrders: SignedOrder[],
takerAmount: BigNumber,
fillAmount: BigNumber,
marketOperation: MarketOperation,
opts?: Partial<GetMarketOrdersOpts>,
): Promise<OptimizerResult> {
const _opts = { ...DEFAULT_GET_MARKET_ORDERS_OPTS, ...opts };
const marketSideLiquidity = await this.getMarketSellLiquidityAsync(nativeOrders, takerAmount, _opts);
const marketSideLiquidity =
marketOperation === MarketOperation.Sell
? await this.getMarketSellLiquidityAsync(nativeOrders, fillAmount, _opts)
: await this.getMarketBuyLiquidityAsync(nativeOrders, fillAmount, _opts);
const optimizerResult = await this._generateOptimizedOrdersAsync(marketSideLiquidity, {
bridgeSlippage: _opts.bridgeSlippage,
maxFallbackSlippage: _opts.maxFallbackSlippage,
Expand All @@ -385,41 +390,6 @@ export class MarketOperationUtils {
return { ...optimizerResult, quoteReport };
}

/**
* gets the orders required for a market buy operation by (potentially) merging native orders with
* generated bridge orders.
* @param nativeOrders Native orders.
* @param makerAmount Amount of maker asset to buy.
* @param opts Options object.
* @return object with optimized orders and a QuoteReport
*/
public async getMarketBuyOrdersAsync(
nativeOrders: SignedOrder[],
makerAmount: BigNumber,
opts?: Partial<GetMarketOrdersOpts>,
): Promise<OptimizerResult> {
const _opts = { ...DEFAULT_GET_MARKET_ORDERS_OPTS, ...opts };
const marketSideLiquidity = await this.getMarketBuyLiquidityAsync(nativeOrders, makerAmount, _opts);
const optimizerResult = await this._generateOptimizedOrdersAsync(marketSideLiquidity, {
bridgeSlippage: _opts.bridgeSlippage,
maxFallbackSlippage: _opts.maxFallbackSlippage,
excludedSources: _opts.excludedSources,
feeSchedule: _opts.feeSchedule,
exchangeProxyOverhead: _opts.exchangeProxyOverhead,
allowFallback: _opts.allowFallback,
});
let quoteReport: QuoteReport | undefined;
if (_opts.shouldGenerateQuoteReport) {
quoteReport = MarketOperationUtils._computeQuoteReport(
nativeOrders,
_opts.rfqt ? _opts.rfqt.quoteRequestor : undefined,
marketSideLiquidity,
optimizerResult,
);
}
return { ...optimizerResult, quoteReport };
}

/**
* gets the orders required for a batch of market buy operations by (potentially) merging native orders with
* generated bridge orders.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,7 @@ import { BigNumber } from '@0x/utils';
import { MarketOperation } from '../../types';

import { POSITIVE_INF, SOURCE_FLAGS, ZERO_AMOUNT } from './constants';
import {
createBridgeOrder,
createNativeOrder,
CreateOrderFromPathOpts,
getMakerTakerTokens,
} from './orders';
import { createBridgeOrder, createNativeOrder, CreateOrderFromPathOpts, getMakerTakerTokens } from './orders';
import { getCompleteRate, getRate } from './rate_utils';
import {
CollapsedFill,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ export type FeeSchedule = Partial<{ [key in ERC20BridgeSource]: FeeEstimate }>;
export type ExchangeProxyOverhead = (sourceFlags: number) => BigNumber;

/**
* Options for `getMarketSellOrdersAsync()` and `getMarketBuyOrdersAsync()`.
* Options for `getMarketOrdersAsync()`.
*/
export interface GetMarketOrdersOpts {
/**
Expand Down
Loading

0 comments on commit 4d2264c

Please sign in to comment.