order.gno
6.99 Kb · 256 lines
1package limit
2
3import (
4 "math"
5
6 u256 "gno.land/p/gnoswap/uint256/v1"
7)
8
9// OrderStatus is the time-derived lifecycle state of a pending limit order.
10type OrderStatus string
11
12const (
13 // OrderStatusOpen: no input has been filled and the order has not expired.
14 OrderStatusOpen OrderStatus = "OPEN"
15 // OrderStatusPartiallyFilled: some input has been filled while unexpired.
16 OrderStatusPartiallyFilled OrderStatus = "PARTIALLY_FILLED"
17 // OrderStatusExpired: the deadline has been reached while input awaits refund.
18 OrderStatusExpired OrderStatus = "EXPIRED"
19)
20
21func (s OrderStatus) String() string {
22 return string(s)
23}
24
25// Order keeps the original net exchange ratio and execution fee rate
26// snapshotted at creation. grossOutput is the output received from the pool.
27// Execution fees are paid at each fill, but rounded on cumulative gross output
28// so splitting cannot evade them. Every amount, including cumulative gross
29// output, stays within MaxInt64.
30type Order struct {
31 id uint64
32 owner address
33 tokenIn string
34 tokenOut string
35
36 makingAmount int64
37 takingAmount int64
38 slippageBps int64
39 executionFeeRate int64
40
41 createdAt int64
42 expiresAt int64
43
44 filledInput int64
45 refundedInput int64
46 grossOutput int64
47 executionFee int64
48}
49
50// NewOrder creates an order with executionFeeRate snapshotted for its lifetime.
51// Domain terms, including a positive expiry, are validated here;
52// token registration and configured duration bounds belong to the implementation.
53func NewOrder(
54 id uint64,
55 owner address,
56 tokenIn string,
57 tokenOut string,
58 makingAmount int64,
59 takingAmount int64,
60 slippageBps int64,
61 executionFeeRate int64,
62 createdAt int64,
63 expiresAt int64,
64) (*Order, error) {
65 if makingAmount <= 0 {
66 return nil, ErrInvalidMakingAmount
67 }
68
69 if takingAmount <= 0 {
70 return nil, ErrInvalidTakingAmount
71 }
72
73 if slippageBps < 0 || slippageBps > BpsDenominator {
74 return nil, ErrInvalidSlippage
75 }
76
77 if !isValidExecutionFeeRate(executionFeeRate) {
78 return nil, ErrInvalidExecutionFeeRate
79 }
80
81 if expiresAt <= 0 {
82 return nil, ErrInvalidExpiresAt
83 }
84
85 return &Order{
86 id: id,
87 owner: owner,
88 tokenIn: tokenIn,
89 tokenOut: tokenOut,
90 makingAmount: makingAmount,
91 takingAmount: takingAmount,
92 slippageBps: slippageBps,
93 executionFeeRate: executionFeeRate,
94 createdAt: createdAt,
95 expiresAt: expiresAt,
96 }, nil
97}
98
99func (o *Order) ID() uint64 { return o.id }
100func (o *Order) Owner() address { return o.owner }
101func (o *Order) TokenIn() string { return o.tokenIn }
102func (o *Order) TokenOut() string { return o.tokenOut }
103func (o *Order) MakingAmount() int64 { return o.makingAmount }
104func (o *Order) TakingAmount() int64 { return o.takingAmount }
105func (o *Order) SlippageBps() int64 { return o.slippageBps }
106func (o *Order) ExecutionFeeRate() int64 { return o.executionFeeRate }
107
108// Status derives the order lifecycle state at the supplied Unix timestamp.
109func (o *Order) Status(now int64) OrderStatus {
110 if o.IsExpired(now) {
111 return OrderStatusExpired
112 }
113
114 if o.FilledInput() > 0 {
115 return OrderStatusPartiallyFilled
116 }
117
118 return OrderStatusOpen
119}
120func (o *Order) CreatedAt() int64 { return o.createdAt }
121func (o *Order) ExpiresAt() int64 { return o.expiresAt }
122func (o *Order) FilledInput() int64 { return o.filledInput }
123func (o *Order) RefundedInput() int64 { return o.refundedInput }
124func (o *Order) GrossOutput() int64 { return o.grossOutput }
125func (o *Order) ExecutionFee() int64 { return o.executionFee }
126
127// Clone returns a detached copy that shares no mutable state with o.
128// Fields are copied one by one, so a field added later must be added here.
129func (o *Order) Clone() *Order {
130 return &Order{
131 id: o.id,
132 owner: o.owner,
133 tokenIn: o.tokenIn,
134 tokenOut: o.tokenOut,
135
136 makingAmount: o.makingAmount,
137 takingAmount: o.takingAmount,
138 slippageBps: o.slippageBps,
139 executionFeeRate: o.executionFeeRate,
140
141 createdAt: o.createdAt,
142 expiresAt: o.expiresAt,
143
144 filledInput: o.filledInput,
145 refundedInput: o.refundedInput,
146 grossOutput: o.grossOutput,
147 executionFee: o.executionFee,
148 }
149}
150
151// RemainingInput returns escrowed input not yet filled or refunded.
152func (o *Order) RemainingInput() int64 {
153 return o.makingAmount - o.filledInput - o.refundedInput
154}
155
156// IsExpired reports whether the deadline has been reached at now.
157func (o *Order) IsExpired(now int64) bool {
158 return now >= o.expiresAt
159}
160
161// IsActive reports whether unfilled input can accept a fill at now.
162func (o *Order) IsActive(now int64) bool {
163 return !o.IsExpired(now) && o.RemainingInput() > 0
164}
165
166// MinimumUserOutput returns the owner-net output a fill of fillInput must
167// deliver: the slippage-adjusted original ratio, rounded up.
168func (o *Order) MinimumUserOutput(fillInput int64) (int64, error) {
169 if fillInput <= 0 || fillInput > o.RemainingInput() {
170 return 0, ErrInvalidFillAmount
171 }
172
173 return proportionalMinimumOutput(o.makingAmount, o.takingAmount, o.slippageBps, fillInput)
174}
175
176// GetMinimumOutput returns the exact minimum pool output needed by a
177// fillInput, including the next cumulative execution-fee rounding
178// boundary. It returns ErrAmountOverflow when no fill could satisfy the
179// minimum without cumulative gross output exceeding MaxInt64.
180func (o *Order) GetMinimumOutput(fillInput int64) (int64, error) {
181 minimum, err := o.MinimumUserOutput(fillInput)
182 if err != nil {
183 return 0, err
184 }
185
186 // A zero owner minimum still requires a positive pool output.
187 if minimum == 0 {
188 if o.grossOutput == math.MaxInt64 {
189 return 0, ErrAmountOverflow
190 }
191
192 return 1, nil
193 }
194
195 requiredNet := u256.NewUint(uint64(o.grossOutput - o.executionFee))
196 requiredNet.Add(requiredNet, u256.NewUint(uint64(minimum)))
197
198 requiredGross, err := requiredGrossOutput(requiredNet, o.executionFeeRate)
199 if err != nil {
200 return 0, err
201 }
202
203 return requiredGross - o.grossOutput, nil
204}
205
206// ApplyFill records a fill of fillInput that produced poolOutput at now.
207// It validates every quantity before changing any accounting; on error the
208// order is unchanged.
209func (o *Order) ApplyFill(fillInput, poolOutput, now int64) error {
210 if o.RemainingInput() <= 0 {
211 return ErrOrderNotActive
212 }
213
214 if o.IsExpired(now) {
215 return ErrOrderExpired
216 }
217
218 minimum, err := o.MinimumUserOutput(fillInput)
219 if err != nil {
220 return err
221 }
222
223 if poolOutput <= 0 {
224 return ErrInsufficientOutput
225 }
226
227 if poolOutput > math.MaxInt64-o.grossOutput {
228 return ErrAmountOverflow
229 }
230
231 gross := o.grossOutput + poolOutput
232
233 executionFee, err := CumulativeExecutionFee(gross, o.executionFeeRate)
234 if err != nil {
235 return err
236 }
237
238 if poolOutput-(executionFee-o.executionFee) < minimum {
239 return ErrSlippageExceeded
240 }
241
242 o.filledInput += fillInput
243 o.grossOutput = gross
244 o.executionFee = executionFee
245
246 return nil
247}
248
249// RefundInput consumes the remaining escrow exactly once and returns it,
250// without pretending that refunded input was traded. Later calls return 0.
251func (o *Order) RefundInput() int64 {
252 remaining := o.RemainingInput()
253 o.refundedInput += remaining
254
255 return remaining
256}