-
Notifications
You must be signed in to change notification settings - Fork 0
/
abci.go
219 lines (192 loc) · 7.92 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
package clob
import (
"fmt"
"time"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
liquidationtypes "github.com/furyanprotocol/v4-chain/protocol/daemons/server/types/liquidations"
indexerevents "github.com/furyanprotocol/v4-chain/protocol/indexer/events"
"github.com/furyanprotocol/v4-chain/protocol/indexer/indexer_manager"
indexershared "github.com/furyanprotocol/v4-chain/protocol/indexer/shared"
"github.com/furyanprotocol/v4-chain/protocol/lib"
"github.com/furyanprotocol/v4-chain/protocol/lib/metrics"
"github.com/furyanprotocol/v4-chain/protocol/x/clob/keeper"
"github.com/furyanprotocol/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,
indexerevents.StatefulOrderEventVersion,
indexer_manager.GetBytes(
indexerevents.NewStatefulOrderRemovalEvent(
orderId,
indexershared.OrderRemovalReason_ORDER_REMOVAL_REASON_EXPIRED,
),
),
)
metrics.IncrCounterWithLabels(
metrics.ClobExpiredStatefulOrders,
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.UniqueSliceToSet(processProposerMatchesEvents.GetPlacedStatefulCancellationOrderIds()),
lib.UniqueSliceToSet(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)
// Emit relevant metrics at the end of every block.
metrics.SetGauge(
metrics.InsuranceFundBalance,
metrics.GetMetricValueFromBigInt(keeper.GetInsuranceFundBalance(ctx)),
)
}
// PrepareCheckState executes all ABCI PrepareCheckState logic respective to the clob module.
func PrepareCheckState(
ctx sdk.Context,
keeper *keeper.Keeper,
daemonLiquidationInfo *liquidationtypes.DaemonLiquidationInfo,
) {
// 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.
// Note telemetry is measured outside of the function call because `PlaceStatefulOrdersFromLastBlock`
// is called within `PlaceConditionalOrdersTriggeredInLastBlock`.
startPlaceLongTermOrders := time.Now()
offchainUpdates = keeper.PlaceStatefulOrdersFromLastBlock(
ctx,
processProposerMatchesEvents.PlacedLongTermOrderIds,
offchainUpdates,
)
telemetry.MeasureSince(
startPlaceLongTermOrders,
types.ModuleName,
metrics.PlaceLongTermOrdersFromLastBlock,
metrics.Latency,
)
telemetry.SetGauge(
float32(len(processProposerMatchesEvents.PlacedLongTermOrderIds)),
types.ModuleName,
metrics.PlaceLongTermOrdersFromLastBlock,
metrics.Count,
)
// 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 := daemonLiquidationInfo.GetLiquidatableSubaccountIds()
if err := keeper.LiquidateSubaccountsAgainstOrderbook(ctx, subaccountIds); err != nil {
panic(err)
}
// 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)
}