order.gno
21.54 Kb · 616 lines
1package impl
2
3import (
4 "chain/runtime"
5 "time"
6
7 "gno.land/p/gnoswap/gnsmath/v1"
8 pdca "gno.land/p/gnoswap/order/dca/v0"
9 ufmt "gno.land/p/nt/ufmt/v0"
10
11 "gno.land/r/gnoswap/access/v1"
12 "gno.land/r/gnoswap/common"
13 "gno.land/r/gnoswap/order/halt"
14 "gno.land/r/gnoswap/order/keeper"
15 "gno.land/r/gnoswap/order/whitelist"
16)
17
18// CreateOrder escrows the order input
19// and adds the order's per-round amount to its group.
20// The group runs at the slotOffset of each interval, see pdca.Group.
21// The order takes part in the group's next executionCount rounds only;
22// the caller pays for the order's execution logs, one per three rounds.
23// The order snapshots the execution fee rate in effect, charged on its
24// output when it is paid out; later rate changes leave it unchanged.
25func (d *dcaOrderImpl) CreateOrder(
26 _ int,
27 rlm realm,
28 inputToken string,
29 outputToken string,
30 interval int64,
31 slotOffset int64,
32 amountPerExecution int64,
33 executionCount int64,
34) uint64 {
35 access.AssertIsRlmCurrent(0, rlm)
36 common.AssertIsNotHandleNativeCoin()
37 // A new order only joins rounds, so it is rejected while rounds are halted.
38 assertIsNotHalted(halt.OperationExecute)
39 d.assertIsNotExecuting()
40
41 prev := rlm.Previous()
42 caller := prev.Address()
43 access.AssertIsValidAddress(caller)
44
45 config := d.store.GetConfig()
46
47 assertIsValidPair(inputToken, outputToken)
48 assertHasPairPriceLimit(d.store.GetPairPriceLimits(), inputToken, outputToken)
49 assertIsAllowedInterval(config, interval)
50 assertIsAllowedSlot(config, interval, slotOffset)
51 assertIsValidOrderSize(config, d.minAmountPerExecution(inputToken), amountPerExecution, executionCount)
52
53 order, group, isNewGroup, depositAmount, err := d.createOrder(
54 0, rlm, caller, inputToken, outputToken, interval, slotOffset, amountPerExecution, executionCount,
55 )
56 if err != nil {
57 panic(err.Error())
58 }
59
60 if isNewGroup {
61 emitGroupCreated(caller, prev.PkgPath(), group)
62 }
63
64 // The escrow transfer does not touch the pools, so this quotes the state
65 // the order was placed in.
66 // The order's execution fee is deducted up front, as its payouts deduct
67 // it, so the reference is comparable with the output the owner receives.
68 referenceSwapAmountOut := quoteReferenceAmountOut(
69 whitelist.GetWhitelistedPools(whitelist.TargetDCA),
70 getPairPriceLimit(d.store.GetPairPriceLimits(), inputToken, outputToken),
71 config.MaxPoolPriceDeviationRate(),
72 config.MaxPairPriceLimitAge(),
73 inputToken,
74 outputToken,
75 depositAmount,
76 )
77
78 referenceExecutionFeeAmount, err := pdca.CalculateExecutionFeeAmount(referenceSwapAmountOut, order.ExecutionFeeRate())
79 if err != nil {
80 panic(err.Error())
81 }
82
83 referenceAmountOut := gnsmath.SafeSubInt64(referenceSwapAmountOut, referenceExecutionFeeAmount)
84
85 emitOrderCreated(caller, prev.PkgPath(), order, group, depositAmount, referenceAmountOut)
86
87 return order.ID()
88}
89
90// createOrder stores the order, joins or creates its group,
91// and pulls the deposit from the owner.
92func (d *dcaOrderImpl) createOrder(
93 _ int,
94 rlm realm,
95 owner address,
96 inputToken string,
97 outputToken string,
98 interval int64,
99 slotOffset int64,
100 amountPerExecution int64,
101 executionCount int64,
102) (*pdca.Order, *pdca.Group, bool, int64, error) {
103 depositAmount := gnsmath.SafeMulInt64(amountPerExecution, executionCount)
104
105 currentTimestamp := time.Now().Unix()
106 groups := d.store.GetGroups()
107 groupID := pdca.MakeGroupID(inputToken, outputToken, interval, slotOffset)
108
109 // A new or idle group runs its next round at the first slot from now,
110 // instead of at a stale slot that would run at once.
111 firstSlotTimestamp, err := pdca.CalculateFirstSlotTimestamp(currentTimestamp, interval, slotOffset)
112 if err != nil {
113 return nil, nil, false, 0, makeErrorWithDetails(errInvalidSlotOffset, err.Error())
114 }
115
116 var group *pdca.Group
117
118 isNewGroup := false
119
120 if value := groups.Get(groupID); value != nil {
121 group = value.(*pdca.Group)
122 } else {
123 group = pdca.NewGroup(groupID, inputToken, outputToken, interval, slotOffset, firstSlotTimestamp)
124 groups.Set(groupID, group)
125
126 isNewGroup = true
127 }
128
129 nextExecutionTimestamp := group.NextExecutionTimestamp()
130 if group.OrderAmount() == 0 {
131 nextExecutionTimestamp = firstSlotTimestamp
132 }
133
134 orderID := d.store.GetNextOrderID()
135 if err := d.store.SetNextOrderID(0, rlm, gnsmath.SafeAddUint64(orderID, 1)); err != nil {
136 return nil, nil, false, 0, err
137 }
138
139 executionFeeRate := d.store.GetConfig().ExecutionFeeRate()
140
141 order, err := pdca.NewOrder(orderID, owner, group, amountPerExecution, executionCount, executionFeeRate, currentTimestamp, runtime.ChainHeight())
142 if err != nil {
143 return nil, nil, false, 0, makeErrorWithDetails(errInvalidExecutionCount, err.Error())
144 }
145
146 // Store the order's execution logs now,
147 // so the owner pays their storage deposit up front.
148 pdca.AllocateExecutionLogs(d.store.GetExecutionLogs(), order)
149
150 roundMark := group.GetOrCreateRoundMark(order.EndRound())
151 roundMark.SetOrderAmount(gnsmath.SafeAddInt64(roundMark.OrderAmount(), amountPerExecution))
152 roundMark.SetOrderCount(gnsmath.SafeAddInt64(roundMark.OrderCount(), 1))
153
154 groupOrderAmount := gnsmath.SafeAddInt64(group.OrderAmount(), amountPerExecution)
155 if err := d.rescheduleGroup(group, groupOrderAmount, nextExecutionTimestamp); err != nil {
156 return nil, nil, false, 0, err
157 }
158
159 group.SetActiveOrderCount(gnsmath.SafeAddInt64(group.ActiveOrderCount(), 1))
160
161 d.store.GetOrders().Set(pdca.OrderKey(orderID), order)
162 d.store.GetOrdersByOwner().Set(pdca.OwnerOrderKey(owner, orderID), orderID)
163 d.store.GetOrdersByGroup().Set(pdca.GroupOrderKey(groupID, orderID), orderID)
164 d.store.GetOrderAmountsByGroup().Set(pdca.GroupOrderAmountKey(groupID, executionFeeRate, amountPerExecution, orderID), order.EndRound())
165
166 // Pull funds last; a failure reverts every write above.
167 common.SafeGRC20TransferFrom(0, rlm, inputToken, owner, rlm.Address(), depositAmount)
168
169 return order, group, isNewGroup, depositAmount, nil
170}
171
172// CancelOrder pays accrued output, refunds the input of unexecuted rounds,
173// and closes the order, releasing all of its execution logs.
174// If every round already executed, the order completes instead,
175// with nothing to refund.
176func (d *dcaOrderImpl) CancelOrder(_ int, rlm realm, orderID uint64) (int64, int64) {
177 access.AssertIsRlmCurrent(0, rlm)
178 common.AssertIsNotHandleNativeCoin()
179 assertIsNotHalted(halt.OperationWithdraw)
180 d.assertIsNotExecuting()
181
182 prev := rlm.Previous()
183 caller := prev.Address()
184
185 order, group, err := d.getOrderWithGroup(orderID)
186 if err != nil {
187 panic(err.Error())
188 }
189
190 assertIsOrderOwner(order, caller)
191
192 result, err := d.cancelOrder(0, rlm, caller, prev.PkgPath(), order, group)
193 if err != nil {
194 panic(err.Error())
195 }
196
197 if result.isCompleted {
198 // Every round already executed: a completion, not a cancellation.
199 emitOrderClaimed(caller, prev.PkgPath(), order, group, result.payout, pdca.OrderStatusCompleted)
200 } else {
201 emitOrderCancelled(caller, prev.PkgPath(), order, group, result.payout, result.refundedAmount)
202 }
203
204 emitPayoutExecutionFee(caller, prev.PkgPath(), group, result.payout.executionFeeAmount, d.pendingExecutionFeeAmount(group.OutputToken()))
205
206 return result.refundedAmount, result.payout.claimedAmount
207}
208
209// ForceCancelOrder closes an order that blocks its group's rounds exactly as
210// CancelOrder would for its owner: accrued output and unsold input go to the
211// owner, never to the caller. The freed storage deposit of its execution logs
212// goes to the transaction signer, as for any release.
213//
214// The order must have rounds left and meet one of the conditions checked
215// on-chain by forceCancelReason, reported as the event's reason:
216// - below_min_amount: its amountPerExecution is below the minimum a new
217// order selling its token needs now
218// - no_order_output: the next round is due and, as quoted now, would credit
219// it less than minOrderAmountOutFloor after its execution fee
220// - exceeds_pool_capacity: the next round is due, no pool can fill it
221// as quoted now, a pool fills part of it within the price limit, and no
222// order of the round sells more per execution than this one
223//
224// Any other order is rejected, so a keeper cannot close healthy orders.
225//
226// Only keepers allowed by gno.land/r/gnoswap/order/keeper may call it
227// (DCAKeeperRole at deployment).
228func (d *dcaOrderImpl) ForceCancelOrder(_ int, rlm realm, orderID uint64) (int64, int64) {
229 access.AssertIsRlmCurrent(0, rlm)
230 common.AssertIsNotHandleNativeCoin()
231 assertIsNotHalted(halt.OperationWithdraw)
232 d.assertIsNotExecuting()
233
234 prev := rlm.Previous()
235 caller := prev.Address()
236
237 if !keeper.IsAuthorized(rlm.PkgPath(), keeper.SelectorForceCancelOrder, caller) {
238 panic(makeErrorWithDetails(errNotKeeper, ufmt.Sprintf("caller(%s) selector(%s)", caller.String(), string(keeper.SelectorForceCancelOrder))).Error())
239 }
240
241 order, group, err := d.getOrderWithGroup(orderID)
242 if err != nil {
243 panic(err.Error())
244 }
245
246 // Check before the order leaves its group, against the state it blocks.
247 reason, err := d.forceCancelReason(order, group, time.Now().Unix())
248 if err != nil {
249 panic(err.Error())
250 }
251
252 result, err := d.cancelOrder(0, rlm, caller, prev.PkgPath(), order, group)
253 if err != nil {
254 panic(err.Error())
255 }
256
257 emitOrderForceCancelled(caller, prev.PkgPath(), order, group, result.payout, result.refundedAmount, reason)
258
259 emitPayoutExecutionFee(caller, prev.PkgPath(), group, result.payout.executionFeeAmount, d.pendingExecutionFeeAmount(group.OutputToken()))
260
261 return result.refundedAmount, result.payout.claimedAmount
262}
263
264// Reasons ForceCancelOrder accepts, reported by DCAOrderForceCancelled.
265const (
266 forceCancelBelowMinAmount = "below_min_amount"
267 forceCancelNoOrderOutput = "no_order_output"
268 forceCancelExceedsPoolCapacity = "exceeds_pool_capacity"
269)
270
271// forceCancelReason returns why the order blocks its group, or
272// errOrderNotBlocking if it does not (see ForceCancelOrder).
273// The round conditions quote the group's next round as ExecuteGroup would
274// run it at currentTimestamp, so they hold only while that round is due.
275func (d *dcaOrderImpl) forceCancelReason(order *pdca.Order, group *pdca.Group, currentTimestamp int64) (string, error) {
276 nextRound := group.Round() + 1
277 if nextRound > order.EndRound() {
278 // Every round executed: Claim completes it.
279 return "", makeErrorWithDetails(errOrderNotBlocking, ufmt.Sprintf("orderId(%d) has no round left", order.ID()))
280 }
281
282 if order.AmountPerExecution() < d.minAmountPerExecution(group.InputToken()) {
283 return forceCancelBelowMinAmount, nil
284 }
285
286 // An active order sells in every round up to its last, so it sells in
287 // the next one; it blocks rounds only while that round is due.
288 if !isGroupExecutable(group, currentTimestamp) {
289 return "", makeErrorWithDetails(
290 errOrderNotBlocking,
291 ufmt.Sprintf("orderId(%d): groupId(%s) has no due round", order.ID(), group.ID()),
292 )
293 }
294
295 config := d.store.GetConfig()
296 whitelistedPools := whitelist.GetWhitelistedPools(whitelist.TargetDCA)
297 priceLimit := getPairPriceLimit(d.store.GetPairPriceLimits(), group.InputToken(), group.OutputToken())
298 amountIn := group.OrderAmount()
299
300 selectedPool, candidates := selectPool(whitelistedPools, priceLimit, config.MaxPoolPriceDeviationRate(), config.MaxPairPriceLimitAge(), group.InputToken(), group.OutputToken(), amountIn, true)
301
302 if selectedPool == nil {
303 // The round is too large only when a pool fills part of it within
304 // the price limit, with some output; a missing or stale price limit, a pool
305 // past its limit or without a price or liquidity, or a failed quote
306 // blocks every order alike.
307 if !hasPartialFill(candidates) {
308 return "", makeErrorWithDetails(
309 errOrderNotBlocking,
310 ufmt.Sprintf("orderId(%d): no pool of groupId(%s) fills part of the round", order.ID(), group.ID()),
311 )
312 }
313
314 // Shrink the round from its largest orders, one per call: a round that
315 // needs several orders gone gets them one after the other, while a
316 // keeper cannot pick a smaller order instead.
317 if d.sellsLargerOrder(group, nextRound, order.AmountPerExecution()) {
318 return "", makeErrorWithDetails(
319 errOrderNotBlocking,
320 ufmt.Sprintf("orderId(%d): a larger order sells in round %d of groupId(%s)", order.ID(), nextRound, group.ID()),
321 )
322 }
323
324 return forceCancelExceedsPoolCapacity, nil
325 }
326
327 outputPerAmountX128, err := pdca.CalculateOutputPerAmountX128(selectedPool.quotedAmountOut, amountIn)
328 if err != nil {
329 return "", err
330 }
331
332 orderAmountOut, err := calculateMinOrderAmountOut(
333 feeRateMinAmount{executionFeeRate: order.ExecutionFeeRate(), minAmountPerExecution: order.AmountPerExecution()},
334 outputPerAmountX128,
335 )
336 if err != nil {
337 return "", err
338 }
339
340 if orderAmountOut < minOrderAmountOutFloor {
341 return forceCancelNoOrderOutput, nil
342 }
343
344 return "", makeErrorWithDetails(
345 errOrderNotBlocking,
346 ufmt.Sprintf("orderId(%d) would be credited %d in the next round", order.ID(), orderAmountOut),
347 )
348}
349
350// hasPartialFill reports whether a candidate pool fills only part of the
351// round within the price limit, with some output, so that a smaller round
352// may fill. A pool that swaps nothing, such as one without liquidity, also
353// reports codePartialFill but cannot fill any smaller round.
354func hasPartialFill(candidates []*poolCandidate) bool {
355 for _, candidate := range candidates {
356 if candidate.ineligibleCode == codePartialFill && candidate.partialAmountOut > 0 {
357 return true
358 }
359 }
360
361 return false
362}
363
364// sellsLargerOrder reports whether an order of the group selling in round
365// has a larger amountPerExecution than amountPerExecution.
366// The amount index sorts a group's orders by fee rate, then amount, so each
367// fee rate costs one reverse seek past its finished orders, as in
368// getFeeRateMinAmounts.
369func (d *dcaOrderImpl) sellsLargerOrder(group *pdca.Group, round uint64, amountPerExecution int64) bool {
370 orderAmountsByGroup := d.store.GetOrderAmountsByGroup()
371 prefix := pdca.GroupOrderPrefix(group.ID())
372 end := pdca.PrefixEnd(prefix)
373 start := prefix
374
375 for {
376 found := false
377 executionFeeRate := int64(0)
378
379 orderAmountsByGroup.Iterate(start, end, func(key string, _ any) bool {
380 executionFeeRate = pdca.GroupOrderAmountKeyFeeRate(group.ID(), key)
381 found = true
382
383 return true
384 })
385
386 if !found {
387 return false
388 }
389
390 ratePrefix := pdca.GroupOrderFeeRatePrefix(group.ID(), executionFeeRate)
391 rateEnd := pdca.PrefixEnd(ratePrefix)
392 larger := false
393
394 // The largest selling order of the rate; finished orders, whose last
395 // round is before round, are skipped.
396 orderAmountsByGroup.ReverseIterate(ratePrefix, rateEnd, func(key string, value any) bool {
397 if key >= rateEnd || value.(uint64) < round {
398 return false
399 }
400
401 larger = pdca.GroupOrderAmountKeyAmount(group.ID(), key) > amountPerExecution
402
403 return true
404 })
405
406 if larger {
407 return true
408 }
409
410 start = rateEnd
411 }
412}
413
414// orderCancelResult describes a closed order.
415type orderCancelResult struct {
416 payout orderPayout
417 refundedAmount int64 // unsold input returned to the owner
418 isCompleted bool // every round had already executed
419}
420
421// cancelOrder closes an active order and transfers its output and refund.
422// The order's execution fee on its output is kept as pending.
423func (d *dcaOrderImpl) cancelOrder(
424 _ int,
425 rlm realm,
426 prevAddr address,
427 prevRealm string,
428 order *pdca.Order,
429 group *pdca.Group,
430) (orderCancelResult, error) {
431 endAccumulatedX128, isLastRoundExecuted, err := getOrderEndAccumulatedOutputPerAmountX128(order, group)
432 if err != nil {
433 return orderCancelResult{}, err
434 }
435
436 payout, err := calculateOrderPayout(order, endAccumulatedX128)
437 if err != nil {
438 return orderCancelResult{}, err
439 }
440
441 refundedAmount := int64(0)
442
443 if !isLastRoundExecuted {
444 remainingRoundCount := order.EndRound() - group.Round()
445 refundedAmount = gnsmath.SafeMulInt64(order.AmountPerExecution(), int64(remainingRoundCount))
446
447 groupOrderAmount := gnsmath.SafeSubInt64(group.OrderAmount(), order.AmountPerExecution())
448 if err := d.rescheduleGroup(group, groupOrderAmount, group.NextExecutionTimestamp()); err != nil {
449 return orderCancelResult{}, err
450 }
451
452 roundMark := group.GetRoundMark(order.EndRound())
453 if roundMark == nil {
454 return orderCancelResult{}, makeErrorWithDetails(errInvalidState, ufmt.Sprintf("missing mark for round %d", order.EndRound()))
455 }
456
457 roundMark.SetOrderAmount(gnsmath.SafeSubInt64(roundMark.OrderAmount(), order.AmountPerExecution()))
458 }
459
460 order.SetDebtX128(endAccumulatedX128)
461 recordOrderPayout(order, payout)
462 d.addPendingExecutionFee(group.OutputToken(), payout.executionFeeAmount)
463
464 d.releaseExecutionLogs(prevAddr, prevRealm, order, group, true)
465
466 if err := d.finalizeOrder(order, group); err != nil {
467 return orderCancelResult{}, err
468 }
469
470 if payout.claimedAmount > 0 {
471 common.SafeGRC20Transfer(0, rlm, group.OutputToken(), order.Owner(), payout.claimedAmount)
472 }
473
474 if refundedAmount > 0 {
475 common.SafeGRC20Transfer(0, rlm, group.InputToken(), order.Owner(), refundedAmount)
476 }
477
478 return orderCancelResult{payout: payout, refundedAmount: refundedAmount, isCompleted: isLastRoundExecuted}, nil
479}
480
481// Claim pays the order's accrued output to its owner,
482// and releases the order's execution logs whose rounds all executed.
483// Anyone may call it; the freed storage deposit goes to the caller.
484// The order completes once every round executed.
485func (d *dcaOrderImpl) Claim(_ int, rlm realm, orderID uint64) int64 {
486 access.AssertIsRlmCurrent(0, rlm)
487 common.AssertIsNotHandleNativeCoin()
488 assertIsNotHalted(halt.OperationWithdraw)
489 d.assertIsNotExecuting()
490
491 prev := rlm.Previous()
492
493 order, group, err := d.getOrderWithGroup(orderID)
494 if err != nil {
495 panic(err.Error())
496 }
497
498 payout, _, _, err := d.claimOrder(0, rlm, prev.Address(), prev.PkgPath(), order, group)
499 if err != nil {
500 panic(err.Error())
501 }
502
503 emitPayoutExecutionFee(prev.Address(), prev.PkgPath(), group, payout.executionFeeAmount, d.pendingExecutionFeeAmount(group.OutputToken()))
504
505 return payout.claimedAmount
506}
507
508// claimOrder pays an active order's accrued output, net of its execution
509// fee, to its owner, completing the order once its last round ran,
510// and releases its execution logs whose rounds all executed.
511// The execution fee is kept as pending for the protocol fee realm.
512// It returns the payout, the number of logs released,
513// and whether anything was paid or completed.
514func (d *dcaOrderImpl) claimOrder(
515 _ int,
516 rlm realm,
517 prevAddr address,
518 prevRealm string,
519 order *pdca.Order,
520 group *pdca.Group,
521) (orderPayout, int64, bool, error) {
522 endAccumulatedX128, isLastRoundExecuted, err := getOrderEndAccumulatedOutputPerAmountX128(order, group)
523 if err != nil {
524 return orderPayout{}, 0, false, err
525 }
526
527 payout, err := calculateOrderPayout(order, endAccumulatedX128)
528 if err != nil {
529 return orderPayout{}, 0, false, err
530 }
531
532 // Nothing accrued or to finalize: skip the payout writes and events,
533 // so anyone calling Claim cannot spam the owner's event history.
534 if payout.grossAmount == 0 && !isLastRoundExecuted {
535 releasedCount := d.releaseExecutionLogs(prevAddr, prevRealm, order, group, false)
536 return orderPayout{}, releasedCount, false, nil
537 }
538
539 // An active order's debt moves only by the gross output paid,
540 // so the remainder below one unit stays owed until later rounds
541 // add it up to a whole unit; a completed order settles at its end.
542 nextDebtX128 := endAccumulatedX128
543 if !isLastRoundExecuted {
544 nextDebtX128, err = calculateDebtX128AfterPayout(order.AmountPerExecution(), order.DebtX128(), payout.grossAmount)
545 if err != nil {
546 return orderPayout{}, 0, false, err
547 }
548 }
549
550 order.SetDebtX128(nextDebtX128)
551 recordOrderPayout(order, payout)
552 d.addPendingExecutionFee(group.OutputToken(), payout.executionFeeAmount)
553
554 releasedCount := d.releaseExecutionLogs(prevAddr, prevRealm, order, group, isLastRoundExecuted)
555
556 status := pdca.OrderStatusActive
557 if isLastRoundExecuted {
558 status = pdca.OrderStatusCompleted
559
560 if err := d.finalizeOrder(order, group); err != nil {
561 return orderPayout{}, 0, false, err
562 }
563 }
564
565 if payout.claimedAmount > 0 {
566 common.SafeGRC20Transfer(0, rlm, group.OutputToken(), order.Owner(), payout.claimedAmount)
567 }
568
569 emitOrderClaimed(prevAddr, prevRealm, order, group, payout, status)
570
571 return payout, releasedCount, true, nil
572}
573
574// releaseExecutionLogs releases the order's logs whose rounds all executed,
575// or every log of an order being finalized,
576// so the freed storage deposit is refunded to the caller.
577// Call it before finalizeOrder deletes the order.
578func (d *dcaOrderImpl) releaseExecutionLogs(prevAddr address, prevRealm string, order *pdca.Order, group *pdca.Group, isFinalized bool) int64 {
579 executionLogs := d.store.GetExecutionLogs()
580
581 releasedCount := int64(0)
582 if isFinalized {
583 releasedCount = pdca.ReleaseAllExecutionLogs(executionLogs, order)
584 } else {
585 releasedCount = pdca.ReleaseExecutionLogs(executionLogs, order, group.Round())
586 }
587
588 if releasedCount > 0 {
589 emitExecutionLogsReleased(prevAddr, prevRealm, order, group, releasedCount)
590 }
591
592 return releasedCount
593}
594
595// finalizeOrder releases a completed or cancelled order from its group
596// and deletes all of its stored data: the order record, its owner and
597// group index entries, and its end-round mark once no order references it.
598// A finished order's amount index entry may already be pruned by a round.
599//
600// Freeing the storage refunds its deposit to the transaction signer,
601// which pays keepers that finalize orders through ClaimGroupOrders.
602// The order's final state is kept in the emitted event, not in state.
603func (d *dcaOrderImpl) finalizeOrder(order *pdca.Order, group *pdca.Group) error {
604 if err := releaseRoundMark(group, order.EndRound()); err != nil {
605 return err
606 }
607
608 group.SetActiveOrderCount(group.ActiveOrderCount() - 1)
609
610 d.store.GetOrders().Remove(pdca.OrderKey(order.ID()))
611 d.store.GetOrdersByOwner().Remove(pdca.OwnerOrderKey(order.Owner(), order.ID()))
612 d.store.GetOrdersByGroup().Remove(pdca.GroupOrderKey(group.ID(), order.ID()))
613 d.store.GetOrderAmountsByGroup().Remove(pdca.GroupOrderAmountKey(group.ID(), order.ExecutionFeeRate(), order.AmountPerExecution(), order.ID()))
614
615 return nil
616}