-
Notifications
You must be signed in to change notification settings - Fork 93
/
limit_order_tranche.go
283 lines (245 loc) · 8.49 KB
/
limit_order_tranche.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
package keeper
import (
"encoding/binary"
"fmt"
"time"
"cosmossdk.io/math"
"cosmossdk.io/store/prefix"
storetypes "cosmossdk.io/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/neutron-org/neutron/v4/x/dex/types"
"github.com/neutron-org/neutron/v4/x/dex/utils"
)
func NewLimitOrderTranche(
limitOrderTrancheKey *types.LimitOrderTrancheKey,
goodTil *time.Time,
) (*types.LimitOrderTranche, error) {
priceTakerToMaker, err := limitOrderTrancheKey.PriceTakerToMaker()
if err != nil {
return nil, err
}
return &types.LimitOrderTranche{
Key: limitOrderTrancheKey,
ReservesMakerDenom: math.ZeroInt(),
ReservesTakerDenom: math.ZeroInt(),
TotalMakerDenom: math.ZeroInt(),
TotalTakerDenom: math.ZeroInt(),
ExpirationTime: goodTil,
PriceTakerToMaker: priceTakerToMaker,
}, nil
}
func (k Keeper) FindLimitOrderTranche(
ctx sdk.Context,
limitOrderTrancheKey *types.LimitOrderTrancheKey,
) (val *types.LimitOrderTranche, fromFilled, found bool) {
// Try to find the tranche in the active liq index
tick := k.GetLimitOrderTranche(ctx, limitOrderTrancheKey)
if tick != nil {
return tick, false, true
}
// Look for filled limit orders
tranche, found := k.GetInactiveLimitOrderTranche(ctx, limitOrderTrancheKey)
if found {
return tranche, true, true
}
return nil, false, false
}
func (k Keeper) SaveTranche(ctx sdk.Context, tranche *types.LimitOrderTranche) {
if tranche.HasTokenIn() {
k.SetLimitOrderTranche(ctx, tranche)
} else {
k.SetInactiveLimitOrderTranche(ctx, tranche)
k.RemoveLimitOrderTranche(ctx, tranche.Key)
ctx.EventManager().EmitEvents(types.GetEventsDecTotalOrders(tranche.Key.TradePairId))
}
ctx.EventManager().EmitEvent(types.CreateTickUpdateLimitOrderTranche(tranche))
}
func (k Keeper) SetLimitOrderTranche(ctx sdk.Context, tranche *types.LimitOrderTranche) {
// Wrap tranche back into TickLiquidity
tick := types.TickLiquidity{
Liquidity: &types.TickLiquidity_LimitOrderTranche{
LimitOrderTranche: tranche,
},
}
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.TickLiquidityKeyPrefix))
b := k.cdc.MustMarshal(&tick)
store.Set(tranche.Key.KeyMarshal(), b)
}
func (k Keeper) GetLimitOrderTranche(
ctx sdk.Context,
limitOrderTrancheKey *types.LimitOrderTrancheKey,
) (tranche *types.LimitOrderTranche) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.TickLiquidityKeyPrefix))
b := store.Get(limitOrderTrancheKey.KeyMarshal())
if b == nil {
return nil
}
var tick types.TickLiquidity
k.cdc.MustUnmarshal(b, &tick)
return tick.GetLimitOrderTranche()
}
func (k Keeper) GetLimitOrderTrancheByKey(
ctx sdk.Context,
key []byte,
) (tranche *types.LimitOrderTranche, found bool) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.TickLiquidityKeyPrefix))
b := store.Get(key)
if b == nil {
return nil, false
}
var tick types.TickLiquidity
k.cdc.MustUnmarshal(b, &tick)
tranche = tick.GetLimitOrderTranche()
if tranche != nil {
return tranche, true
}
return nil, false
}
func (k Keeper) RemoveLimitOrderTranche(ctx sdk.Context, trancheKey *types.LimitOrderTrancheKey) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.TickLiquidityKeyPrefix))
store.Delete(trancheKey.KeyMarshal())
}
func (k Keeper) GetGTCPlaceTranche(
sdkCtx sdk.Context,
tradePairID *types.TradePairID,
tickIndexTakerToMaker int64,
) *types.LimitOrderTranche {
prefixStore := prefix.NewStore(
sdkCtx.KVStore(k.storeKey),
types.TickLiquidityLimitOrderPrefix(tradePairID, tickIndexTakerToMaker),
)
iter := prefixStore.Iterator(nil, nil)
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var tick types.TickLiquidity
k.cdc.MustUnmarshal(iter.Value(), &tick)
tranche := tick.GetLimitOrderTranche()
// Make sure tranche has not been traded through and is a GTC tranche
if tranche.IsPlaceTranche() && !tranche.HasExpiration() {
return tranche
}
}
return nil
}
func (k Keeper) GetFillTranche(
sdkCtx sdk.Context,
tradePairID *types.TradePairID,
tickIndexTakerToMaker int64,
) (*types.LimitOrderTranche, bool) {
prefixStore := prefix.NewStore(
sdkCtx.KVStore(k.storeKey),
types.TickLiquidityLimitOrderPrefix(tradePairID, tickIndexTakerToMaker),
)
iter := storetypes.KVStorePrefixIterator(prefixStore, []byte{})
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var tick types.TickLiquidity
k.cdc.MustUnmarshal(iter.Value(), &tick)
return tick.GetLimitOrderTranche(), true
}
return &types.LimitOrderTranche{}, false
}
func (k Keeper) GetAllLimitOrderTrancheAtIndex(
sdkCtx sdk.Context,
tradePairID *types.TradePairID,
tickIndexTakerToMaker int64,
) (trancheList []types.LimitOrderTranche) {
prefixStore := prefix.NewStore(
sdkCtx.KVStore(k.storeKey),
types.TickLiquidityLimitOrderPrefix(tradePairID, tickIndexTakerToMaker),
)
iter := storetypes.KVStorePrefixIterator(prefixStore, []byte{})
defer iter.Close()
for ; iter.Valid(); iter.Next() {
var tick types.TickLiquidity
k.cdc.MustUnmarshal(iter.Value(), &tick)
maybeTranche := tick.GetLimitOrderTranche()
if maybeTranche != nil {
trancheList = append(trancheList, *maybeTranche)
}
}
return trancheList
}
func NewTrancheKey(ctx sdk.Context) string {
blockHeight := ctx.BlockHeight()
txGas := ctx.GasMeter().GasConsumed()
blockGas := utils.MustGetBlockGasUsed(ctx)
totalGas := blockGas + txGas
blockStr := utils.Uint64ToSortableString(uint64(blockHeight))
gasStr := utils.Uint64ToSortableString(totalGas)
return fmt.Sprintf("%s%s", blockStr, gasStr)
}
func (k Keeper) GetOrInitPlaceTranche(ctx sdk.Context,
tradePairID *types.TradePairID,
tickIndexTakerToMaker int64,
goodTil *time.Time,
orderType types.LimitOrderType,
) (placeTranche *types.LimitOrderTranche, err error) {
// NOTE: Right now we are not indexing by goodTil date so we can't easily check if there's already a tranche
// with the same goodTil date so instead we create a new tranche for each goodTil order
// if there is a large number of limitOrders with the same goodTilTime (most likely JIT)
// aggregating might be more efficient particularly for deletion, but if they are relatively sparse
// it will incur fewer lookups to just create a new limitOrderTranche
// Also trying to cancel aggregated good_til orders will be a PITA
JITGoodTilTime := types.JITGoodTilTime()
switch orderType {
case types.LimitOrderType_JUST_IN_TIME:
limitOrderTrancheKey := &types.LimitOrderTrancheKey{
TradePairId: tradePairID,
TickIndexTakerToMaker: tickIndexTakerToMaker,
TrancheKey: NewTrancheKey(ctx),
}
placeTranche, err = NewLimitOrderTranche(limitOrderTrancheKey, &JITGoodTilTime)
ctx.EventManager().EmitEvents(types.GetEventsIncTotalOrders(tradePairID))
case types.LimitOrderType_GOOD_TIL_TIME:
limitOrderTrancheKey := &types.LimitOrderTrancheKey{
TradePairId: tradePairID,
TickIndexTakerToMaker: tickIndexTakerToMaker,
TrancheKey: NewTrancheKey(ctx),
}
placeTranche, err = NewLimitOrderTranche(limitOrderTrancheKey, goodTil)
ctx.EventManager().EmitEvents(types.GetEventsIncExpiringOrders(tradePairID))
default:
placeTranche = k.GetGTCPlaceTranche(ctx, tradePairID, tickIndexTakerToMaker)
if placeTranche == nil {
limitOrderTrancheKey := &types.LimitOrderTrancheKey{
TradePairId: tradePairID,
TickIndexTakerToMaker: tickIndexTakerToMaker,
TrancheKey: NewTrancheKey(ctx),
}
placeTranche, err = NewLimitOrderTranche(limitOrderTrancheKey, nil)
ctx.EventManager().EmitEvents(types.GetEventsIncTotalOrders(tradePairID))
if err != nil {
return nil, err
}
}
}
if err != nil {
return nil, err
}
return placeTranche, nil
}
// GetJITsInBlockCount gets the total number of JIT LimitOrders placed in a block
func (k Keeper) GetJITsInBlockCount(ctx sdk.Context) uint64 {
store := prefix.NewStore(ctx.TransientStore(k.tKey), []byte{})
byteKey := types.KeyPrefix(types.JITsInBlockKey)
bz := store.Get(byteKey)
// Count doesn't exist: no element
if bz == nil {
return 0
}
// Parse bytes
return binary.BigEndian.Uint64(bz)
}
// SetJITsInBlockCount sets the total number of JIT LimitOrders placed in a block
func (k Keeper) SetJITsInBlockCount(ctx sdk.Context, count uint64) {
store := prefix.NewStore(ctx.TransientStore(k.tKey), []byte{})
byteKey := types.KeyPrefix(types.JITsInBlockKey)
bz := make([]byte, 8)
binary.BigEndian.PutUint64(bz, count)
store.Set(byteKey, bz)
}
func (k Keeper) IncrementJITsInBlock(ctx sdk.Context) {
currentCount := k.GetJITsInBlockCount(ctx)
k.SetJITsInBlockCount(ctx, currentCount+1)
}