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

[IND-461] handle deleveraging events #730

Merged
merged 31 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,62 @@ export interface OrderFillEventV1SDKType {

total_filled_taker: Long;
}
/**
* DeleveragingEvent message contains all the information for a deleveraging
* on the dYdX chain. This includes the liquidated/offsetting subaccounts and the
* amount filled.
*/

export interface DeleveragingEventV1 {
/** ID of the subaccount that was liquidated. */
liquidated?: IndexerSubaccountId;
/** ID of the subaccount that was used to offset the position. */

offsetting?: IndexerSubaccountId;
/** The ID of the clob pair that was liquidated. */

clobPairId: number;
/**
* The amount filled between the liquidated and offsetting position, in
* base quantums.
*/

fillAmount: Long;
/** The closing price in subticks. */

subticks: Long;
/** `true` if liquidating a short position, `false` otherwise. */

isBuy: boolean;
}
/**
* DeleveragingEvent message contains all the information for a deleveraging
* on the dYdX chain. This includes the liquidated/offsetting subaccounts and the
* amount filled.
*/

export interface DeleveragingEventV1SDKType {
/** ID of the subaccount that was liquidated. */
liquidated?: IndexerSubaccountIdSDKType;
/** ID of the subaccount that was used to offset the position. */

offsetting?: IndexerSubaccountIdSDKType;
/** The ID of the clob pair that was liquidated. */

clob_pair_id: number;
/**
* The amount filled between the liquidated and offsetting position, in
* base quantums.
*/

fill_amount: Long;
/** The closing price in subticks. */

subticks: Long;
/** `true` if liquidating a short position, `false` otherwise. */

is_buy: boolean;
}
/**
* LiquidationOrder represents the liquidation taker order to be included in a
* liquidation order fill event.
Expand Down Expand Up @@ -1719,6 +1775,101 @@ export const OrderFillEventV1 = {

};

function createBaseDeleveragingEventV1(): DeleveragingEventV1 {
return {
liquidated: undefined,
offsetting: undefined,
clobPairId: 0,
fillAmount: Long.UZERO,
subticks: Long.UZERO,
isBuy: false
};
}

export const DeleveragingEventV1 = {
encode(message: DeleveragingEventV1, writer: _m0.Writer = _m0.Writer.create()): _m0.Writer {
if (message.liquidated !== undefined) {
IndexerSubaccountId.encode(message.liquidated, writer.uint32(10).fork()).ldelim();
}

if (message.offsetting !== undefined) {
IndexerSubaccountId.encode(message.offsetting, writer.uint32(18).fork()).ldelim();
}

if (message.clobPairId !== 0) {
writer.uint32(24).uint32(message.clobPairId);
}

if (!message.fillAmount.isZero()) {
writer.uint32(32).uint64(message.fillAmount);
}

if (!message.subticks.isZero()) {
writer.uint32(40).uint64(message.subticks);
}

if (message.isBuy === true) {
writer.uint32(48).bool(message.isBuy);
}

return writer;
},

decode(input: _m0.Reader | Uint8Array, length?: number): DeleveragingEventV1 {
const reader = input instanceof _m0.Reader ? input : new _m0.Reader(input);
let end = length === undefined ? reader.len : reader.pos + length;
const message = createBaseDeleveragingEventV1();

while (reader.pos < end) {
const tag = reader.uint32();

switch (tag >>> 3) {
case 1:
message.liquidated = IndexerSubaccountId.decode(reader, reader.uint32());
break;

case 2:
message.offsetting = IndexerSubaccountId.decode(reader, reader.uint32());
break;

case 3:
message.clobPairId = reader.uint32();
break;

case 4:
message.fillAmount = (reader.uint64() as Long);
break;

case 5:
message.subticks = (reader.uint64() as Long);
break;

case 6:
message.isBuy = reader.bool();
break;

default:
reader.skipType(tag & 7);
break;
}
}

return message;
},

fromPartial(object: DeepPartial<DeleveragingEventV1>): DeleveragingEventV1 {
const message = createBaseDeleveragingEventV1();
message.liquidated = object.liquidated !== undefined && object.liquidated !== null ? IndexerSubaccountId.fromPartial(object.liquidated) : undefined;
message.offsetting = object.offsetting !== undefined && object.offsetting !== null ? IndexerSubaccountId.fromPartial(object.offsetting) : undefined;
message.clobPairId = object.clobPairId ?? 0;
message.fillAmount = object.fillAmount !== undefined && object.fillAmount !== null ? Long.fromValue(object.fillAmount) : Long.UZERO;
message.subticks = object.subticks !== undefined && object.subticks !== null ? Long.fromValue(object.subticks) : Long.UZERO;
message.isBuy = object.isBuy ?? false;
return message;
}

};

function createBaseLiquidationOrderV1(): LiquidationOrderV1 {
return {
liquidated: undefined,
Expand Down
14 changes: 13 additions & 1 deletion indexer/services/ender/__tests__/helpers/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ import {
OrderRemovalReason,
AssetCreateEventV1,
PerpetualMarketCreateEventV1,
ClobPairStatus, LiquidityTierUpsertEventV1, UpdatePerpetualEventV1, UpdateClobPairEventV1,
ClobPairStatus,
LiquidityTierUpsertEventV1,
UpdatePerpetualEventV1,
UpdateClobPairEventV1,
DeleveragingEventV1,
} from '@dydxprotocol-indexer/v4-protos';
import Long from 'long';
import { DateTime } from 'luxon';
Expand Down Expand Up @@ -276,6 +280,14 @@ export const defaultTransferEvent: TransferEventV1 = {
subaccountId: defaultRecipientSubaccountId,
},
};
export const defaultDeleveragingEvent: DeleveragingEventV1 = {
liquidated: defaultSenderSubaccountId,
offsetting: defaultRecipientSubaccountId,
clobPairId: 0,
fillAmount: Long.fromValue(10_000, true),
subticks: Long.fromValue(1_000_000_000, true),
isBuy: true,
};
export const defaultDepositEvent: TransferEventV1 = {
assetId: 0,
amount: Long.fromValue(100, true),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import { logger, ParseMessageError } from '@dydxprotocol-indexer/base';
import { DeleveragingEventV1, IndexerTendermintBlock, IndexerTendermintEvent } from '@dydxprotocol-indexer/v4-protos';
import { DydxIndexerSubtypes } from '../../src/lib/types';
import { DeleveragingValidator } from '../../src/validators/deleveraging-validator';
import {
defaultDeleveragingEvent, defaultHeight, defaultTime, defaultTxHash,
} from '../helpers/constants';
import { createIndexerTendermintBlock, createIndexerTendermintEvent } from '../helpers/indexer-proto-helpers';
import { expectDidntLogError, expectLoggedParseMessageError } from '../helpers/validator-helpers';

describe('deleveraging-validator', () => {
beforeEach(() => {
jest.spyOn(logger, 'error');
});

afterEach(() => {
jest.clearAllMocks();
});

describe('validate', () => {
it('does not throw error on valid deleveraging', () => {
const validator: DeleveragingValidator = new DeleveragingValidator(
defaultDeleveragingEvent,
createBlock(defaultDeleveragingEvent),
);

validator.validate();
expectDidntLogError();
});

it.each([
[
'does not contain liquidated',
{
...defaultDeleveragingEvent,
liquidated: undefined,
},
'DeleveragingEvent must have a liquidated subaccount id',
],
[
'does not contain offsetting',
{
...defaultDeleveragingEvent,
offsetting: undefined,
},
'DeleveragingEvent must have an offsetting subaccount id',
],
])('throws error if event %s', (_message: string, event: DeleveragingEventV1, message: string) => {
const validator: DeleveragingValidator = new DeleveragingValidator(
event,
createBlock(event),
);

expect(() => validator.validate()).toThrow(new ParseMessageError(message));
expectLoggedParseMessageError(
DeleveragingValidator.name,
message,
{ event },
);
});
});
});

function createBlock(
deleveragingEvent: DeleveragingEventV1,
): IndexerTendermintBlock {
const event: IndexerTendermintEvent = createIndexerTendermintEvent(
DydxIndexerSubtypes.DELEVERAGING,
DeleveragingEventV1.encode(deleveragingEvent).finish(),
0,
0,
);

return createIndexerTendermintBlock(
defaultHeight,
defaultTime,
[event],
[defaultTxHash],
);
}
18 changes: 18 additions & 0 deletions indexer/services/ender/src/handlers/deleveraging-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { DeleveragingEventV1 } from '@dydxprotocol-indexer/v4-protos';

import { ConsolidatedKafkaEvent } from '../lib/types';
import { Handler } from './handler';

export class DeleveragingHandler extends Handler<DeleveragingEventV1> {
eventType: string = 'DeleveragingEvent';

Copy link
Contributor

Choose a reason for hiding this comment

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

The eventType property is hardcoded as 'DeleveragingEvent'. This is fine if the class is only intended to handle this specific event type. However, if the class is expected to handle multiple event types, consider making eventType a parameter in the constructor.

public getParallelizationIds(): string[] {
return [];
}

// eslint-disable-next-line @typescript-eslint/require-await
public async internalHandle(): Promise<ConsolidatedKafkaEvent[]> {
// Implement this
return [];
}
}
2 changes: 2 additions & 0 deletions indexer/services/ender/src/lib/block-processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import _ from 'lodash';

import { Handler } from '../handlers/handler';
import { AssetValidator } from '../validators/asset-validator';
import { DeleveragingValidator } from '../validators/deleveraging-validator';
import { FundingValidator } from '../validators/funding-validator';
import { LiquidityTierValidator } from '../validators/liquidity-tier-validator';
import { MarketValidator } from '../validators/market-validator';
Expand Down Expand Up @@ -35,6 +36,7 @@ const TXN_EVENT_SUBTYPE_VERSION_TO_VALIDATOR_MAPPING: Record<string, ValidatorIn
[serializeSubtypeAndVersion(DydxIndexerSubtypes.LIQUIDITY_TIER.toString(), 1)]: LiquidityTierValidator,
[serializeSubtypeAndVersion(DydxIndexerSubtypes.UPDATE_PERPETUAL.toString(), 1)]: UpdatePerpetualValidator,
[serializeSubtypeAndVersion(DydxIndexerSubtypes.UPDATE_CLOB_PAIR.toString(), 1)]: UpdateClobPairValidator,
[serializeSubtypeAndVersion(DydxIndexerSubtypes.DELEVERAGING.toString(), 1)]: DeleveragingValidator,
};

const BLOCK_EVENT_SUBTYPE_VERSION_TO_VALIDATOR_MAPPING: Record<string, ValidatorInitializer> = {
Expand Down
7 changes: 7 additions & 0 deletions indexer/services/ender/src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
LiquidityTierUpsertEventV1,
UpdatePerpetualEventV1,
UpdateClobPairEventV1,
DeleveragingEventV1,
} from '@dydxprotocol-indexer/v4-protos';
import Long from 'long';

Expand All @@ -47,6 +48,7 @@ export enum DydxIndexerSubtypes {
LIQUIDITY_TIER = 'liquidity_tier',
UPDATE_PERPETUAL = 'update_perpetual',
UPDATE_CLOB_PAIR = 'update_clob_pair',
DELEVERAGING = 'deleveraging',
}

// Generic interface used for creating the Handler objects
Expand Down Expand Up @@ -113,6 +115,11 @@ export type EventProtoWithTypeAndVersion = {
eventProto: UpdateClobPairEventV1,
indexerTendermintEvent: IndexerTendermintEvent,
version: number,
} | {
type: DydxIndexerSubtypes.DELEVERAGING,
eventProto: DeleveragingEventV1,
indexerTendermintEvent: IndexerTendermintEvent,
version: number,
});

// Events grouped into events block events and events for each transactionIndex
Expand Down
38 changes: 38 additions & 0 deletions indexer/services/ender/src/validators/deleveraging-validator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { IndexerTendermintEvent, DeleveragingEventV1 } from '@dydxprotocol-indexer/v4-protos';

import { DeleveragingHandler } from '../handlers/deleveraging-handler';
import { Handler } from '../handlers/handler';
import { Validator } from './validator';

export class DeleveragingValidator extends Validator<DeleveragingEventV1> {
public validate(): void {
if (this.event.liquidated === undefined) {
return this.logAndThrowParseMessageError(
'DeleveragingEvent must have a liquidated subaccount id',
{ event: this.event },
);
}

if (this.event.offsetting === undefined) {
return this.logAndThrowParseMessageError(
'DeleveragingEvent must have an offsetting subaccount id',
{ event: this.event },
);
}

}

public createHandlers(
indexerTendermintEvent: IndexerTendermintEvent,
txId: number,
): Handler<DeleveragingEventV1>[] {
return [
new DeleveragingHandler(
this.block,
indexerTendermintEvent,
txId,
this.event,
),
];
}
}
Loading
Loading