execute.gno
8.66 Kb · 249 lines
1package impl
2
3import (
4 "time"
5
6 "gno.land/p/gnoswap/gnsmath/v1"
7 pdca "gno.land/p/gnoswap/order/dca/v0"
8 u256 "gno.land/p/gnoswap/uint256/v1"
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/whitelist"
15)
16
17// ExecuteGroup sells one round of a group with a pool swap
18// and credits the swap output to the group accumulator.
19// Each order's execution fee is deducted when the order is paid out;
20// the round forwards the fee already pending for its output token.
21// Only keepers allowed by gno.land/r/gnoswap/order/keeper may call it
22// (DCAKeeperRole at deployment): the schedule and the swap result are checked on-chain,
23// and a failed swap reverts so the round can be retried.
24// minOrderAmountOut, raised to minOrderAmountOutFloor, is the least output
25// every order of the round must be credited.
26func (d *dcaOrderImpl) ExecuteGroup(
27 _ int,
28 rlm realm,
29 groupID string,
30 expectedAmountIn int64,
31 amountOutMin int64,
32 minOrderAmountOut int64,
33) (int64, int64) {
34 access.AssertIsRlmCurrent(0, rlm)
35 common.AssertIsNotHandleNativeCoin()
36 assertIsNotHalted(halt.OperationExecute, halt.OperationWithdraw)
37 d.assertIsNotExecuting()
38
39 if amountOutMin < 0 || expectedAmountIn < 0 || minOrderAmountOut < 0 {
40 panic(makeErrorWithDetails(
41 errInvalidAmount,
42 ufmt.Sprintf(
43 "expectedAmountIn(%d) amountOutMin(%d) minOrderAmountOut(%d)",
44 expectedAmountIn, amountOutMin, minOrderAmountOut,
45 ),
46 ).Error())
47 }
48
49 if minOrderAmountOut < minOrderAmountOutFloor {
50 minOrderAmountOut = minOrderAmountOutFloor
51 }
52
53 prev := rlm.Previous()
54 assertIsAuthorizedKeeper(rlm.PkgPath(), prev.Address())
55
56 group, err := d.getGroup(groupID)
57 if err != nil {
58 panic(err.Error())
59 }
60
61 currentTimestamp := time.Now().Unix()
62
63 result, err := d.executeGroupRound(0, rlm, group, expectedAmountIn, amountOutMin, minOrderAmountOut, currentTimestamp)
64 if err != nil {
65 panic(err.Error())
66 }
67
68 emitGroupExecuted(prev.Address(), prev.PkgPath(), group, result)
69
70 if result.forwardedExecutionFeeAmount > 0 || result.pendingExecutionFeeAmount > 0 {
71 emitExecutionFeeCollected(
72 prev.Address(),
73 prev.PkgPath(),
74 group.ID(),
75 group.OutputToken(),
76 group.Round(),
77 0,
78 result.forwardedExecutionFeeAmount,
79 result.pendingExecutionFeeAmount,
80 )
81 }
82
83 return result.executedAmountIn, result.executedAmountOut
84}
85
86// groupRoundResult describes one executed round.
87type groupRoundResult struct {
88 poolPath string
89 scheduledTimestamp int64
90 executionTimestamp int64
91 executedAmountIn int64 // input sold, the group orderAmount
92 swapAmountOut int64 // pool output of the round
93 executedAmountOut int64 // output credited to the orders, before their execution fees
94 endedOrderAmount int64 // orderAmount of the orders whose last round this was
95
96 forwardedExecutionFeeAmount int64 // pending execution fee sent to the protocol fee realm
97 pendingExecutionFeeAmount int64 // execution fee still held by this realm
98}
99
100// executeGroupRound runs the group's next round: it checks the schedule
101// and the quoted input, picks the pool, swaps the whole round input within
102// the pair price limit, and credits the pool output (swapAmountOut) to the
103// accumulator per unit of the round input.
104//
105// The round charges no fee itself. Each order's execution fee is its own
106// snapshotted executionFeeRate of its gross output, deducted when the order
107// is paid out (Claim, ClaimGroupOrders, CancelOrder, ForceCancelOrder) and
108// held as pending. The round forwards the fee pending for its output token to
109// the protocol fee realm, so the fee still costs one transfer per round
110// instead of one per order.
111//
112// Every order of the round must be credited at least minOrderAmountOut of
113// output after its own execution fee rate. A round that cannot
114// pay its smallest order that much is treated as lacking liquidity: it
115// reverts, like a failed swap, so it can be retried.
116//
117// Checks-effects-interactions:
118// the round, schedule, and next orderAmount are written before the pool
119// swap, and an execution lock blocks re-entry while the swap and the
120// pending execution fee transfer run.
121// Only the swap-dependent accumulator is written after the swap.
122func (d *dcaOrderImpl) executeGroupRound(
123 _ int,
124 rlm realm,
125 group *pdca.Group,
126 expectedAmountIn,
127 amountOutMin,
128 minOrderAmountOut,
129 currentTimestamp int64,
130) (groupRoundResult, error) {
131 config := d.store.GetConfig()
132
133 orderAmount := group.OrderAmount()
134 if orderAmount <= 0 {
135 return groupRoundResult{}, makeErrorWithDetails(errGroupNotExecutable, ufmt.Sprintf("groupId(%s) has no active order amount", group.ID()))
136 }
137
138 // Check the schedule first,
139 // so a round already run by someone else reports "not executable".
140 scheduledTimestamp := group.NextExecutionTimestamp()
141 if currentTimestamp < scheduledTimestamp {
142 return groupRoundResult{}, makeErrorWithDetails(
143 errGroupNotExecutable,
144 ufmt.Sprintf("groupId(%s) next execution at %d, now %d", group.ID(), scheduledTimestamp, currentTimestamp),
145 )
146 }
147
148 // Orders may join or leave between the keeper's quote and inclusion;
149 // the keeper then quotes again.
150 assertIsQuotedAmountIn(group, expectedAmountIn, amountOutMin)
151
152 // The pair price limit bounds the round's price and the pool's tick walk.
153 priceLimit := getPairPriceLimit(d.store.GetPairPriceLimits(), group.InputToken(), group.OutputToken())
154
155 selectedPool, err := selectRoundPool(whitelist.GetWhitelistedPools(whitelist.TargetDCA), priceLimit, config.MaxPoolPriceDeviationRate(), config.MaxPairPriceLimitAge(), group, orderAmount)
156 if err != nil {
157 return groupRoundResult{}, err
158 }
159
160 // Effects independent of the swap result.
161 round := gnsmath.SafeAddUint64(group.Round(), 1)
162
163 group.SetRound(round)
164
165 // Orders ending at this round stop selling from the next round.
166 roundMark := group.GetRoundMark(round)
167
168 endedOrderAmount := int64(0)
169 if roundMark != nil {
170 endedOrderAmount = roundMark.OrderAmount()
171 }
172
173 // Move to the next slot without the ended order amount,
174 // at least the execution gap after now.
175 // A group with no order amount left drops out of the schedule index.
176 minExecutionGap, err := pdca.CalculateMinExecutionGap(group.Interval(), config.MinExecutionGapRate())
177 if err != nil {
178 return groupRoundResult{}, err
179 }
180
181 nextExecutionTimestamp, err := pdca.CalculateNextExecutionTimestampWithGap(scheduledTimestamp, currentTimestamp, group.Interval(), minExecutionGap)
182 if err != nil {
183 return groupRoundResult{}, err
184 }
185
186 nextOrderAmount := gnsmath.SafeSubInt64(orderAmount, endedOrderAmount)
187 if err := d.rescheduleGroup(group, nextOrderAmount, nextExecutionTimestamp); err != nil {
188 return groupRoundResult{}, err
189 }
190
191 // Net payouts grow with amountPerExecution at one fee rate,
192 // so the smallest order of each rate bounds every order's output.
193 minAmounts := d.getFeeRateMinAmounts(group, round, true)
194 if len(minAmounts) == 0 {
195 return groupRoundResult{}, makeErrorWithDetails(
196 errInvalidState,
197 ufmt.Sprintf("groupId(%s) has no indexed order for round %d", group.ID(), round),
198 )
199 }
200
201 if err := d.store.SetExecuting(0, rlm, true); err != nil {
202 return groupRoundResult{}, err
203 }
204
205 swapAmountOut, err := swapExactIn(0, rlm, group, selectedPool.fee, selectedPool.sqrtPriceLimitX96, orderAmount, amountOutMin)
206 if err != nil {
207 return groupRoundResult{}, err
208 }
209
210 executedAmountOut := swapAmountOut
211
212 outputPerAmountX128, err := pdca.CalculateOutputPerAmountX128(executedAmountOut, orderAmount)
213 if err != nil {
214 return groupRoundResult{}, err
215 }
216
217 if err := validateOrderOutput(group, minAmounts, minOrderAmountOut, outputPerAmountX128, executedAmountOut, orderAmount); err != nil {
218 return groupRoundResult{}, err
219 }
220
221 accumulatedOutputPerAmountX128, overflow := u256.Zero().AddOverflow(group.AccumulatedOutputPerAmountX128(), outputPerAmountX128)
222 if overflow {
223 return groupRoundResult{}, makeErrorWithDetails(errOverflow, "accumulator overflow")
224 }
225
226 group.SetAccumulatedOutputPerAmountX128(accumulatedOutputPerAmountX128)
227
228 if roundMark != nil {
229 roundMark.SnapshotAccumulatedOutputPerAmountX128(accumulatedOutputPerAmountX128)
230 }
231
232 forwardedExecutionFeeAmount, pendingExecutionFeeAmount := d.collectExecutionFee(0, rlm, group.OutputToken(), 0)
233
234 if err := d.store.SetExecuting(0, rlm, false); err != nil {
235 return groupRoundResult{}, err
236 }
237
238 return groupRoundResult{
239 poolPath: selectedPool.poolPath,
240 scheduledTimestamp: scheduledTimestamp,
241 executionTimestamp: currentTimestamp,
242 executedAmountIn: orderAmount,
243 swapAmountOut: swapAmountOut,
244 executedAmountOut: executedAmountOut,
245 endedOrderAmount: endedOrderAmount,
246 forwardedExecutionFeeAmount: forwardedExecutionFeeAmount,
247 pendingExecutionFeeAmount: pendingExecutionFeeAmount,
248 }, nil
249}