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

getter.gno

14.42 Kb · 453 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	"gno.land/p/gnoswap/utils/v1"
  9	rotree "gno.land/p/nt/bptree/rotree/v0"
 10	"gno.land/p/onbloc/json/v0"
 11
 12	"gno.land/r/gnoswap/order/halt"
 13	"gno.land/r/gnoswap/order/whitelist"
 14)
 15
 16// Getters return copies of stored orders, groups, and configs.
 17// A stored pointer must never leave the realm: methods of pdca types run
 18// with the storing realm's authority, so a caller holding the pointer
 19// could mutate state through its setters.
 20// Store trees are wrapped in read-only views for the same reason:
 21// views of trees holding pointers copy every entry they return.
 22// Group copies leave out the round marks, so their cost does not grow with
 23// the marks any order creator can add; GetGroupRoundMarks reads them.
 24
 25// GetConfig returns a copy of the configuration.
 26func (d *dcaOrderImpl) GetConfig() *pdca.Config {
 27	return d.store.GetConfig().Clone()
 28}
 29
 30// GetNextOrderID returns the ID the next created order receives.
 31func (d *dcaOrderImpl) GetNextOrderID() uint64 {
 32	return d.store.GetNextOrderID()
 33}
 34
 35// ExistsOrder reports whether orderID is an active order.
 36func (d *dcaOrderImpl) ExistsOrder(orderID uint64) bool {
 37	return d.store.GetOrders().Has(pdca.OrderKey(orderID))
 38}
 39
 40// GetOrder returns a copy of an active order.
 41func (d *dcaOrderImpl) GetOrder(orderID uint64) (*pdca.Order, error) {
 42	order, err := d.getOrder(orderID)
 43	if err != nil {
 44		return nil, err
 45	}
 46
 47	return order.Clone(), nil
 48}
 49
 50// GetOrders returns a read-only view of active orders keyed by OrderKey.
 51func (d *dcaOrderImpl) GetOrders() *rotree.ReadOnlyTree {
 52	return rotree.Wrap(d.store.GetOrders(), cloneOrderEntry)
 53}
 54
 55// GetOrdersByOwner returns the read-only OwnerOrderKey -> orderID index.
 56func (d *dcaOrderImpl) GetOrdersByOwner() *rotree.ReadOnlyTree {
 57	return rotree.Wrap(d.store.GetOrdersByOwner(), nil)
 58}
 59
 60// GetClaimableAmount returns what the next Claim of an active order pays.
 61func (d *dcaOrderImpl) GetClaimableAmount(orderID uint64) int64 {
 62	order, group, err := d.getOrderWithGroup(orderID)
 63	if err != nil {
 64		return 0
 65	}
 66
 67	claimableAmount, err := calculateClaimableAmount(order, group)
 68	if err != nil {
 69		panic(err.Error())
 70	}
 71
 72	return claimableAmount
 73}
 74
 75// GetOrderIDsByOwner pages an owner's active order IDs.
 76func (d *dcaOrderImpl) GetOrderIDsByOwner(owner address, startAfterID uint64, count int) []uint64 {
 77	if count <= 0 {
 78		return []uint64{}
 79	}
 80
 81	prefix := pdca.OwnerOrderPrefix(owner)
 82	start := prefix
 83
 84	if startAfterID > 0 {
 85		if startAfterID == ^uint64(0) {
 86			return []uint64{}
 87		}
 88
 89		start = pdca.OwnerOrderKey(owner, gnsmath.SafeAddUint64(startAfterID, 1))
 90	}
 91
 92	orderIDs := []uint64{}
 93
 94	d.store.GetOrdersByOwner().Iterate(start, pdca.PrefixEnd(prefix), func(_ string, value any) bool {
 95		orderIDs = append(orderIDs, value.(uint64))
 96
 97		return len(orderIDs) >= count
 98	})
 99
100	return orderIDs
101}
102
103// GetOrderIDsByGroup pages a group's active order IDs.
104func (d *dcaOrderImpl) GetOrderIDsByGroup(groupID string, startAfterID uint64, count int) []uint64 {
105	if count <= 0 {
106		return []uint64{}
107	}
108
109	orderIDs, _ := d.getGroupOrderIDs(groupID, startAfterID, count)
110
111	return orderIDs
112}
113
114// ExistsGroup reports whether groupID is a stored group.
115func (d *dcaOrderImpl) ExistsGroup(groupID string) bool {
116	return d.store.GetGroups().Has(groupID)
117}
118
119// GetGroup returns a copy of a group without its round marks.
120func (d *dcaOrderImpl) GetGroup(groupID string) (*pdca.Group, error) {
121	group, err := d.getGroup(groupID)
122	if err != nil {
123		return nil, err
124	}
125
126	return group.CloneWithoutRoundMarks(), nil
127}
128
129// GetGroups returns a read-only view of groups keyed by group ID.
130func (d *dcaOrderImpl) GetGroups() *rotree.ReadOnlyTree {
131	return rotree.Wrap(d.store.GetGroups(), cloneGroupEntry)
132}
133
134// GetGroupRoundMarks returns a read-only view of a group's round marks
135// keyed by RoundKey, or nil if the group does not exist.
136func (d *dcaOrderImpl) GetGroupRoundMarks(groupID string) *rotree.ReadOnlyTree {
137	group, err := d.getGroup(groupID)
138	if err != nil {
139		return nil
140	}
141
142	return group.RoundMarks()
143}
144
145// GetOrdersByGroup returns the read-only GroupOrderKey -> orderID index.
146func (d *dcaOrderImpl) GetOrdersByGroup() *rotree.ReadOnlyTree {
147	return rotree.Wrap(d.store.GetOrdersByGroup(), nil)
148}
149
150// GetOrderAmountsByGroup returns the read-only
151// GroupOrderAmountKey -> endRound index.
152func (d *dcaOrderImpl) GetOrderAmountsByGroup() *rotree.ReadOnlyTree {
153	return rotree.Wrap(d.store.GetOrderAmountsByGroup(), nil)
154}
155
156// GetScheduledGroups returns the read-only ScheduleKey -> groupID index.
157func (d *dcaOrderImpl) GetScheduledGroups() *rotree.ReadOnlyTree {
158	return rotree.Wrap(d.store.GetScheduledGroups(), nil)
159}
160
161// GetTokenMinAmountPerExecution returns the minimum input per execution set
162// for tokenPath, or 0 if none is set.
163func (d *dcaOrderImpl) GetTokenMinAmountPerExecution(tokenPath string) int64 {
164	return getTokenMinAmountPerExecution(d.store, tokenPath)
165}
166
167// GetMinAmountPerExecution returns the minimum input per execution a new order
168// selling tokenPath needs: the larger of the global and the token minimum.
169func (d *dcaOrderImpl) GetMinAmountPerExecution(tokenPath string) int64 {
170	return d.minAmountPerExecution(tokenPath)
171}
172
173// GetTokenMinAmountsPerExecution returns the read-only tokenPath -> int64
174// index of per-token minimums.
175func (d *dcaOrderImpl) GetTokenMinAmountsPerExecution() *rotree.ReadOnlyTree {
176	return rotree.Wrap(d.store.GetTokenMinAmountsPerExecution(), nil)
177}
178
179// GetPairPriceLimit returns a copy of the price limit of selling inputToken
180// for outputToken, and whether one is set.
181func (d *dcaOrderImpl) GetPairPriceLimit(inputToken string, outputToken string) (*pdca.PairPriceLimit, bool) {
182	limit := getPairPriceLimit(d.store.GetPairPriceLimits(), inputToken, outputToken)
183	if limit == nil {
184		return nil, false
185	}
186
187	return limit.Clone(), true
188}
189
190// GetPairPriceLimits returns a read-only view of the pair price limits keyed
191// by PairKey.
192func (d *dcaOrderImpl) GetPairPriceLimits() *rotree.ReadOnlyTree {
193	return rotree.Wrap(d.store.GetPairPriceLimits(), clonePairPriceLimitEntry)
194}
195
196// GetExecutableGroups lists copies of due groups after the cursor entry.
197// The schedule index is ordered by next execution timestamp,
198// so the scan stops at the first group that is not yet due.
199// Pools are not quoted; a listed round may still revert.
200// Nothing is listed while rounds are halted.
201func (d *dcaOrderImpl) GetExecutableGroups(cursor string, count int) ([]*pdca.Group, error) {
202	if count <= 0 {
203		return []*pdca.Group{}, nil
204	}
205
206	start, err := pdca.ParseScheduleCursor(cursor)
207	if err != nil {
208		return nil, makeErrorWithDetails(errInvalidCursor, cursor)
209	}
210
211	// Rounds cannot run while execution is halted.
212	if isExecutionHalted() {
213		return []*pdca.Group{}, nil
214	}
215
216	currentTimestamp := time.Now().Unix()
217	groupIDs := []string{}
218	d.store.GetScheduledGroups().Iterate(start, "", func(key string, value any) bool {
219		if key == start && start != "" {
220			return false
221		}
222
223		if pdca.ScheduleKeyTimestamp(key) > currentTimestamp {
224			return true
225		}
226
227		groupIDs = append(groupIDs, value.(string))
228
229		return len(groupIDs) >= count
230	})
231
232	groups := make([]*pdca.Group, 0, len(groupIDs))
233	for _, groupID := range groupIDs {
234		group, err := d.GetGroup(groupID)
235		if err != nil {
236			return nil, err
237		}
238
239		groups = append(groups, group)
240	}
241
242	return groups, nil
243}
244
245// GetOrderExecutionLogs returns copies of up to count of an order's unreleased
246// execution logs, oldest first.
247func (d *dcaOrderImpl) GetOrderExecutionLogs(orderID uint64, count int) ([]*pdca.ExecutionLog, error) {
248	order, err := d.getOrder(orderID)
249	if err != nil {
250		return nil, err
251	}
252
253	return pdca.ExecutionLogs(d.store.GetExecutionLogs(), order, count), nil
254}
255
256// GetExecutionLogs returns the read-only ExecutionLogKey -> lastRound index
257// of unreleased execution logs.
258func (d *dcaOrderImpl) GetExecutionLogs() *rotree.ReadOnlyTree {
259	return rotree.Wrap(d.store.GetExecutionLogs(), nil)
260}
261
262// GetPendingExecutionFeeAmount returns the execution fee of tokenPath
263// held by this realm until the protocol fee realm accepts it.
264func (d *dcaOrderImpl) GetPendingExecutionFeeAmount(tokenPath string) int64 {
265	return getPendingExecutionFeeAmount(d.store.GetPendingExecutionFees(), tokenPath)
266}
267
268// GetPendingExecutionFees returns the read-only tokenPath -> amount index
269// of execution fees held until the protocol fee realm accepts them.
270func (d *dcaOrderImpl) GetPendingExecutionFees() *rotree.ReadOnlyTree {
271	return rotree.Wrap(d.store.GetPendingExecutionFees(), nil)
272}
273
274// GetExecutionQuote reports how the group's next round would trade now.
275// Every pool is quoted here, even a single one,
276// so the selection and output match ExecuteGroup in the same block.
277func (d *dcaOrderImpl) GetExecutionQuote(groupID string) string {
278	group, err := d.getGroup(groupID)
279	if err != nil {
280		return ""
281	}
282
283	config := d.store.GetConfig()
284	amountIn := group.OrderAmount()
285	selectedPoolPath := ""
286	expectedAmountOut := int64(0)
287	expectedExecutionFeeAmount := int64(0)
288	expectedMinOrderAmountOut := int64(0)
289	candidateNodes := []*json.Node{}
290	minAmountNodes := []*json.Node{}
291
292	// The round checks the smallest order of each execution fee rate after
293	// that rate. The quote's fee and order output assume the highest rate of
294	// the orders the round sells, the most any of them pays.
295	minAmounts := []feeRateMinAmount{}
296	if amountIn > 0 {
297		minAmounts = d.getFeeRateMinAmounts(group, group.Round()+1, false)
298	}
299
300	minAmountPerExecution := minAmountPerExecutionOf(minAmounts)
301	executionFeeRate := maxExecutionFeeRateOf(minAmounts)
302
303	priceLimit := getPairPriceLimit(d.store.GetPairPriceLimits(), group.InputToken(), group.OutputToken())
304	minOutputPerInputX128 := "0"
305	priceLimitUpdatedAt := int64(0)
306
307	if priceLimit != nil {
308		minOutputPerInputX128 = priceLimit.MinOutputPerInputX128().ToString()
309		priceLimitUpdatedAt = priceLimit.UpdatedAt()
310	}
311
312	if amountIn > 0 {
313		selectedPool, candidates := selectPool(whitelist.GetWhitelistedPools(whitelist.TargetDCA), priceLimit, config.MaxPoolPriceDeviationRate(), config.MaxPairPriceLimitAge(), group.InputToken(), group.OutputToken(), amountIn, true)
314		if selectedPool != nil {
315			expectedAmountOut = selectedPool.quotedAmountOut
316			selectedPoolPath = selectedPool.poolPath
317
318			expectedOrderAmountOut, err := pdca.CalculateMinNetAmountOut(expectedAmountOut, executionFeeRate)
319			if err != nil {
320				panic(err.Error())
321			}
322
323			expectedExecutionFeeAmount = expectedAmountOut - expectedOrderAmountOut
324		}
325
326		// The least output the round's per-order check would compare with
327		// max(1, minOrderAmountOut).
328		outputPerAmountX128, err := pdca.CalculateOutputPerAmountX128(expectedAmountOut, amountIn)
329		if err != nil {
330			panic(err.Error())
331		}
332
333		for i, minAmount := range minAmounts {
334			orderAmountOut, err := calculateMinOrderAmountOut(minAmount, outputPerAmountX128)
335			if err != nil {
336				panic(err.Error())
337			}
338
339			if i == 0 || orderAmountOut < expectedMinOrderAmountOut {
340				expectedMinOrderAmountOut = orderAmountOut
341			}
342
343			minAmountNodes = append(minAmountNodes, json.ObjectNode("", map[string]*json.Node{
344				"executionFeeRate":      intNode(minAmount.executionFeeRate),
345				"minAmountPerExecution": intNode(minAmount.minAmountPerExecution),
346			}))
347		}
348
349		for _, candidate := range candidates {
350			candidateAmountOut := int64(0)
351			if candidate.isQuoted {
352				candidateAmountOut = candidate.quotedAmountOut
353			}
354
355			candidateNodes = append(candidateNodes, json.ObjectNode("", map[string]*json.Node{
356				"poolPath":         json.StringNode("", candidate.poolPath),
357				"eligible":         json.BoolNode("", candidate.isEligible()),
358				"ineligibleCode":   json.StringNode("", candidate.ineligibleCode),
359				"ineligibleReason": json.StringNode("", candidate.ineligibleReason),
360				"amountOut":        intNode(candidateAmountOut),
361			}))
362		}
363	}
364
365	return marshal(map[string]*json.Node{
366		"groupId":                      json.StringNode("", group.ID()),
367		"inputToken":                   json.StringNode("", group.InputToken()),
368		"outputToken":                  json.StringNode("", group.OutputToken()),
369		"amountIn":                     intNode(amountIn),
370		"minAmountPerExecution":        intNode(minAmountPerExecution),
371		"executable":                   json.BoolNode("", isGroupExecutable(group, time.Now().Unix())),
372		"selectedPool":                 json.StringNode("", selectedPoolPath),
373		"expectedAmountOut":            intNode(expectedAmountOut),
374		"executionFeeRate":             intNode(executionFeeRate),
375		"expectedExecutionFeeAmount":   intNode(expectedExecutionFeeAmount),
376		"expectedOrderAmountOut":       intNode(expectedAmountOut - expectedExecutionFeeAmount),
377		"expectedMinOrderAmountOut":    intNode(expectedMinOrderAmountOut),
378		"minAmountsByExecutionFeeRate": json.ArrayNode("", minAmountNodes),
379		"minOutputPerInputX128":        json.StringNode("", minOutputPerInputX128),
380		"priceLimitUpdatedAt":          intNode(priceLimitUpdatedAt),
381		"candidates":                   json.ArrayNode("", candidateNodes),
382	})
383}
384
385// calculateClaimableAmount returns what the next Claim pays the owner,
386// net of the order's execution fee.
387func calculateClaimableAmount(order *pdca.Order, group *pdca.Group) (int64, error) {
388	endAccumulatedX128, _, err := getOrderEndAccumulatedOutputPerAmountX128(order, group)
389	if err != nil {
390		return 0, err
391	}
392
393	payout, err := calculateOrderPayout(order, endAccumulatedX128)
394	if err != nil {
395		return 0, err
396	}
397
398	return payout.claimedAmount, nil
399}
400
401// isGroupExecutable reports whether the schedule and the halts allow
402// the group's next round now.
403// Pools are not quoted here.
404func isGroupExecutable(group *pdca.Group, currentTimestamp int64) bool {
405	return group.OrderAmount() > 0 && currentTimestamp >= group.NextExecutionTimestamp() && !isExecutionHalted()
406}
407
408// isExecutionHalted reports whether execute or withdraw is halted,
409// matching the checks ExecuteGroup makes before running a round.
410func isExecutionHalted() bool {
411	_, halted := haltedOperation(halt.OperationExecute, halt.OperationWithdraw)
412	return halted
413}
414
415func marshal(fields map[string]*json.Node) string {
416	b, err := json.Marshal(json.ObjectNode("", fields))
417	if err != nil {
418		panic(err.Error())
419	}
420
421	return string(b)
422}
423
424func intNode(v int64) *json.Node {
425	return json.StringNode("", utils.FormatInt(v))
426}
427
428func cloneOrderEntry(value any) any {
429	order, ok := value.(*pdca.Order)
430	if !ok {
431		return nil
432	}
433
434	return order.Clone()
435}
436
437func cloneGroupEntry(value any) any {
438	group, ok := value.(*pdca.Group)
439	if !ok {
440		return nil
441	}
442
443	return group.CloneWithoutRoundMarks()
444}
445
446func clonePairPriceLimitEntry(value any) any {
447	limit, ok := value.(*pdca.PairPriceLimit)
448	if !ok {
449		return nil
450	}
451
452	return limit.Clone()
453}