Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Log QuoteReport to Kibana #298

Merged
merged 24 commits into from
Aug 10, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,3 +95,6 @@ export const GST2_WALLET_ADDRESSES = {
export const MARKET_DEPTH_MAX_SAMPLES = 50;
export const MARKET_DEPTH_DEFAULT_DISTRIBUTION = 1.05;
export const MARKET_DEPTH_END_PRICE_SLIPPAGE_PERC = 20;

// Logging
export const NUMBER_SOURCES_PER_LOG_LINE = 12;
13 changes: 12 additions & 1 deletion src/handlers/swap_handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { RfqtRequestOpts, SwapQuoterError } from '@0x/asset-swapper';
import { BigNumber, NULL_ADDRESS } from '@0x/utils';
import * as express from 'express';
import * as HttpStatus from 'http-status-codes';
import _ = require('lodash');

import { CHAIN_ID, RFQT_API_KEY_WHITELIST } from '../config';
import {
Expand Down Expand Up @@ -34,6 +35,8 @@ import {
isWETHSymbolOrAddress,
} from '../utils/token_metadata_utils';

import { quoteReportUtils } from './../utils/quote_report_utils';

export class SwapHandlers {
private readonly _swapService: SwapService;
public static rootAsync(_req: express.Request, res: express.Response): void {
Expand Down Expand Up @@ -63,8 +66,16 @@ export class SwapHandlers {
makers: quote.orders.map(order => order.makerAddress),
},
});
if (quote.quoteReport && params.rfqt && params.rfqt.intentOnFilling) {
quoteReportUtils.logQuoteReport({
quoteReport: quote.quoteReport,
submissionBy: 'taker',
decodedUniqueId: quote.decodedUniqueId,
});
}
}
res.status(HttpStatus.OK).send(quote);
const cleanedQuote = _.omit(quote, 'quoteReport', 'decodedUniqueId');
res.status(HttpStatus.OK).send(cleanedQuote);
}
// tslint:disable-next-line:prefer-function-over-method
public async getSwapTokensAsync(_req: express.Request, res: express.Response): Promise<void> {
Expand Down
23 changes: 19 additions & 4 deletions src/services/meta_transaction_service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { Orderbook, SwapQuoter, SwapQuoteRequestOpts, SwapQuoterOpts } from '@0x/asset-swapper';
import {
MarketBuySwapQuote,
MarketSellSwapQuote,
Orderbook,
SwapQuoter,
SwapQuoteRequestOpts,
SwapQuoterOpts,
} from '@0x/asset-swapper';
import { ContractAddresses, getContractAddressesForChainOrThrow } from '@0x/contract-addresses';
import { ContractWrappers } from '@0x/contract-wrappers';
import { DevUtilsContract } from '@0x/contracts-dev-utils';
Expand Down Expand Up @@ -41,6 +48,7 @@ import {
ZeroExTransactionWithoutDomain,
} from '../types';
import { ethGasStationUtils } from '../utils/gas_station_utils';
import { quoteReportUtils } from '../utils/quote_report_utils';
import { serviceUtils } from '../utils/service_utils';
import { utils } from '../utils/utils';

Expand Down Expand Up @@ -111,7 +119,7 @@ export class MetaTransactionService {
rfqt: _rfqt,
};

let swapQuote;
let swapQuote: MarketSellSwapQuote | MarketBuySwapQuote | undefined;
feuGeneA marked this conversation as resolved.
Show resolved Hide resolved
if (sellAmount !== undefined) {
swapQuote = await this._swapQuoter.getMarketSellSwapQuoteAsync(
buyTokenAddress,
Expand All @@ -129,7 +137,7 @@ export class MetaTransactionService {
} else {
throw new Error('sellAmount or buyAmount required');
}
const { gasPrice } = swapQuote;
const { gasPrice, quoteReport } = swapQuote;
const { gas, protocolFeeInWeiAmount: protocolFee } = swapQuote.worstCaseQuoteInfo;
const makerAssetAmount = swapQuote.bestCaseQuoteInfo.makerAssetAmount;
const totalTakerAssetAmount = swapQuote.bestCaseQuoteInfo.totalTakerAssetAmount;
Expand Down Expand Up @@ -162,6 +170,7 @@ export class MetaTransactionService {
protocolFee,
minimumProtocolFee: protocolFee,
allowanceTarget,
quoteReport,
};
return response;
}
Expand All @@ -177,6 +186,7 @@ export class MetaTransactionService {
estimatedGas,
protocolFee,
minimumProtocolFee,
quoteReport,
} = await this.calculateMetaTransactionPriceAsync(params, 'quote');

const floatGasPrice = swapQuote.gasPrice;
Expand Down Expand Up @@ -206,6 +216,11 @@ export class MetaTransactionService {
)
.callAsync();

// log quote report and associate with txn hash if this is an RFQT firm quote
Copy link
Contributor

@alexkroeger alexkroeger Aug 5, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this mean we don't get a report if the meta TX didn't consider an RFQT quote?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right now all meta-txn calls are RFQT enabled b/c they all come from matcha.

for non-meta-txn calls I do limit it only to RFQT firm quotes (

if (quote.quoteReport && params.rfqt && params.rfqt.intentOnFilling) {
) since there will be a lot of verbose log lines emitted.

if we find this data useful for firm quotes we can consider opening up to all requests (as long as get confirmation from Oskar that our log serve can handle it)

if (quoteReport) {
quoteReportUtils.logQuoteReport({ submissionBy: 'metaTxn', quoteReport, zeroExTransactionHash });
}

const makerAssetAmount = swapQuote.bestCaseQuoteInfo.makerAssetAmount;
const totalTakerAssetAmount = swapQuote.bestCaseQuoteInfo.totalTakerAssetAmount;
const allowanceTarget = this._contractAddresses.erc20Proxy;
Expand Down Expand Up @@ -339,7 +354,7 @@ export class MetaTransactionService {
status: TransactionStates.Unsubmitted,
takerAddress: zeroExTransaction.signerAddress,
to: this._contractWrappers.exchange.address,
data,
data: data.affiliatedData,
value: protocolFee,
apiKey,
gasPrice: zeroExTransaction.gasPrice,
Expand Down
14 changes: 9 additions & 5 deletions src/services/swap_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,14 +121,14 @@ export class SwapService {
protocolFeeInWeiAmount: bestCaseProtocolFee,
} = attributedSwapQuote.bestCaseQuoteInfo;
const { protocolFeeInWeiAmount: protocolFee, gas: worstCaseGas } = attributedSwapQuote.worstCaseQuoteInfo;
const { orders, gasPrice, sourceBreakdown } = attributedSwapQuote;
const { orders, gasPrice, sourceBreakdown, quoteReport } = attributedSwapQuote;

const {
gasCost: affiliateFeeGasCost,
buyTokenFeeAmount,
sellTokenFeeAmount,
} = serviceUtils.getAffiliateFeeAmounts(swapQuote, affiliateFee);
const { to, value, data } = await this._getSwapQuotePartialTransactionAsync(
const { to, value, data, decodedUniqueId } = await this._getSwapQuotePartialTransactionAsync(
swapQuote,
isETHSell,
isETHBuy,
Expand Down Expand Up @@ -221,6 +221,8 @@ export class SwapService {
sources: serviceUtils.convertSourceBreakdownToArray(sourceBreakdown),
orders: serviceUtils.cleanSignedOrderFields(orders),
allowanceTarget,
decodedUniqueId,
quoteReport,
steveklebanoff marked this conversation as resolved.
Show resolved Hide resolved
};
return apiSwapQuote;
}
Expand Down Expand Up @@ -360,15 +362,16 @@ export class SwapService {
: this._wethContract.deposit()
).getABIEncodedTransactionData();
const value = isUnwrap ? ZERO : amount;
const affiliatedData = serviceUtils.attributeCallData(data, affiliateAddress);
const attributedCalldata = serviceUtils.attributeCallData(data, affiliateAddress);
// TODO: consider not using protocol fee utils due to lack of need for an aggresive gas price for wrapping/unwrapping
const gasPrice = providedGasPrice || (await this._swapQuoter.getGasPriceEstimationOrThrowAsync());
const gasEstimate = isUnwrap ? UNWRAP_QUOTE_GAS : WRAP_QUOTE_GAS;
const apiSwapQuote: GetSwapQuoteResponse = {
price: ONE,
guaranteedPrice: ONE,
to: this._wethContract.address,
data: affiliatedData,
data: attributedCalldata.affiliatedData,
decodedUniqueId: attributedCalldata.decodedUniqueId,
value,
gas: gasEstimate,
estimatedGas: gasEstimate,
Expand Down Expand Up @@ -537,11 +540,12 @@ export class SwapService {
toAddress: to,
} = await this._swapQuoteConsumer.getCalldataOrThrowAsync(swapQuote, opts);

const affiliatedData = serviceUtils.attributeCallData(data, affiliateAddress);
const { affiliatedData, decodedUniqueId } = serviceUtils.attributeCallData(data, affiliateAddress);
return {
to,
value,
data: affiliatedData,
decodedUniqueId,
};
}

Expand Down
4 changes: 4 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
ERC20BridgeSource,
MarketBuySwapQuote,
MarketSellSwapQuote,
QuoteReport,
RfqtRequestOpts,
SupportedProvider,
} from '@0x/asset-swapper';
Expand Down Expand Up @@ -395,6 +396,7 @@ export interface SwapQuoteResponsePartialTransaction {
to: string;
data: string;
value: BigNumber;
decodedUniqueId: string;
}

export interface SwapQuoteResponsePrice {
Expand All @@ -417,6 +419,7 @@ export interface GetSwapQuoteResponse extends SwapQuoteResponsePartialTransactio
estimatedGas: BigNumber;
estimatedGasTokenRefund: BigNumber;
allowanceTarget?: string;
quoteReport?: QuoteReport;
}

export interface Price {
Expand Down Expand Up @@ -476,6 +479,7 @@ export interface CalculateMetaTransactionPriceResponse {
protocolFee: BigNumber;
minimumProtocolFee: BigNumber;
estimatedGas: BigNumber;
quoteReport?: QuoteReport;
allowanceTarget?: string;
}

Expand Down
53 changes: 53 additions & 0 deletions src/utils/quote_report_utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { QuoteReport } from '@0x/asset-swapper';
import _ = require('lodash');

import { NUMBER_SOURCES_PER_LOG_LINE } from '../constants';
import { logger } from '../logger';

interface QuoteReportForTakerTxn {
quoteReport: QuoteReport;
submissionBy: 'taker';
decodedUniqueId: string;
}
interface QuoteReportForMetaTxn {
quoteReport: QuoteReport;
submissionBy: 'metaTxn';
zeroExTransactionHash: string;
}
type QuoteReportLogOptions = QuoteReportForTakerTxn | QuoteReportForMetaTxn;

export const quoteReportUtils = {
logQuoteReport(logOpts: QuoteReportLogOptions): void {
const qr = logOpts.quoteReport;

let logBase: { [key: string]: string | boolean } = {
firmQuoteReport: true,
submissionBy: logOpts.submissionBy,
};
if (logOpts.submissionBy === 'metaTxn') {
logBase = { ...logBase, zeroExTransactionHash: logOpts.zeroExTransactionHash };
} else if (logOpts.submissionBy === 'taker') {
logBase = { ...logBase, decodedUniqueId: logOpts.decodedUniqueId };
}

// Deliver in chunks since Kibana can't handle logs large requests
const sourcesConsideredChunks = _.chunk(qr.sourcesConsidered, NUMBER_SOURCES_PER_LOG_LINE);
sourcesConsideredChunks.forEach((chunk, i) => {
logger.info({
...logBase,
sourcesConsidered: chunk,
sourcesConsideredChunkIndex: i,
sourcesConsideredChunkLength: sourcesConsideredChunks.length,
});
});
const sourcesDeliveredChunks = _.chunk(qr.sourcesDelivered, NUMBER_SOURCES_PER_LOG_LINE);
sourcesDeliveredChunks.forEach((chunk, i) => {
logger.info({
...logBase,
sourcesDelivered: chunk,
sourcesDeliveredChunkIndex: i,
sourcesDeliveredChunkLength: sourcesDeliveredChunks.length,
});
});
},
};
10 changes: 8 additions & 2 deletions src/utils/service_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,13 @@ export const serviceUtils = {
return attributedSwapQuote;
},

attributeCallData(data: string, affiliateAddress?: string): string {
attributeCallData(
data: string,
affiliateAddress?: string,
): {
affiliatedData: string;
feuGeneA marked this conversation as resolved.
Show resolved Hide resolved
decodedUniqueId: string;
} {
const affiliateAddressOrDefault = affiliateAddress ? affiliateAddress : FEE_RECIPIENT_ADDRESS;
const affiliateCallDataEncoder = new AbiEncoder.Method({
constant: true,
Expand Down Expand Up @@ -89,7 +95,7 @@ export const serviceUtils = {
// Encode additional call data and return
const encodedAffiliateData = affiliateCallDataEncoder.encode([affiliateAddressOrDefault, uniqueIdentifier]);
const affiliatedData = `${data}${encodedAffiliateData.slice(2)}`;
return affiliatedData;
return { affiliatedData, decodedUniqueId: `${randomNumber}-${timestampInSeconds}` };
},

// tslint:disable-next-line:prefer-function-over-method
Expand Down
2 changes: 1 addition & 1 deletion test/service_utils_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ describe(SUITE_NAME, () => {
it('it returns a reasonable ID and timestamp', () => {
const fakeCallData = '0x0000000000000';
const fakeAffiliate = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee';
const attributedCallData = serviceUtils.attributeCallData(fakeCallData, fakeAffiliate);
const attributedCallData = serviceUtils.attributeCallData(fakeCallData, fakeAffiliate).affiliatedData;
const currentTime = new Date();

// parse out items from call data to ensure they are reasonable values
Expand Down