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

Cherry-pick changes for indexer v1.0.2 #787

Merged
merged 18 commits into from
Nov 10, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
5a28087
[IND-171]: Do not send subaccount websocket message for unplaced and …
Christopher-Li Oct 27, 2023
f564c79
[IND-458]: In case of errors in comlink log request (#722)
Christopher-Li Oct 31, 2023
567423a
Fix order handler to return correct updatedAt/updatedAtHeight (#733)
lcwik Nov 1, 2023
af09034
[IND-465] Add support for liquidation handler to use a single SQL fun…
lcwik Nov 2, 2023
d7376bd
[IND-467] Push ender market create logic to use a single sql function…
lcwik Nov 2, 2023
e4ed18b
[IND-468] Push ender market modify logic to use a single SQL function…
lcwik Nov 2, 2023
680779e
[IND-469] Update `ender` market price update handler to execute updat…
lcwik Nov 3, 2023
b3d3132
[IND-470] Update asset create handler to use SQL function. (#748)
lcwik Nov 3, 2023
88b6d24
[IND-475] Update ender `update clob pair` handler to execute via a SQ…
lcwik Nov 4, 2023
3713d55
[IND-476] Update ender update perpetual handler to execute updates vi…
lcwik Nov 6, 2023
2433894
[IND-473] Update ender perpetual market create to execute updates via…
lcwik Nov 6, 2023
69ed5ec
[IND-472] Update ender liquidity tier upsert to execute updates via a…
lcwik Nov 6, 2023
77b5707
[IND-450]: Prevent orders transitioning from canceled to best effort …
Christopher-Li Nov 6, 2023
d61033d
[IND-474] Update ender transfer handler to execute updates via a SQL …
lcwik Nov 6, 2023
26eb1ad
[IND-442] Don't send cancel messages if orders are fully filled in st…
vincentwschau Nov 7, 2023
ba2de87
[IND-471] Update ender funding to execute updates via a SQL function.…
lcwik Nov 7, 2023
73bd546
[IND-482]: Send timing fields for orders when possible (#768)
Christopher-Li Nov 8, 2023
31cc1af
[IND-477, IND-478, IND-479, IND-480] Update all stateful order handle…
lcwik Nov 8, 2023
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
1 change: 1 addition & 0 deletions indexer/packages/postgres/__tests__/helpers/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,7 @@ export const defaultOrderGoodTilBlockTime: OrderCreateObject = {
clientId: '2',
goodTilBlock: undefined,
goodTilBlockTime: '2023-01-22T00:00:00.000Z',
createdAtHeight: '1',
orderFlags: ORDER_FLAG_LONG_TERM.toString(),
};

Expand Down
10 changes: 10 additions & 0 deletions indexer/packages/postgres/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { CandleMessage_Resolution, ClobPairStatus } from '@dydxprotocol-indexer/v4-protos';

import config from './config';
import AssetModel from './models/asset-model';
import AssetPositionModel from './models/asset-position-model';
import FillModel from './models/fill-model';
import LiquidityTiersModel from './models/liquidity-tiers-model';
import MarketModel from './models/market-model';
import OraclePriceModel from './models/oracle-price-model';
import OrderModel from './models/order-model';
import PerpetualMarketModel from './models/perpetual-market-model';
import PerpetualPositionModel from './models/perpetual-position-model';
import SubaccountModel from './models/subaccount-model';
import TransferModel from './models/transfer-model';
import {
APITimeInForce,
CandleResolution,
Expand Down Expand Up @@ -81,12 +86,17 @@ export const TIME_IN_FORCE_TO_API_TIME_IN_FORCE: Record<TimeInForce, APITimeInFo

// A list of models that have sqlToJsonConversions defined.
export const SQL_TO_JSON_DEFINED_MODELS = [
AssetModel,
AssetPositionModel,
FillModel,
LiquidityTiersModel,
MarketModel,
OraclePriceModel,
OrderModel,
PerpetualMarketModel,
PerpetualPositionModel,
SubaccountModel,
TransferModel,
];

export type SpecifiedClobPairStatus =
Expand Down
2 changes: 1 addition & 1 deletion indexer/packages/postgres/src/helpers/db-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ $$ LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE;`;
return rawQuery(sqlFn, {}).catch((error) => {
logger.error({
at: 'dbHelpers#createModelToJsonFunctions',
message: `Failed to create or replace function dydx_to_json for model ${model.tableName}.`,
message: `Failed to create or replace function dydx_to_jsonb for model ${model.tableName}.`,
error,
});
throw error;
Expand Down
5 changes: 5 additions & 0 deletions indexer/packages/postgres/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,16 @@ export * from './constants';

export { default as Transaction } from './helpers/transaction';
export { postgresConfigSchema } from './config';
export { default as AssetModel } from './models/asset-model';
export { default as AssetPositionModel } from './models/asset-position-model';
export { default as FillModel } from './models/fill-model';
export { default as LiquidityTiersModel } from './models/liquidity-tiers-model';
export { default as MarketModel } from './models/market-model';
export { default as OraclePriceModel } from './models/oracle-price-model';
export { default as OrderModel } from './models/order-model';
export { default as PerpetualMarketModel } from './models/perpetual-market-model';
export { default as PerpetualPositionModel } from './models/perpetual-position-model';
export { default as TransferModel } from './models/transfer-model';

export * as AssetTable from './stores/asset-table';
export * as AssetPositionTable from './stores/asset-position-table';
Expand Down
34 changes: 29 additions & 5 deletions indexer/packages/postgres/src/lib/order-translations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,11 @@ import {
*
* @param order
*/
export async function convertToIndexerOrder(
export function convertToIndexerOrderWithSubaccount(
order: OrderFromDatabase,
perpetualMarket: PerpetualMarketFromDatabase,
): Promise<IndexerOrder> {
const subaccount: SubaccountFromDatabase | undefined = await SubaccountTable.findById(
order.subaccountId,
);
subaccount: SubaccountFromDatabase,
): IndexerOrder {
if (!OrderTable.isLongTermOrConditionalOrder(order.orderFlags)) {
logger.error({
at: 'protocol-translations#convertToIndexerOrder',
Expand Down Expand Up @@ -77,3 +75,29 @@ export async function convertToIndexerOrder(

return indexerOrder;
}

/**
* Converts an order from the database to an IndexerOrder proto.
* This is used to resend open stateful orders to Vulcan during Indexer fast sync
* to uncross the orderbook.
*
* @param order
*/
export async function convertToIndexerOrder(
order: OrderFromDatabase,
perpetualMarket: PerpetualMarketFromDatabase,
): Promise<IndexerOrder> {
const subaccount: SubaccountFromDatabase | undefined = await SubaccountTable.findById(
order.subaccountId,
);

if (!subaccount === undefined) {
logger.error({
at: 'protocol-translations#convertToIndexerOrder',
message: 'Subaccount for order not found',
order,
});
throw new Error(`Subaccount for order not found: ${order.subaccountId}`);
}
return convertToIndexerOrderWithSubaccount(order, perpetualMarket, subaccount!);
}
7 changes: 7 additions & 0 deletions indexer/packages/postgres/src/loops/market-refresher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ export async function updateMarkets(options?: Options): Promise<void> {
stats.timing(`${config.SERVICE_NAME}.loops.update_markets`, Date.now() - startTime);
}

/**
* Updates the markets map with the specified market.
*/
export function updateMarket(market: MarketFromDatabase): void {
idToMarket[market.id] = market;
}

/**
* Gets the market for a given id.
*/
Expand Down
16 changes: 16 additions & 0 deletions indexer/packages/postgres/src/models/asset-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,22 @@ export default class AssetModel extends Model {
};
}

/**
* A mapping from column name to JSON conversion expected.
* See getSqlConversionForDydxModelTypes for valid conversions.
*
* TODO(IND-239): Ensure that jsonSchema() / sqlToJsonConversions() / model fields match.
*/
static get sqlToJsonConversions() {
return {
id: 'string',
symbol: 'string',
atomicResolution: 'integer',
hasMarket: 'boolean',
marketId: 'integer',
};
}

id!: string;

symbol!: string;
Expand Down
2 changes: 1 addition & 1 deletion indexer/packages/postgres/src/models/fill-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ export default class FillModel extends Model {
transactionHash: { type: 'string' },
createdAt: { type: 'string', format: 'date-time' },
createdAtHeight: { type: 'string', pattern: IntegerPattern },
clientMetadata: { type: 'string', pattern: IntegerPattern },
clientMetadata: { type: ['string', 'null'], pattern: IntegerPattern },
fee: { type: 'string', pattern: NumericPattern },
},
};
Expand Down
16 changes: 16 additions & 0 deletions indexer/packages/postgres/src/models/liquidity-tiers-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,22 @@ export default class LiquidityTiersModel extends BaseModel {
};
}

/**
* A mapping from column name to JSON conversion expected.
* See getSqlConversionForDydxModelTypes for valid conversions.
*
* TODO(IND-239): Ensure that jsonSchema() / sqlToJsonConversions() / model fields match.
*/
static get sqlToJsonConversions() {
return {
id: 'integer',
name: 'string',
initialMarginPpm: 'string',
maintenanceFractionPpm: 'string',
basePositionNotional: 'string',
};
}

id!: number;

QueryBuilderType!: UpsertQueryBuilder<this>;
Expand Down
16 changes: 16 additions & 0 deletions indexer/packages/postgres/src/models/market-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,22 @@ export default class MarketModel extends Model {
};
}

/**
* A mapping from column name to JSON conversion expected.
* See getSqlConversionForDydxModelTypes for valid conversions.
*
* TODO(IND-239): Ensure that jsonSchema() / sqlToJsonConversions() / model fields match.
*/
static get sqlToJsonConversions() {
return {
id: 'integer',
pair: 'string',
exponent: 'integer',
minPriceChangePpm: 'integer',
oraclePrice: 'string',
};
}

id!: number;

pair!: string;
Expand Down
16 changes: 16 additions & 0 deletions indexer/packages/postgres/src/models/oracle-price-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,22 @@ export default class OraclePriceModel extends Model {
};
}

/**
* A mapping from column name to JSON conversion expected.
* See getSqlConversionForDydxModelTypes for valid conversions.
*
* TODO(IND-239): Ensure that jsonSchema() / sqlToJsonConversions() / model fields match.
*/
static get sqlToJsonConversions() {
return {
id: 'string',
marketId: 'integer',
price: 'string',
effectiveAt: 'date-time',
effectiveAtHeight: 'string',
};
}

id!: string;

marketId!: number;
Expand Down
22 changes: 22 additions & 0 deletions indexer/packages/postgres/src/models/transfer-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,28 @@ export default class TransferModel extends Model {
};
}

/**
* A mapping from column name to JSON conversion expected.
* See getSqlConversionForDydxModelTypes for valid conversions.
*
* TODO(IND-239): Ensure that jsonSchema() / sqlToJsonConversions() / model fields match.
*/
static get sqlToJsonConversions() {
return {
id: 'string',
senderSubaccountId: 'string',
recipientSubaccountId: 'string',
senderWalletAddress: 'string',
recipientWalletAddress: 'string',
assetId: 'string',
size: 'string',
eventId: 'hex-string',
transactionHash: 'string',
createdAt: 'date-time',
createdAtHeight: 'string',
};
}

id!: string;

senderSubaccountId?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
} from '../types';

export function uuid(subaccountId: string, assetId: string): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(Buffer.from(`${subaccountId}-${assetId}`, BUFFER_ENCODING_UTF_8));
}

Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/stores/candle-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
} from '../types';

export function uuid(startedAt: IsoString, ticker: string, resolution: CandleResolution): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(Buffer.from(`${startedAt}-${ticker}-${resolution}`, BUFFER_ENCODING_UTF_8));
}

Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/stores/fill-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
} from '../types';

export function uuid(eventId: Buffer, liquidity: Liquidity): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(Buffer.from(`${eventId.toString('hex')}-${liquidity}`, BUFFER_ENCODING_UTF_8));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export function uuid(
eventId: Buffer,
perpetualId: string,
): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(Buffer.from(`${blockHeight}-${eventId.toString('hex')}-${perpetualId}`, BUFFER_ENCODING_UTF_8));
}

Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/stores/oracle-price-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
export function uuid(
marketId: number, height: string,
): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(Buffer.from(`${marketId.toString()}-${height}`, BUFFER_ENCODING_UTF_8));
}

Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/stores/order-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export function uuid(
clobPairId: string,
orderFlags: string,
): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(
Buffer.from(
`${subaccountId}-${clientId}-${clobPairId}-${orderFlags}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ const DEFAULT_SUBACCOUNT_UPDATE_DEFAULT_POSITION_FIELDS = {
};

export function uuid(subaccountId: string, openEventId: Buffer): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(Buffer.from(`${subaccountId}-${openEventId.toString('hex')}`, BUFFER_ENCODING_UTF_8));
}

Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/stores/pnl-ticks-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export function uuid(
subaccountId: string,
createdAt: string,
): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(
Buffer.from(
`${subaccountId}-${createdAt}`,
Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/stores/subaccount-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
} from '../types';

export function uuid(address: string, subaccountNumber: number): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(Buffer.from(`${address}-${subaccountNumber}`, BUFFER_ENCODING_UTF_8));
}

Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/stores/transaction-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
} from '../types';

export function uuid(blockHeight: string, transactionIndex: number): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(Buffer.from(`${blockHeight}-${transactionIndex}`, BUFFER_ENCODING_UTF_8));
}

Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/stores/transfer-table.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export function uuid(
senderWalletAddress?: string,
recipientWalletAddress?: string,
): string {
// TODO(IND-483): Fix all uuid string substitutions to use Array.join.
return getUuid(
Buffer.from(
`${senderSubaccountId}-${recipientSubaccountId}-${senderWalletAddress}-${recipientWalletAddress}-${eventId.toString('hex')}-${assetId}`,
Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/types/db-model-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export interface OrderFromDatabase extends IdBasedModelFromDatabase {
updatedAtHeight: string;
goodTilBlock?: string;
goodTilBlockTime?: string;
// createdAtHeight is optional because short term orders do not have a createdAtHeight.
createdAtHeight?: string;
clientMetadata: string;
triggerPrice?: string;
Expand Down
1 change: 1 addition & 0 deletions indexer/packages/postgres/src/types/order-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export interface OrderCreateObject {
updatedAtHeight: string;
goodTilBlock?: string;
goodTilBlockTime?: string;
// createdAtHeight is optional because short term orders do not have a createdAtHeight.
createdAtHeight?: string;
clientMetadata: string;
triggerPrice?: string,
Expand Down
Loading