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

order.gno

7.06 Kb · 279 lines
  1package impl
  2
  3import (
  4	"strconv"
  5	"strings"
  6	"time"
  7
  8	plimit "gno.land/p/gnoswap/order/limit/v0"
  9	ufmt "gno.land/p/nt/ufmt/v0"
 10	"gno.land/r/gnoswap/common"
 11	"gno.land/r/gnoswap/order/halt"
 12	lo "gno.land/r/gnoswap/order/limit"
 13)
 14
 15func (l *limitOrderImpl) CreateOrder(_ int, rlm realm, tokenIn, tokenOut string, makingAmount, takingAmount, slippageBps, expiresAt int64, baseToken string) uint64 {
 16	prev := l.assertIsCall(0, rlm)
 17
 18	assertIsNotHalted(halt.OperationExecute)
 19
 20	if baseToken == "" || (baseToken != tokenIn && baseToken != tokenOut) {
 21		panic(errInvalidBaseToken)
 22	}
 23
 24	order, err := l.createOrder(0, rlm, prev.Address(), tokenIn, tokenOut, makingAmount, takingAmount, slippageBps, expiresAt)
 25	if err != nil {
 26		panic(realmError(err).Error())
 27	}
 28
 29	emitOrderCreated(prev.Address(), prev.PkgPath(), order, baseToken)
 30
 31	return order.ID()
 32}
 33
 34func (l *limitOrderImpl) createOrder(_ int, rlm realm, owner address, tokenIn, tokenOut string, makingAmount, takingAmount, slippageBps, expiresAt int64) (*plimit.Order, error) {
 35	now := time.Now().Unix()
 36
 37	orderID := l.store.GetNextOrderID()
 38	if orderID == ^uint64(0) {
 39		return nil, plimit.ErrAmountOverflow
 40	}
 41
 42	config := l.store.GetConfig()
 43
 44	max := config.MaxSlippageBps()
 45	if slippageBps < 0 || slippageBps > max {
 46		return nil, makeErrorWithDetails(errInvalidSlippage, ufmt.Sprintf("max %d bps, got %d bps", max, slippageBps))
 47	}
 48
 49	order, err := plimit.NewOrder(orderID, owner, tokenIn, tokenOut, makingAmount, takingAmount, slippageBps, config.ExecutionFeeRate(), now, expiresAt)
 50	if err != nil {
 51		return nil, err
 52	}
 53
 54	if err := l.validateCreateOrder(tokenIn, tokenOut, makingAmount, expiresAt, now); err != nil {
 55		return nil, err
 56	}
 57
 58	if err := l.store.SetNextOrderID(0, rlm, orderID+1); err != nil {
 59		return nil, err
 60	}
 61
 62	l.store.GetOrders().Set(plimit.OrderKey(orderID), order)
 63	l.store.GetOrdersByOwner().Set(plimit.OwnerOrderKey(owner, orderID), orderID)
 64
 65	common.SafeGRC20TransferFrom(0, rlm, tokenIn, owner, lo.Address(), makingAmount)
 66
 67	return order, nil
 68}
 69
 70func (l *limitOrderImpl) removeOrder(order *plimit.Order) {
 71	l.store.GetOrders().Remove(plimit.OrderKey(order.ID()))
 72	l.store.GetOrdersByOwner().Remove(plimit.OwnerOrderKey(order.Owner(), order.ID()))
 73}
 74
 75// CancelOrder returns the unsold input in the same transaction.
 76func (l *limitOrderImpl) CancelOrder(_ int, rlm realm, orderID uint64) int64 {
 77	prev := l.assertIsCall(0, rlm)
 78
 79	assertIsNotHalted(halt.OperationWithdraw)
 80
 81	order, err := l.getOrder(orderID)
 82	if err != nil {
 83		panic(err.Error())
 84	}
 85
 86	assertIsOrderOwner(order, prev.Address())
 87
 88	if order.RemainingInput() <= 0 {
 89		panic(makeErrorWithDetails(errOrderNotActive, "order has no remaining input").Error())
 90	}
 91
 92	expired := order.IsExpired(time.Now().Unix())
 93	refund := order.RefundInput()
 94	l.removeOrder(order)
 95
 96	if refund > 0 {
 97		common.SafeGRC20Transfer(0, rlm, order.TokenIn(), order.Owner(), refund)
 98	}
 99
100	emitOrderRefunded(prev.Address(), prev.PkgPath(), order, refund, expired)
101
102	return refund
103}
104
105// CleanupExpiredOrders bounds the number of pending records examined per scan.
106// The cursor is the last examined ID and remains usable after that order is removed.
107func (l *limitOrderImpl) CleanupExpiredOrders(_ int, rlm realm, startAfterOrderID uint64, maxOrders int) (int, uint64) {
108	prev := l.assertIsCall(0, rlm)
109
110	assertIsNotHalted(halt.OperationWithdraw)
111
112	if maxOrders <= 0 {
113		return 0, 0
114	}
115
116	limit := int(l.store.GetConfig().MaxCleanupBatchSize())
117	if maxOrders < limit {
118		limit = maxOrders
119	}
120
121	ids := make([]uint64, 0, limit)
122	more := false
123
124	l.store.GetOrders().Iterate(plimit.OrderKey(startAfterOrderID), "", func(_ string, value any) bool {
125		order := value.(*plimit.Order)
126		if order.ID() <= startAfterOrderID {
127			return false
128		}
129
130		if len(ids) == limit {
131			more = true
132			return true
133		}
134
135		ids = append(ids, order.ID())
136
137		return false
138	})
139
140	now := time.Now().Unix()
141	expired := 0
142
143	for _, orderID := range ids {
144		order, err := l.getOrder(orderID)
145		if err != nil {
146			panic(err.Error())
147		}
148
149		isExpired := order.IsExpired(now)
150		if !isExpired {
151			continue
152		}
153
154		remaining := order.RemainingInput()
155		if remaining > 0 {
156			balance := common.BalanceOf(order.TokenIn(), lo.Address())
157			if balance < remaining {
158				emitOrderCleanupInsufficientBalance(prev.Address(), prev.PkgPath(), order, remaining, balance)
159				continue
160			}
161		}
162
163		refund := order.RefundInput()
164		l.removeOrder(order)
165
166		if refund > 0 {
167			common.SafeGRC20Transfer(0, rlm, order.TokenIn(), order.Owner(), refund)
168		}
169
170		emitOrderRefunded(prev.Address(), prev.PkgPath(), order, refund, isExpired)
171
172		expired++
173	}
174
175	if more {
176		return expired, ids[len(ids)-1]
177	}
178
179	return expired, 0
180}
181
182// CleanupExpiredOrdersByIDs examines only the validated IDs supplied by the caller.
183func (l *limitOrderImpl) CleanupExpiredOrdersByIDs(_ int, rlm realm, orderIDs string) (int, string) {
184	prev := l.assertIsCall(0, rlm)
185
186	assertIsNotHalted(halt.OperationWithdraw)
187
188	if orderIDs == "" {
189		return 0, ""
190	}
191
192	ids := parseCleanupOrderIDsCSV(orderIDs, l.store.GetConfig().MaxCleanupBatchSize())
193	now := time.Now().Unix()
194	expired := 0
195	retryOrderIDs := make([]string, 0, len(ids))
196
197	for _, orderID := range ids {
198		value := l.store.GetOrders().Get(plimit.OrderKey(orderID))
199		if value == nil {
200			continue
201		}
202
203		order, ok := value.(*plimit.Order)
204		if !ok || order == nil {
205			panic(makeErrorWithDetails(errInvalidState, "invalid stored order").Error())
206		}
207
208		isExpired := order.IsExpired(now)
209		if !isExpired {
210			retryOrderIDs = append(retryOrderIDs, strconv.FormatUint(orderID, 10))
211			continue
212		}
213
214		remaining := order.RemainingInput()
215		if remaining > 0 {
216			balance := common.BalanceOf(order.TokenIn(), lo.Address())
217			if balance < remaining {
218				emitOrderCleanupInsufficientBalance(prev.Address(), prev.PkgPath(), order, remaining, balance)
219
220				retryOrderIDs = append(retryOrderIDs, strconv.FormatUint(orderID, 10))
221
222				continue
223			}
224		}
225
226		refund := order.RefundInput()
227		l.removeOrder(order)
228
229		if refund > 0 {
230			common.SafeGRC20Transfer(0, rlm, order.TokenIn(), order.Owner(), refund)
231		}
232
233		emitOrderRefunded(prev.Address(), prev.PkgPath(), order, refund, isExpired)
234
235		expired++
236	}
237
238	return expired, strings.Join(retryOrderIDs, ",")
239}
240
241// parseCleanupOrderIDsCSV validates the complete bounded input before cleanup
242// can change any order or refund any escrow.
243func parseCleanupOrderIDsCSV(orderIDs string, maxBatchSize int64) []uint64 {
244	if len(orderIDs) > maxCleanupOrderIDsCSVLength {
245		panic(errInvalidCleanupOrderIDs)
246	}
247
248	itemCount := 1
249
250	for i := 0; i < len(orderIDs); i++ {
251		if orderIDs[i] == ',' {
252			itemCount++
253			if itemCount > int(maxCleanupBatchSizeLimit) || int64(itemCount) > maxBatchSize {
254				panic(errInvalidCleanupOrderIDs)
255			}
256		}
257	}
258
259	if itemCount > int(maxCleanupBatchSizeLimit) || int64(itemCount) > maxBatchSize {
260		panic(errInvalidCleanupOrderIDs)
261	}
262
263	values := strings.Split(orderIDs, ",")
264	ids := make([]uint64, len(values))
265
266	var previous uint64
267
268	for i, value := range values {
269		id, err := strconv.ParseUint(value, 10, 64)
270		if err != nil || id == 0 || strconv.FormatUint(id, 10) != value || (i > 0 && id <= previous) {
271			panic(errInvalidCleanupOrderIDs)
272		}
273
274		ids[i] = id
275		previous = id
276	}
277
278	return ids
279}