/
abci.go
288 lines (251 loc) · 10.2 KB
/
abci.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package clob
import (
"errors"
"fmt"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
liquidationtypes "github.com/dydxprotocol/v4-chain/protocol/daemons/server/types/liquidations"
indexerevents "github.com/dydxprotocol/v4-chain/protocol/indexer/events"
"github.com/dydxprotocol/v4-chain/protocol/indexer/indexer_manager"
indexershared "github.com/dydxprotocol/v4-chain/protocol/indexer/shared"
"github.com/dydxprotocol/v4-chain/protocol/lib"
"github.com/dydxprotocol/v4-chain/protocol/lib/metrics"
"github.com/dydxprotocol/v4-chain/protocol/x/clob/keeper"
"github.com/dydxprotocol/v4-chain/protocol/x/clob/types"
)
// BeginBlocker executes all ABCI BeginBlock logic respective to the clob module.
func BeginBlocker(
ctx sdk.Context,
keeper types.ClobKeeper,
) {
// Initialize the set of process proposer match events for the next block effectively
// removing any events that occurred in the last block.
keeper.MustSetProcessProposerMatchesEvents(
ctx,
types.ProcessProposerMatchesEvents{
BlockHeight: lib.MustConvertIntegerToUint32(ctx.BlockHeight()),
},
)
}
// EndBlocker executes all ABCI EndBlock logic respective to the clob module.
func EndBlocker(
ctx sdk.Context,
keeper keeper.Keeper,
) {
processProposerMatchesEvents := keeper.GetProcessProposerMatchesEvents(ctx)
// Prune any fill amounts from state which are now past their `pruneableBlockHeight`.
keeper.PruneStateFillAmountsForShortTermOrders(ctx)
// Prune expired stateful orders completely from state.
expiredStatefulOrderIds := keeper.RemoveExpiredStatefulOrdersTimeSlices(ctx, ctx.BlockTime())
for _, orderId := range expiredStatefulOrderIds {
// Remove the order fill amount from state.
keeper.RemoveOrderFillAmount(ctx, orderId)
// Delete the stateful order placement from state.
keeper.DeleteLongTermOrderPlacement(ctx, orderId)
// Emit an on-chain indexer event for Stateful Order Expiration.
keeper.GetIndexerEventManager().AddTxnEvent(
ctx,
indexerevents.SubtypeStatefulOrder,
indexer_manager.GetB64EncodedEventMessage(
indexerevents.NewStatefulOrderRemovalEvent(
orderId,
indexershared.OrderRemovalReason_ORDER_REMOVAL_REASON_EXPIRED,
),
),
)
telemetry.IncrCounterWithLabels(
[]string{types.ModuleName, metrics.Expired, metrics.StatefulOrderRemoved, metrics.Count},
1,
orderId.GetOrderIdLabels(),
)
}
// Prune expired untriggered conditional orders from the in-memory UntriggeredConditionalOrders struct.
keeper.PruneUntriggeredConditionalOrders(
expiredStatefulOrderIds,
processProposerMatchesEvents.PlacedStatefulCancellationOrderIds,
)
// Update the memstore with expired order ids.
// These expired stateful order ids will be purged from the memclob in `Commit`.
processProposerMatchesEvents.ExpiredStatefulOrderIds = expiredStatefulOrderIds
// Before triggering conditional orders, add newly-placed conditional orders to the clob keeper's
// in-memory UntriggeredConditionalOrders data structure to allow conditional orders to
// trigger in the same block they are placed. Skip triggering orders which have been cancelled
// or expired.
// TODO(CLOB-773) Support conditional order replacements. Ensure replacements are de-duplicated.
keeper.AddUntriggeredConditionalOrders(
ctx,
processProposerMatchesEvents.PlacedConditionalOrderIds,
lib.SliceToSet(processProposerMatchesEvents.GetPlacedStatefulCancellationOrderIds()),
lib.SliceToSet(expiredStatefulOrderIds),
)
// Poll out all triggered conditional orders from `UntriggeredConditionalOrders` and update state.
triggeredConditionalOrderIds := keeper.MaybeTriggerConditionalOrders(ctx)
// Update the memstore with conditional order ids triggered in the last block.
// These triggered conditional orders will be placed in the `PrepareCheckState``.
processProposerMatchesEvents.ConditionalOrderIdsTriggeredInLastBlock = triggeredConditionalOrderIds
// Write the ProcessProposerMatchcesEvents with all the EndBlocker updates to state.
keeper.MustSetProcessProposerMatchesEvents(
ctx,
processProposerMatchesEvents,
)
// Prune any rate limiting information that is no longer relevant.
keeper.PruneRateLimits(ctx)
}
// PrepareCheckState executes all ABCI PrepareCheckState logic respective to the clob module.
func PrepareCheckState(
ctx sdk.Context,
keeper *keeper.Keeper,
liquidatableSubaccountIds *liquidationtypes.LiquidatableSubaccountIds,
) {
// Get the events generated from processing the matches in the latest block.
processProposerMatchesEvents := keeper.GetProcessProposerMatchesEvents(ctx)
if ctx.BlockHeight() != int64(processProposerMatchesEvents.BlockHeight) {
panic(
fmt.Errorf(
"block height %d for ProcessProposerMatchesEvents does not equal current block height %d",
processProposerMatchesEvents.BlockHeight,
ctx.BlockHeight(),
),
)
}
// 1. Remove all operations in the local validators operations queue from the memclob.
localValidatorOperationsQueue, shortTermOrderTxBytes := keeper.MemClob.GetOperationsToReplay(ctx)
keeper.Logger(ctx).Debug(
"Clearing local operations queue",
"localValidatorOperationsQueue",
types.GetInternalOperationsQueueTextString(localValidatorOperationsQueue),
"block",
ctx.BlockHeight(),
)
keeper.MemClob.RemoveAndClearOperationsQueue(ctx, localValidatorOperationsQueue)
// 2. Purge invalid state from the memclob.
offchainUpdates := types.NewOffchainUpdates()
offchainUpdates = keeper.MemClob.PurgeInvalidMemclobState(
ctx,
processProposerMatchesEvents.OrderIdsFilledInLastBlock,
processProposerMatchesEvents.ExpiredStatefulOrderIds,
processProposerMatchesEvents.PlacedStatefulCancellationOrderIds,
processProposerMatchesEvents.RemovedStatefulOrderIds,
offchainUpdates,
)
// 3. Place all stateful order placements included in the last block on the memclob.
offchainUpdates = keeper.PlaceStatefulOrdersFromLastBlock(
ctx,
processProposerMatchesEvents.PlacedLongTermOrderIds,
offchainUpdates,
)
// 4. Place all conditional orders triggered in EndBlocker of last block on the memclob.
offchainUpdates = keeper.PlaceConditionalOrdersTriggeredInLastBlock(
ctx,
processProposerMatchesEvents.ConditionalOrderIdsTriggeredInLastBlock,
offchainUpdates,
)
// 5. Replay the local validator’s operations onto the book.
replayUpdates := keeper.MemClob.ReplayOperations(
ctx,
localValidatorOperationsQueue,
shortTermOrderTxBytes,
offchainUpdates,
)
// TODO(CLOB-275): Do not gracefully handle panics in `PrepareCheckState`.
if replayUpdates != nil {
offchainUpdates = replayUpdates
}
// 6. Get all potentially liquidatable subaccount IDs and attempt to liquidate them.
subaccountIds := liquidatableSubaccountIds.GetSubaccountIds()
telemetry.ModuleSetGauge(
types.ModuleName,
float32(len(subaccountIds)),
metrics.Liquidations,
metrics.LiquidatableSubaccountIds,
metrics.Count,
)
// Get the liquidation order for each subaccount.
liquidationOrders := make([]types.LiquidationOrder, 0)
for _, subaccountId := range subaccountIds {
// If attempting to liquidate a subaccount returns an error, panic.
liquidationOrder, err := keeper.MaybeGetLiquidationOrder(ctx, subaccountId)
if err != nil {
// Subaccount might not always be liquidatable since liquidation daemon runs
// in a separate goroutine and is not always in sync with the application.
// Therefore, if subaccount is not liquidatable, continue.
if errors.Is(err, types.ErrSubaccountNotLiquidatable) {
telemetry.IncrCounter(
1,
metrics.MaybeGetLiquidationOrder,
metrics.SubaccountsNotLiquidatable,
metrics.Count,
)
continue
}
// Panic on unexpected errors.
panic(err)
}
liquidationOrders = append(liquidationOrders, *liquidationOrder)
}
// Sort liquidation orders.
keeper.SortLiquidationOrders(ctx, liquidationOrders)
// Attempt to place each liquidation order and perform deleveraging if necessary.
numFilledLiquidations := uint32(0)
numAttemptedDeleveraging := uint32(0)
for i := 0; numFilledLiquidations < keeper.MaxLiquidationOrdersPerBlock && i < len(liquidationOrders); i++ {
optimisticallyFilledQuantums, _, err := keeper.PlacePerpetualLiquidation(ctx, liquidationOrders[i])
if err != nil {
keeper.Logger(ctx).Error(
fmt.Sprintf(
"Failed to liquidate subaccount. Liquidation Order: (%+v). Err: %v",
liquidationOrders[i],
err,
),
)
panic(err)
}
// Keep a count of partially and fully filled liquidations for this block.
if optimisticallyFilledQuantums > 0 {
numFilledLiquidations++
} else {
telemetry.IncrCounter(1, types.ModuleName, metrics.PrepareCheckState, metrics.UnfilledLiquidationOrders)
if numAttemptedDeleveraging < keeper.MaxDeleveragingAttemptsPerBlock {
// The liquidation order was unfilled. Try to deleverage the subaccount.
subaccountId := liquidationOrders[i].GetSubaccountId()
perpetualId := liquidationOrders[i].MustGetLiquidatedPerpetualId()
deltaQuantums := liquidationOrders[i].GetDeltaQuantums()
_, err := keeper.MaybeDeleverageSubaccount(ctx, subaccountId, perpetualId, deltaQuantums)
if err != nil {
keeper.Logger(ctx).Error(
"Failed to deleverage subaccount.",
"subaccount", liquidationOrders[i].GetSubaccountId(),
"perpetualId", liquidationOrders[i].MustGetLiquidatedPerpetualId(),
"baseQuantums", liquidationOrders[i].GetBaseQuantums().ToBigInt(),
"error", err,
)
panic(err)
}
numAttemptedDeleveraging++
}
}
}
telemetry.IncrCounter(
float32(numFilledLiquidations),
types.ModuleName,
metrics.PrepareCheckState,
metrics.NumMatchedLiquidationOrders,
)
telemetry.ModuleSetGauge(
types.ModuleName,
metrics.GetMetricValueFromBigInt(keeper.GetInsuranceFundBalance(ctx)),
metrics.InsuranceFundBalance,
)
// Send all off-chain Indexer events
keeper.SendOffchainMessages(offchainUpdates, nil, metrics.SendPrepareCheckStateOffchainUpdates)
newLocalValidatorOperationsQueue, _ := keeper.MemClob.GetOperationsToReplay(ctx)
keeper.Logger(ctx).Debug(
"Local operations queue after PrepareCheckState",
"newLocalValidatorOperationsQueue",
types.GetInternalOperationsQueueTextString(newLocalValidatorOperationsQueue),
"block",
ctx.BlockHeight(),
)
// Set per-orderbook gauges.
keeper.MemClob.SetMemclobGauges(ctx)
}