forked from tendermint/liquidity
/
batch.go
289 lines (244 loc) · 9.15 KB
/
batch.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
289
package keeper
import (
sdk "github.com/cosmos/cosmos-sdk/types"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/Victor118/liquidity/x/liquidity/types"
)
// DeleteAndInitPoolBatches resets batch msg states that were previously executed
// and deletes msg states that were marked to be deleted.
func (k Keeper) DeleteAndInitPoolBatches(ctx sdk.Context) {
k.IterateAllPoolBatches(ctx, func(poolBatch types.PoolBatch) bool {
// Re-initialize the executed batch.
if poolBatch.Executed {
// On the other hand, BatchDeposit, BatchWithdraw, is all handled by the endblock if there is no error.
// If there are BatchMsgs left, reset the Executed, Succeeded flag so that it can be executed in the next batch.
depositMsgs := k.GetAllRemainingPoolBatchDepositMsgStates(ctx, poolBatch)
if len(depositMsgs) > 0 {
for _, msg := range depositMsgs {
msg.Executed = false
msg.Succeeded = false
}
k.SetPoolBatchDepositMsgStatesByPointer(ctx, poolBatch.PoolId, depositMsgs)
}
withdrawMsgs := k.GetAllRemainingPoolBatchWithdrawMsgStates(ctx, poolBatch)
if len(withdrawMsgs) > 0 {
for _, msg := range withdrawMsgs {
msg.Executed = false
msg.Succeeded = false
}
k.SetPoolBatchWithdrawMsgStatesByPointer(ctx, poolBatch.PoolId, withdrawMsgs)
}
height := ctx.BlockHeight()
// In the case of remaining swap msg states, those are either fractionally matched
// or has not yet been expired.
swapMsgs := k.GetAllRemainingPoolBatchSwapMsgStates(ctx, poolBatch)
if len(swapMsgs) > 0 {
for _, msg := range swapMsgs {
if height > msg.OrderExpiryHeight {
msg.ToBeDeleted = true
} else {
msg.Executed = false
msg.Succeeded = false
}
}
k.SetPoolBatchSwapMsgStatesByPointer(ctx, poolBatch.PoolId, swapMsgs)
}
// Delete all batch msg states that are ready to be deleted.
k.DeleteAllReadyPoolBatchDepositMsgStates(ctx, poolBatch)
k.DeleteAllReadyPoolBatchWithdrawMsgStates(ctx, poolBatch)
k.DeleteAllReadyPoolBatchSwapMsgStates(ctx, poolBatch)
if err := k.InitNextPoolBatch(ctx, poolBatch); err != nil {
panic(err)
}
}
return false
})
}
// InitNextPoolBatch re-initializes the batch and increases the batch index.
func (k Keeper) InitNextPoolBatch(ctx sdk.Context, poolBatch types.PoolBatch) error {
if !poolBatch.Executed {
return types.ErrBatchNotExecuted
}
poolBatch.Index++
poolBatch.BeginHeight = ctx.BlockHeight()
poolBatch.Executed = false
k.SetPoolBatch(ctx, poolBatch)
return nil
}
// ExecutePoolBatches executes the accumulated msgs in the batch.
// The order is (1)swap, (2)deposit, (3)withdraw.
func (k Keeper) ExecutePoolBatches(ctx sdk.Context) {
params := k.GetParams(ctx)
logger := k.Logger(ctx)
k.IterateAllPoolBatches(ctx, func(poolBatch types.PoolBatch) bool {
if !poolBatch.Executed && ctx.BlockHeight()%int64(params.UnitBatchHeight) == 0 {
executedMsgCount, err := k.SwapExecution(ctx, poolBatch)
if err != nil {
panic(err)
}
k.IterateAllPoolBatchDepositMsgStates(ctx, poolBatch, func(batchMsg types.DepositMsgState) bool {
if batchMsg.Executed || batchMsg.ToBeDeleted || batchMsg.Succeeded {
return false
}
executedMsgCount++
if err := k.ExecuteDeposit(ctx, batchMsg, poolBatch); err != nil {
logger.Error("deposit failed",
"poolID", poolBatch.PoolId,
"batchIndex", poolBatch.Index,
"msgIndex", batchMsg.MsgIndex,
"depositor", batchMsg.Msg.GetDepositor(),
"error", err)
if err := k.RefundDeposit(ctx, batchMsg, poolBatch); err != nil {
panic(err)
}
}
return false
})
k.IterateAllPoolBatchWithdrawMsgStates(ctx, poolBatch, func(batchMsg types.WithdrawMsgState) bool {
if batchMsg.Executed || batchMsg.ToBeDeleted || batchMsg.Succeeded {
return false
}
executedMsgCount++
if err := k.ExecuteWithdrawal(ctx, batchMsg, poolBatch); err != nil {
logger.Error("withdraw failed",
"poolID", poolBatch.PoolId,
"batchIndex", poolBatch.Index,
"msgIndex", batchMsg.MsgIndex,
"withdrawer", batchMsg.Msg.GetWithdrawer(),
"error", err)
if err := k.RefundWithdrawal(ctx, batchMsg, poolBatch); err != nil {
panic(err)
}
}
return false
})
// Mark the batch as executed when any msgs were executed.
if executedMsgCount > 0 {
poolBatch.Executed = true
k.SetPoolBatch(ctx, poolBatch)
}
}
return false
})
}
// HoldEscrow sends coins to the module account for an escrow.
func (k Keeper) HoldEscrow(ctx sdk.Context, depositor sdk.AccAddress, depositCoins sdk.Coins) error {
if err := k.bankKeeper.SendCoinsFromAccountToModule(ctx, depositor, types.ModuleName, depositCoins); err != nil {
return err
}
return nil
}
// If batch messages have expired or have not been processed, coins that were deposited with this function are refunded to the escrow.
func (k Keeper) ReleaseEscrow(ctx sdk.Context, withdrawer sdk.AccAddress, withdrawCoins sdk.Coins) error {
if err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, types.ModuleName, withdrawer, withdrawCoins); err != nil {
return err
}
return nil
}
// Generate inputs and outputs to treat escrow refunds atomically.
func (k Keeper) ReleaseEscrowForMultiSend(withdrawer sdk.AccAddress, withdrawCoins sdk.Coins) (
banktypes.Input, banktypes.Output, error) {
var input banktypes.Input
var output banktypes.Output
input = banktypes.NewInput(k.accountKeeper.GetModuleAddress(types.ModuleName), withdrawCoins)
output = banktypes.NewOutput(withdrawer, withdrawCoins)
if err := banktypes.ValidateInputsOutputs([]banktypes.Input{input}, []banktypes.Output{output}); err != nil {
return banktypes.Input{}, banktypes.Output{}, err
}
return input, output, nil
}
// In order to deal with the batch at the same time, the coins of msgs are deposited in escrow.
func (k Keeper) DepositWithinBatch(ctx sdk.Context, msg *types.MsgDepositWithinBatch) (types.DepositMsgState, error) {
if err := k.ValidateMsgDepositWithinBatch(ctx, *msg); err != nil {
return types.DepositMsgState{}, err
}
poolBatch, found := k.GetPoolBatch(ctx, msg.PoolId)
if !found {
return types.DepositMsgState{}, types.ErrPoolBatchNotExists
}
if poolBatch.BeginHeight == 0 {
poolBatch.BeginHeight = ctx.BlockHeight()
}
msgState := types.DepositMsgState{
MsgHeight: ctx.BlockHeight(),
MsgIndex: poolBatch.DepositMsgIndex,
Msg: msg,
}
if err := k.HoldEscrow(ctx, msg.GetDepositor(), msg.DepositCoins); err != nil {
return types.DepositMsgState{}, err
}
poolBatch.DepositMsgIndex++
k.SetPoolBatch(ctx, poolBatch)
k.SetPoolBatchDepositMsgState(ctx, poolBatch.PoolId, msgState)
return msgState, nil
}
// In order to deal with the batch at the same time, the coins of msgs are deposited in escrow.
func (k Keeper) WithdrawWithinBatch(ctx sdk.Context, msg *types.MsgWithdrawWithinBatch) (types.WithdrawMsgState, error) {
if err := k.ValidateMsgWithdrawWithinBatch(ctx, *msg); err != nil {
return types.WithdrawMsgState{}, err
}
poolBatch, found := k.GetPoolBatch(ctx, msg.PoolId)
if !found {
return types.WithdrawMsgState{}, types.ErrPoolBatchNotExists
}
if poolBatch.BeginHeight == 0 {
poolBatch.BeginHeight = ctx.BlockHeight()
}
batchPoolMsg := types.WithdrawMsgState{
MsgHeight: ctx.BlockHeight(),
MsgIndex: poolBatch.WithdrawMsgIndex,
Msg: msg,
}
if err := k.HoldEscrow(ctx, msg.GetWithdrawer(), sdk.NewCoins(msg.PoolCoin)); err != nil {
return types.WithdrawMsgState{}, err
}
poolBatch.WithdrawMsgIndex++
k.SetPoolBatch(ctx, poolBatch)
k.SetPoolBatchWithdrawMsgState(ctx, poolBatch.PoolId, batchPoolMsg)
return batchPoolMsg, nil
}
// In order to deal with the batch at the same time, the coins of msgs are deposited in escrow.
func (k Keeper) SwapWithinBatch(ctx sdk.Context, msg *types.MsgSwapWithinBatch, orderExpirySpanHeight int64) (*types.SwapMsgState, error) {
pool, found := k.GetPool(ctx, msg.PoolId)
if !found {
return nil, types.ErrPoolNotExists
}
if k.IsDepletedPool(ctx, pool) {
return nil, types.ErrDepletedPool
}
if err := k.ValidateMsgSwapWithinBatch(ctx, *msg, pool); err != nil {
return nil, err
}
poolBatch, found := k.GetPoolBatch(ctx, msg.PoolId)
if !found {
return nil, types.ErrPoolBatchNotExists
}
if poolBatch.BeginHeight == 0 {
poolBatch.BeginHeight = ctx.BlockHeight()
}
currentHeight := ctx.BlockHeight()
if orderExpirySpanHeight == 0 {
params := k.GetParams(ctx)
u := int64(params.UnitBatchHeight)
orderExpirySpanHeight = (u - currentHeight%u) % u
}
batchPoolMsg := types.SwapMsgState{
MsgHeight: currentHeight,
MsgIndex: poolBatch.SwapMsgIndex,
Executed: false,
Succeeded: false,
ToBeDeleted: false,
OrderExpiryHeight: currentHeight + orderExpirySpanHeight,
ExchangedOfferCoin: sdk.NewCoin(msg.OfferCoin.Denom, sdk.ZeroInt()),
RemainingOfferCoin: msg.OfferCoin,
ReservedOfferCoinFee: msg.OfferCoinFee,
Msg: msg,
}
if err := k.HoldEscrow(ctx, msg.GetSwapRequester(), sdk.NewCoins(msg.OfferCoin.Add(msg.OfferCoinFee))); err != nil {
return nil, err
}
poolBatch.SwapMsgIndex++
k.SetPoolBatch(ctx, poolBatch)
k.SetPoolBatchSwapMsgState(ctx, poolBatch.PoolId, batchPoolMsg)
return &batchPoolMsg, nil
}