Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

utils.gno

10.14 Kb · 305 lines
  1package impl
  2
  3import (
  4	"gno.land/p/gnoswap/gnsmath/v1"
  5	pdca "gno.land/p/gnoswap/order/dca/v0"
  6	u256 "gno.land/p/gnoswap/uint256/v1"
  7	ufmt "gno.land/p/nt/ufmt/v0"
  8)
  9
 10// calculatePayout wraps pdca.CalculatePayout,
 11// reporting a backwards accumulator as invalid state.
 12func calculatePayout(amountPerExecution int64, endAccumulatedX128 *u256.Uint, debtX128 *u256.Uint) (int64, error) {
 13	payoutAmount, err := pdca.CalculatePayout(amountPerExecution, endAccumulatedX128, debtX128)
 14	if err != nil {
 15		return 0, makeErrorWithDetails(errInvalidState, err.Error())
 16	}
 17
 18	return payoutAmount, nil
 19}
 20
 21// orderPayout is one payout of an order's accrued output.
 22type orderPayout struct {
 23	grossAmount        int64 // accrued output paid out
 24	executionFeeAmount int64 // the order's execution fee on grossAmount
 25	claimedAmount      int64 // grossAmount - executionFeeAmount, sent to the owner
 26}
 27
 28// calculateOrderPayout returns the payout of the output the order accrued up
 29// to endAccumulatedX128, with the order's execution fee deducted on its
 30// cumulative gross output (see pdca.CalculatePayoutExecutionFeeAmount).
 31func calculateOrderPayout(order *pdca.Order, endAccumulatedX128 *u256.Uint) (orderPayout, error) {
 32	grossAmount, err := calculatePayout(order.AmountPerExecution(), endAccumulatedX128, order.DebtX128())
 33	if err != nil {
 34		return orderPayout{}, err
 35	}
 36
 37	executionFeeAmount, err := pdca.CalculatePayoutExecutionFeeAmount(order.PaidGrossAmount(), grossAmount, order.ExecutionFeeRate())
 38	if err != nil {
 39		return orderPayout{}, makeErrorWithDetails(errInvalidState, err.Error())
 40	}
 41
 42	return orderPayout{
 43		grossAmount:        grossAmount,
 44		executionFeeAmount: executionFeeAmount,
 45		claimedAmount:      gnsmath.SafeSubInt64(grossAmount, executionFeeAmount),
 46	}, nil
 47}
 48
 49// recordOrderPayout adds a payout to the order's lifetime
 50// claimed amount and execution fee.
 51func recordOrderPayout(order *pdca.Order, payout orderPayout) {
 52	order.SetClaimedAmount(u256.Zero().Add(order.ClaimedAmount(), u256.NewUint(uint64(payout.claimedAmount))))
 53	order.SetExecutionFeeAmount(u256.Zero().Add(order.ExecutionFeeAmount(), u256.NewUint(uint64(payout.executionFeeAmount))))
 54}
 55
 56// calculateDebtX128AfterPayout wraps pdca.CalculateDebtX128AfterPayout,
 57// reporting an invalid payout as invalid state.
 58func calculateDebtX128AfterPayout(amountPerExecution int64, debtX128 *u256.Uint, payoutAmount int64) (*u256.Uint, error) {
 59	nextDebtX128, err := pdca.CalculateDebtX128AfterPayout(amountPerExecution, debtX128, payoutAmount)
 60	if err != nil {
 61		return nil, makeErrorWithDetails(errInvalidState, err.Error())
 62	}
 63
 64	return nextDebtX128, nil
 65}
 66
 67// getOrderEndAccumulatedOutputPerAmountX128 returns the accumulator an order
 68// is paid against, and whether all of its rounds have executed.
 69func getOrderEndAccumulatedOutputPerAmountX128(order *pdca.Order, group *pdca.Group) (*u256.Uint, bool, error) {
 70	if group.Round() < order.EndRound() {
 71		return group.AccumulatedOutputPerAmountX128(), false, nil
 72	}
 73
 74	roundMark := group.GetRoundMark(order.EndRound())
 75	if roundMark == nil {
 76		return nil, false, makeErrorWithDetails(errInvalidState, ufmt.Sprintf("missing snapshot for round %d", order.EndRound()))
 77	}
 78
 79	return roundMark.AccumulatedOutputPerAmountX128(), true, nil
 80}
 81
 82// releaseRoundMark drops one order reference from its end-round mark,
 83// removing the mark once no order references it.
 84func releaseRoundMark(group *pdca.Group, round uint64) error {
 85	roundMark := group.GetRoundMark(round)
 86	if roundMark == nil {
 87		return makeErrorWithDetails(errInvalidState, ufmt.Sprintf("missing mark for round %d", round))
 88	}
 89
 90	orderCount := roundMark.OrderCount() - 1
 91	if orderCount < 0 {
 92		return makeErrorWithDetails(errInvalidState, ufmt.Sprintf("negative order count for round %d", round))
 93	}
 94
 95	if orderCount > 0 {
 96		roundMark.SetOrderCount(orderCount)
 97		return nil
 98	}
 99
100	if round > group.Round() && roundMark.OrderAmount() != 0 {
101		return makeErrorWithDetails(errInvalidState, ufmt.Sprintf("unexecuted mark %d still has order amount", round))
102	}
103
104	group.RemoveRoundMark(round)
105
106	return nil
107}
108
109// feeRateMinAmount is the smallest amountPerExecution of the orders with
110// one execution fee rate that sell in a round.
111type feeRateMinAmount struct {
112	executionFeeRate      int64
113	minAmountPerExecution int64
114}
115
116// getFeeRateMinAmounts returns, by ascending execution fee rate, the
117// smallest amountPerExecution of the group's orders of each fee rate that
118// sell in round; it is empty when no order does.
119// The amount index sorts a group's orders by fee rate, then amount,
120// so each rate costs one seek past the finished orders before its first
121// selling one, and the number of seeks is the number of fee rates indexed.
122// The amount index keeps finished orders until they are paid out;
123// with prune, the entries of orders whose last round is before round
124// are removed on the way, as no later round sells them.
125func (d *dcaOrderImpl) getFeeRateMinAmounts(group *pdca.Group, round uint64, prune bool) []feeRateMinAmount {
126	orderAmountsByGroup := d.store.GetOrderAmountsByGroup()
127	prefix := pdca.GroupOrderPrefix(group.ID())
128	end := pdca.PrefixEnd(prefix)
129
130	minAmounts := []feeRateMinAmount{}
131	finishedKeys := []string{}
132	start := prefix
133
134	for {
135		found := false
136		executionFeeRate := int64(0)
137		minAmountPerExecution := int64(0)
138
139		orderAmountsByGroup.Iterate(start, end, func(key string, value any) bool {
140			if value.(uint64) < round {
141				if prune {
142					finishedKeys = append(finishedKeys, key)
143				}
144
145				return false
146			}
147
148			executionFeeRate = pdca.GroupOrderAmountKeyFeeRate(group.ID(), key)
149			minAmountPerExecution = pdca.GroupOrderAmountKeyAmount(group.ID(), key)
150			found = true
151
152			return true
153		})
154
155		if !found {
156			break
157		}
158
159		minAmounts = append(minAmounts, feeRateMinAmount{
160			executionFeeRate:      executionFeeRate,
161			minAmountPerExecution: minAmountPerExecution,
162		})
163
164		// Skip the larger orders of this rate.
165		start = pdca.PrefixEnd(pdca.GroupOrderFeeRatePrefix(group.ID(), executionFeeRate))
166	}
167
168	for _, key := range finishedKeys {
169		orderAmountsByGroup.Remove(key)
170	}
171
172	return minAmounts
173}
174
175// minAmountPerExecutionOf returns the smallest amountPerExecution of
176// minAmounts, or 0 when it is empty.
177func minAmountPerExecutionOf(minAmounts []feeRateMinAmount) int64 {
178	minAmountPerExecution := int64(0)
179
180	for i, minAmount := range minAmounts {
181		if i == 0 || minAmount.minAmountPerExecution < minAmountPerExecution {
182			minAmountPerExecution = minAmount.minAmountPerExecution
183		}
184	}
185
186	return minAmountPerExecution
187}
188
189// maxExecutionFeeRateOf returns the highest execution fee rate of
190// minAmounts, or 0 when it is empty.
191func maxExecutionFeeRateOf(minAmounts []feeRateMinAmount) int64 {
192	maxExecutionFeeRate := int64(0)
193
194	for _, minAmount := range minAmounts {
195		if minAmount.executionFeeRate > maxExecutionFeeRate {
196			maxExecutionFeeRate = minAmount.executionFeeRate
197		}
198	}
199
200	return maxExecutionFeeRate
201}
202
203// calculateMinOrderAmountOut returns the output, net of its own execution
204// fee rate, the order of minAmount is credited at outputPerAmountX128.
205func calculateMinOrderAmountOut(minAmount feeRateMinAmount, outputPerAmountX128 *u256.Uint) (int64, error) {
206	grossAmountOut, err := pdca.CalculatePayout(minAmount.minAmountPerExecution, outputPerAmountX128, u256.Zero())
207	if err != nil {
208		return 0, err
209	}
210
211	return pdca.CalculateMinNetAmountOut(grossAmountOut, minAmount.executionFeeRate)
212}
213
214func getScheduleKey(group *pdca.Group) string {
215	return pdca.ScheduleKey(group.NextExecutionTimestamp(), group.ID())
216}
217
218// rescheduleGroup sets a group's order amount and next execution timestamp,
219// keeping the schedule index in sync.
220// Only groups with a positive order amount are indexed.
221func (d *dcaOrderImpl) rescheduleGroup(group *pdca.Group, orderAmount int64, nextExecutionTimestamp int64) error {
222	if orderAmount < 0 {
223		return makeErrorWithDetails(errInvalidState, ufmt.Sprintf("negative order amount for group %s", group.ID()))
224	}
225
226	scheduledGroups := d.store.GetScheduledGroups()
227	if group.OrderAmount() > 0 {
228		scheduledGroups.Remove(getScheduleKey(group))
229	}
230
231	group.SetOrderAmount(orderAmount)
232	group.SetNextExecutionTimestamp(nextExecutionTimestamp)
233
234	if orderAmount > 0 {
235		scheduledGroups.Set(getScheduleKey(group), group.ID())
236	}
237
238	return nil
239}
240
241func (d *dcaOrderImpl) getOrder(orderID uint64) (*pdca.Order, error) {
242	value := d.store.GetOrders().Get(pdca.OrderKey(orderID))
243	if value == nil {
244		return nil, makeErrorWithDetails(errOrderNotFound, ufmt.Sprintf("orderId(%d)", orderID))
245	}
246
247	return value.(*pdca.Order), nil
248}
249
250func (d *dcaOrderImpl) getGroup(groupID string) (*pdca.Group, error) {
251	value := d.store.GetGroups().Get(groupID)
252	if value == nil {
253		return nil, makeErrorWithDetails(errGroupNotFound, ufmt.Sprintf("groupId(%s)", groupID))
254	}
255
256	return value.(*pdca.Group), nil
257}
258
259// getOrderWithGroup returns an order and the group it belongs to.
260func (d *dcaOrderImpl) getOrderWithGroup(orderID uint64) (*pdca.Order, *pdca.Group, error) {
261	order, err := d.getOrder(orderID)
262	if err != nil {
263		return nil, nil, err
264	}
265
266	group, err := d.getGroup(order.GroupID())
267	if err != nil {
268		return nil, nil, err
269	}
270
271	return order, group, nil
272}
273
274// validateOrderOutput checks that the round credits the smallest order of
275// each execution fee rate at least minOrderAmountOut of output net of that
276// rate, computed as its payout is. Within one rate an order's net payout
277// only grows with amountPerExecution, so every order of the round then
278// receives at least that much net of its own fee.
279func validateOrderOutput(
280	group *pdca.Group,
281	minAmounts []feeRateMinAmount,
282	minOrderAmountOut int64,
283	outputPerAmountX128 *u256.Uint,
284	executedAmountOut int64,
285	orderAmount int64,
286) error {
287	for _, minAmount := range minAmounts {
288		orderAmountOut, err := calculateMinOrderAmountOut(minAmount, outputPerAmountX128)
289		if err != nil {
290			return makeErrorWithDetails(errInvalidState, err.Error())
291		}
292
293		if orderAmountOut < minOrderAmountOut {
294			return makeErrorWithDetails(
295				errInsufficientOrderOutput,
296				ufmt.Sprintf(
297					"groupId(%s) amountPerExecution(%d) receives %d after executionFeeRate(%d), below minOrderAmountOut(%d), of executedAmountOut(%d) for orderAmount(%d)",
298					group.ID(), minAmount.minAmountPerExecution, orderAmountOut, minAmount.executionFeeRate, minOrderAmountOut, executedAmountOut, orderAmount,
299				),
300			)
301		}
302	}
303
304	return nil
305}