math.gno
9.83 Kb · 270 lines
1package dca
2
3import (
4 "math"
5
6 "gno.land/p/gnoswap/gnsmath/v1"
7 u256 "gno.land/p/gnoswap/uint256/v1"
8)
9
10// Read-only constants: never pass them to a mutating u256 method.
11var (
12 q128 = u256.Zero().Lsh(u256.One(), 128)
13 maxInt64U256 = u256.NewUintFromInt64(math.MaxInt64)
14)
15
16// Q128 returns a copy of 2^128, the accumulator scale.
17func Q128() *u256.Uint {
18 return q128.Clone()
19}
20
21// CalculateNextExecutionTimestamp returns the first slot strictly after
22// currentTimestamp.
23// Slots keep a fixed cadence from scheduledTimestamp,
24// so a late execution skips missed slots instead of running them back to back.
25// interval must be positive and the timestamps non-negative;
26// a next slot above math.MaxInt64 returns ErrOverflow.
27func CalculateNextExecutionTimestamp(scheduledTimestamp int64, currentTimestamp int64, interval int64) (int64, error) {
28 if interval <= 0 || scheduledTimestamp < 0 || currentTimestamp < 0 {
29 return 0, ErrInvalidInput
30 }
31
32 // Slots from scheduledTimestamp to the next one, at least one,
33 // and the most that stay within math.MaxInt64.
34 maxSlotCount := (math.MaxInt64 - scheduledTimestamp) / interval
35
36 slotCount := int64(1)
37
38 if currentTimestamp >= scheduledTimestamp {
39 elapsedSlotCount := (currentTimestamp - scheduledTimestamp) / interval
40 if elapsedSlotCount >= maxSlotCount {
41 return 0, ErrOverflow
42 }
43
44 slotCount = gnsmath.SafeAddInt64(elapsedSlotCount, 1)
45 }
46
47 if slotCount > maxSlotCount {
48 return 0, ErrOverflow
49 }
50
51 return gnsmath.SafeAddInt64(scheduledTimestamp, gnsmath.SafeMulInt64(slotCount, interval)), nil
52}
53
54// CalculateFirstSlotTimestamp returns the first slot at or after
55// currentTimestamp, that is the smallest t >= currentTimestamp
56// with t % interval == slotOffset.
57// interval must be positive and slotOffset in [0, interval).
58func CalculateFirstSlotTimestamp(currentTimestamp int64, interval int64, slotOffset int64) (int64, error) {
59 if interval <= 0 || slotOffset < 0 || slotOffset >= interval || currentTimestamp < 0 {
60 return 0, ErrInvalidInput
61 }
62
63 // slotOffset and the remainder are both in [0, interval),
64 // so the wait stays within [0, interval) without overflowing.
65 wait := slotOffset - currentTimestamp%interval
66 if wait < 0 {
67 wait = gnsmath.SafeAddInt64(wait, interval)
68 }
69
70 if currentTimestamp > math.MaxInt64-wait {
71 return 0, ErrOverflow
72 }
73
74 return gnsmath.SafeAddInt64(currentTimestamp, wait), nil
75}
76
77// CalculateMinExecutionGap returns minExecutionGapRate (basis points) of
78// interval in seconds, rounded up: the minimum time between two executions
79// of a group.
80func CalculateMinExecutionGap(interval int64, minExecutionGapRate int64) (int64, error) {
81 if interval < 0 || minExecutionGapRate < 0 {
82 return 0, ErrInvalidInput
83 }
84
85 return toInt64(u256.MulDivRoundingUp(
86 u256.NewUint(uint64(interval)),
87 u256.NewUint(uint64(minExecutionGapRate)),
88 u256.NewUint(uint64(BasisPointDenominator)),
89 ))
90}
91
92// CalculateNextExecutionTimestampWithGap returns the first slot after
93// currentTimestamp that is also at least minExecutionGap seconds after
94// currentTimestamp.
95// Like CalculateNextExecutionTimestamp, it keeps the cadence anchored at
96// scheduledTimestamp, skipping slots that fall inside the gap.
97// minExecutionGap must be non-negative; a gap reaching past math.MaxInt64
98// returns ErrOverflow.
99func CalculateNextExecutionTimestampWithGap(scheduledTimestamp int64, currentTimestamp int64, interval int64, minExecutionGap int64) (int64, error) {
100 if minExecutionGap < 0 {
101 return 0, ErrInvalidInput
102 }
103
104 // The next slot is strictly after its argument, so it is at least
105 // minExecutionGap seconds after currentTimestamp.
106 after := currentTimestamp
107 if minExecutionGap > 0 {
108 if currentTimestamp > math.MaxInt64-(minExecutionGap-1) {
109 return 0, ErrOverflow
110 }
111
112 after += minExecutionGap - 1
113 }
114
115 return CalculateNextExecutionTimestamp(scheduledTimestamp, after, interval)
116}
117
118// CalculateExecutionFeeAmount returns
119// amount * executionFeeRate / BasisPointDenominator,
120// rounded down, so the fee never exceeds the configured share.
121// Config.SetExecutionFeeRate bounds the rate to [0, MaxExecutionFeeRate].
122func CalculateExecutionFeeAmount(amount int64, executionFeeRate int64) (int64, error) {
123 if amount < 0 || executionFeeRate < 0 {
124 return 0, ErrInvalidInput
125 }
126
127 return toInt64(calculateExecutionFeeAmountU256(u256.NewUint(uint64(amount)), executionFeeRate))
128}
129
130// CalculatePayoutExecutionFeeAmount returns the execution fee of a payout of
131// grossAmount to an order already paid paidGrossAmount (its claimedAmount plus
132// executionFeeAmount): fee(paidGrossAmount + grossAmount) - fee(paidGrossAmount),
133// with fee as in CalculateExecutionFeeAmount.
134//
135// The fee is charged on the order's cumulative gross output, so splitting it
136// over many payouts never rounds the fee away: after every payout the order's
137// lifetime fee equals fee(its lifetime gross output).
138// The result is at most ceil(grossAmount * executionFeeRate / BasisPointDenominator),
139// so the payout net of the fee is at least
140// CalculateMinNetAmountOut(grossAmount, executionFeeRate).
141// It returns ErrInvalidInput for a negative grossAmount or a rate outside
142// [0, MaxExecutionFeeRate].
143func CalculatePayoutExecutionFeeAmount(paidGrossAmount *u256.Uint, grossAmount int64, executionFeeRate int64) (int64, error) {
144 if grossAmount < 0 || !isValidExecutionFeeRate(executionFeeRate) {
145 return 0, ErrInvalidInput
146 }
147
148 if grossAmount == 0 || executionFeeRate == 0 {
149 return 0, nil
150 }
151
152 totalGrossAmount, overflow := u256.Zero().AddOverflow(paidGrossAmount, u256.NewUint(uint64(grossAmount)))
153 if overflow {
154 return 0, ErrOverflow
155 }
156
157 totalFeeAmount := calculateExecutionFeeAmountU256(totalGrossAmount, executionFeeRate)
158 paidFeeAmount := calculateExecutionFeeAmountU256(paidGrossAmount, executionFeeRate)
159
160 return toInt64(u256.Zero().Sub(totalFeeAmount, paidFeeAmount))
161}
162
163// CalculateMinNetAmountOut returns
164// grossAmount * (BasisPointDenominator - executionFeeRate) / BasisPointDenominator,
165// rounded down: the least an order paid grossAmount at executionFeeRate or
166// less receives after CalculatePayoutExecutionFeeAmount, whatever it was paid
167// before. A round checks its per-order output with it.
168// It returns ErrInvalidInput for a negative grossAmount or a rate outside
169// [0, MaxExecutionFeeRate].
170func CalculateMinNetAmountOut(grossAmount int64, executionFeeRate int64) (int64, error) {
171 if grossAmount < 0 || !isValidExecutionFeeRate(executionFeeRate) {
172 return 0, ErrInvalidInput
173 }
174
175 return toInt64(u256.MulDiv(
176 u256.NewUint(uint64(grossAmount)),
177 u256.NewUint(uint64(BasisPointDenominator-executionFeeRate)),
178 u256.NewUint(uint64(BasisPointDenominator)),
179 ))
180}
181
182// calculateExecutionFeeAmountU256 returns
183// floor(amount * executionFeeRate / BasisPointDenominator).
184// It is the single rounding rule of every execution fee.
185func calculateExecutionFeeAmountU256(amount *u256.Uint, executionFeeRate int64) *u256.Uint {
186 return u256.MulDiv(
187 amount,
188 u256.NewUint(uint64(executionFeeRate)),
189 u256.NewUint(uint64(BasisPointDenominator)),
190 )
191}
192
193// isValidExecutionFeeRate reports whether executionFeeRate is in
194// [0, MaxExecutionFeeRate].
195func isValidExecutionFeeRate(executionFeeRate int64) bool {
196 return executionFeeRate >= 0 && executionFeeRate <= MaxExecutionFeeRate
197}
198
199// CalculateOutputPerAmountX128 returns amountOut * 2^128 / amountIn,
200// rounded down: the output per unit of input of one round,
201// added to the group accumulator.
202func CalculateOutputPerAmountX128(amountOut int64, amountIn int64) (*u256.Uint, error) {
203 if amountIn <= 0 || amountOut < 0 {
204 return nil, ErrInvalidInput
205 }
206
207 return u256.MulDiv(u256.NewUint(uint64(amountOut)), q128, u256.NewUint(uint64(amountIn))), nil
208}
209
210// CalculateOwedAmount returns
211// amountPerExecution * (endAccumulatedX128 - debtX128) / 2^128, rounded down:
212// the output accrued since the last payout.
213func CalculateOwedAmount(amountPerExecution int64, endAccumulatedX128 *u256.Uint, debtX128 *u256.Uint) (*u256.Uint, error) {
214 if endAccumulatedX128.Lt(debtX128) {
215 return nil, ErrAccumulatorBackwards
216 }
217
218 delta := u256.Zero().Sub(endAccumulatedX128, debtX128)
219 if delta.IsZero() || amountPerExecution <= 0 {
220 return u256.Zero(), nil
221 }
222
223 return u256.MulDiv(delta, u256.NewUint(uint64(amountPerExecution)), q128), nil
224}
225
226// CalculatePayout returns the output accrued since the last payout,
227// amountPerExecution * (endAccumulatedX128 - debtX128) / 2^128 rounded down,
228// paid in one transfer: a GRC20 total supply is at most math.MaxInt64, so
229// the escrow, and any order's share of it, never exceeds one int64 transfer.
230// After paying it the order's debt is endAccumulatedX128.
231func CalculatePayout(amountPerExecution int64, endAccumulatedX128 *u256.Uint, debtX128 *u256.Uint) (int64, error) {
232 owedAmount, err := CalculateOwedAmount(amountPerExecution, endAccumulatedX128, debtX128)
233 if err != nil {
234 return 0, err
235 }
236
237 return toInt64(owedAmount)
238}
239
240// CalculateDebtX128AfterPayout returns the debt of an order after it is
241// paid payoutAmount: debtX128 + payoutAmount * 2^128 / amountPerExecution,
242// rounded up.
243// The debt moves only by the accumulator share that payoutAmount pays for,
244// so the remainder CalculatePayout rounds down stays owed and is paid once
245// it adds up to a whole unit.
246// Rounding up never moves the debt past the end accumulator that paid out
247// payoutAmount, so no payout is counted twice.
248func CalculateDebtX128AfterPayout(amountPerExecution int64, debtX128 *u256.Uint, payoutAmount int64) (*u256.Uint, error) {
249 if amountPerExecution <= 0 || payoutAmount < 0 {
250 return nil, ErrInvalidInput
251 }
252
253 settledX128 := u256.MulDivRoundingUp(u256.NewUint(uint64(payoutAmount)), q128, u256.NewUint(uint64(amountPerExecution)))
254
255 nextDebtX128, overflow := u256.Zero().AddOverflow(debtX128, settledX128)
256 if overflow {
257 return nil, ErrOverflow
258 }
259
260 return nextDebtX128, nil
261}
262
263// toInt64 converts a non-negative u256 to int64, or returns ErrOverflow.
264func toInt64(v *u256.Uint) (int64, error) {
265 if v.Gt(maxInt64U256) {
266 return 0, ErrOverflow
267 }
268
269 return int64(v.Uint64()), nil
270}