const BasisPointDenominator
BasisPointDenominator is 100% in basis points, the denominator of every rate in basis points: executionFeeRate, minExecutionGapRate, and maxPoolPriceDeviationRate.
Package dca holds the immutable building blocks of the GnoSwap DCA (dollar-cost averaging) order realm:
Package dca holds the immutable building blocks of the GnoSwap DCA (dollar-cost averaging) order realm:
Nothing here holds state. Storage, authorization, and token transfers live in gno.land/r/gnoswap/order/dca and its implementations under impl/.
Accounting: orders selling the same token for the same token at the same interval and slot offset share a group. A group's rounds run at the unix times t with t % interval == slotOffset, so the slot fixes the time of day (or day of week) of every round. Each round sells the sum of the active orders' per-round input and adds the whole output per unit of input, scaled by 2^128, to the group accumulator. An order accrues
1amountPerExecution * (acc(endRound) - debtX128) / 2^128
of gross output, rounded down, where debtX128 starts at the accumulator when the order joins. A payout moves debtX128 only by the accumulator share its gross output pays for, so the remainder below one unit stays owed and is paid once later rounds add it up to a whole unit. Each payout deducts the order's execution fee, at the rate it snapshotted when created, from that gross output (see CalculatePayoutExecutionFeeAmount).
BasisPointDenominator is 100% in basis points, the denominator of every rate in basis points: executionFeeRate, minExecutionGapRate, and maxPoolPriceDeviationRate.
ExecutionLogRoundCount is the number of consecutive rounds of an order one execution log covers. A tree entry costs about 640 bytes of storage whatever it holds, so covering three rounds keeps the deposit near 0.02 GNOT per round at 100 ugnot per byte.
MaxExecutionFeeRate is the largest execution fee rate: 1000 basis points (10%).
1const (
2 // OrderStatusActive: still selling input or holding unclaimed output.
3 OrderStatusActive OrderStatus = "ACTIVE"
4 // OrderStatusCompleted: every round executed and all output was paid.
5 OrderStatusCompleted OrderStatus = "COMPLETED"
6 // OrderStatusCancelled: cancelled by the owner; unsold input was refunded.
7 OrderStatusCancelled OrderStatus = "CANCELLED"
8) 1var (
2 // ErrInvalidInput is returned when an argument is out of its domain.
3 ErrInvalidInput = errors.New("invalid input")
4
5 // ErrOverflow is returned when a result does not fit in int64.
6 ErrOverflow = errors.New("int64 overflow")
7
8 // ErrAccumulatorBackwards is returned when the payout accumulator
9 // is below the order's debt.
10 ErrAccumulatorBackwards = errors.New("accumulator moved backwards")
11
12 // ErrInvalidCursor is returned when a schedule cursor cannot be parsed.
13 ErrInvalidCursor = errors.New("invalid cursor")
14
15 // ErrIntervalExists is returned when adding an interval already allowed.
16 ErrIntervalExists = errors.New("interval already allowed")
17
18 // ErrIntervalNotFound is returned when removing an interval not allowed.
19 ErrIntervalNotFound = errors.New("interval not allowed")
20)AllocateExecutionLogs stores the logs of the order's unreleased rounds, ExecutionLogRoundCount rounds per log, and returns how many were stored.
1func CalculateDebtX128AfterPayout(amountPerExecution int64, debtX128 *u256.Uint, payoutAmount int64) (*u256.Uint, error)CalculateDebtX128AfterPayout returns the debt of an order after it is paid payoutAmount: debtX128 + payoutAmount * 2^128 / amountPerExecution, rounded up. The debt moves only by the accumulator share that payoutAmount pays for, so the remainder CalculatePayout rounds down stays owed and is paid once it adds up to a whole unit. Rounding up never moves the debt past the end accumulator that paid out payoutAmount, so no payout is counted twice.
CalculateExecutionFeeAmount returns amount * executionFeeRate / BasisPointDenominator, rounded down, so the fee never exceeds the configured share. Config.SetExecutionFeeRate bounds the rate to [0, MaxExecutionFeeRate].
1func CalculateFirstSlotTimestamp(currentTimestamp int64, interval int64, slotOffset int64) (int64, error)CalculateFirstSlotTimestamp returns the first slot at or after currentTimestamp, that is the smallest t >= currentTimestamp with t % interval == slotOffset. interval must be positive and slotOffset in [0, interval).
CalculateMinExecutionGap returns minExecutionGapRate (basis points) of interval in seconds, rounded up: the minimum time between two executions of a group.
CalculateMinNetAmountOut returns grossAmount * (BasisPointDenominator - executionFeeRate) / BasisPointDenominator, rounded down: the least an order paid grossAmount at executionFeeRate or less receives after CalculatePayoutExecutionFeeAmount, whatever it was paid before. A round checks its per-order output with it. It returns ErrInvalidInput for a negative grossAmount or a rate outside [0, MaxExecutionFeeRate].
1func CalculateNextExecutionTimestamp(scheduledTimestamp int64, currentTimestamp int64, interval int64) (int64, error)CalculateNextExecutionTimestamp returns the first slot strictly after currentTimestamp. Slots keep a fixed cadence from scheduledTimestamp, so a late execution skips missed slots instead of running them back to back. interval must be positive and the timestamps non-negative; a next slot above math.MaxInt64 returns ErrOverflow.
1func CalculateNextExecutionTimestampWithGap(scheduledTimestamp int64, currentTimestamp int64, interval int64, minExecutionGap int64) (int64, error)CalculateNextExecutionTimestampWithGap returns the first slot after currentTimestamp that is also at least minExecutionGap seconds after currentTimestamp. Like CalculateNextExecutionTimestamp, it keeps the cadence anchored at scheduledTimestamp, skipping slots that fall inside the gap. minExecutionGap must be non-negative; a gap reaching past math.MaxInt64 returns ErrOverflow.
CalculateOutputPerAmountX128 returns amountOut * 2^128 / amountIn, rounded down: the output per unit of input of one round, added to the group accumulator.
1func CalculateOwedAmount(amountPerExecution int64, endAccumulatedX128 *u256.Uint, debtX128 *u256.Uint) (*u256.Uint, error)CalculateOwedAmount returns amountPerExecution * (endAccumulatedX128 - debtX128) / 2^128, rounded down: the output accrued since the last payout.
1func CalculatePayout(amountPerExecution int64, endAccumulatedX128 *u256.Uint, debtX128 *u256.Uint) (int64, error)CalculatePayout returns the output accrued since the last payout, amountPerExecution * (endAccumulatedX128 - debtX128) / 2^128 rounded down, paid in one transfer: a GRC20 total supply is at most math.MaxInt64, so the escrow, and any order's share of it, never exceeds one int64 transfer. After paying it the order's debt is endAccumulatedX128.
1func CalculatePayoutExecutionFeeAmount(paidGrossAmount *u256.Uint, grossAmount int64, executionFeeRate int64) (int64, error)CalculatePayoutExecutionFeeAmount returns the execution fee of a payout of grossAmount to an order already paid paidGrossAmount (its claimedAmount plus executionFeeAmount): fee(paidGrossAmount + grossAmount) - fee(paidGrossAmount), with fee as in CalculateExecutionFeeAmount.
The fee is charged on the order's cumulative gross output, so splitting it over many payouts never rounds the fee away: after every payout the order's lifetime fee equals fee(its lifetime gross output). The result is at most ceil(grossAmount * executionFeeRate / BasisPointDenominator), so the payout net of the fee is at least CalculateMinNetAmountOut(grossAmount, executionFeeRate). It returns ErrInvalidInput for a negative grossAmount or a rate outside [0, MaxExecutionFeeRate].
ExecutionLogKey sorts an order's execution logs by round under ExecutionLogPrefix.
ExecutionLogPrefix is the common prefix of an order's execution log keys.
FormatScheduleCursor renders a schedule entry as "<nextExecutionTimestamp>|<groupID>".
1func GroupOrderAmountKey(groupID string, executionFeeRate int64, amountPerExecution int64, orderID uint64) stringGroupOrderAmountKey sorts a group's orders by executionFeeRate, then amountPerExecution, then ID, under GroupOrderFeeRatePrefix. amountPerExecution is positive, so its first byte is below 0x80 and PrefixEnd of GroupOrderFeeRatePrefix still bounds the rate's keys.
GroupOrderAmountKeyAmount extracts amountPerExecution from a GroupOrderAmountKey of groupID.
GroupOrderAmountKeyFeeRate extracts executionFeeRate from a GroupOrderAmountKey of groupID.
GroupOrderFeeRatePrefix is the common prefix of the GroupOrderAmountKeys of a group's orders with executionFeeRate, under GroupOrderPrefix. executionFeeRate is in [0, MaxExecutionFeeRate], so its first byte is 0 and PrefixEnd of GroupOrderPrefix still bounds every rate's keys.
GroupOrderKey sorts a group's orders by ID under GroupOrderPrefix.
GroupOrderPrefix is the common prefix of a group's order index keys. Token paths contain no ':', so one group's prefix never starts another's.
1func MakeGroupID(inputToken string, outputToken string, interval int64, slotOffset int64) stringMakeGroupID builds the group key "inputToken:outputToken:interval:slotOffset".
OrderKey encodes an order ID so B+tree order matches numeric order.
OwnerOrderKey sorts an owner's orders by ID under OwnerOrderPrefix.
OwnerOrderPrefix is the common prefix of an owner's index keys.
PairKey builds the key of a pair direction, "inputToken:outputToken". Token paths contain no ':', so the key is unambiguous.
ParseScheduleCursor converts a "<nextExecutionTimestamp>|<groupID>" cursor back to its ScheduleKey. An empty cursor yields an empty key, i.e. the start of the index. A malformed cursor returns ErrInvalidCursor.
PrefixEnd is an exclusive upper bound for prefix + 8-byte encoded ID keys. Nine 0xff bytes sort after every 8-byte suffix.
Q128 returns a copy of 2^128, the accumulator scale.
ReleaseAllExecutionLogs removes every log of the order, executed or not, and returns how many were released.
1func ReleaseExecutionLogs(executionLogs *bptree.BPTree, order *Order, executedRound uint64) int64ReleaseExecutionLogs removes the order's logs whose rounds all executed by executedRound, the group round, and returns how many were released. A log with a round still to run stays.
RoundKey encodes a round so B+tree order matches numeric order.
ScheduleKey orders groups by next execution timestamp, then group ID.
ScheduleKeyTimestamp extracts the next execution timestamp from a ScheduleKey.
1func NewConfig(minAmountPerExecution, maxExecutionCount int64, allowedIntervals []int64) *ConfigNewConfig returns a config that allows allowedIntervals, which must be ascending. The slice is copied. Fees and the execution gap start disabled. Each interval starts with a single slot, offset 0; see SetSlotStep.
ExecutionLogs returns up to count of the order's unreleased logs, oldest first.
1func NewGroup(id string, inputToken string, outputToken string, interval int64, slotOffset int64, nextExecutionTimestamp int64) *GroupNewGroup creates an empty group whose first round is due at nextExecutionTimestamp.
NewOrder creates an order that joins group at its current round. Store its execution logs with AllocateExecutionLogs. Its debt starts at the group's current accumulated output per amount, so it never shares output from earlier rounds. executionFeeRate is fixed for the order's lifetime. It returns ErrInvalidInput if executionCount is not positive or executionFeeRate is outside [0, MaxExecutionFeeRate], and ErrOverflow if the end round would pass the uint64 limit.
NewPairPriceLimit returns a limit of minOutputPerInputX128, set at updatedAt.
1type Config struct {
2 minAmountPerExecution int64 // minimum input per execution
3 maxExecutionCount int64 // maximum executions per order
4
5 // allowedIntervals lists the intervals new orders may use, ascending.
6 // Removing one only blocks new orders; existing groups keep running.
7 allowedIntervals []int64
8
9 // Execution guard.
10 minExecutionGapRate int64 // min gap between a group's executions, bps of interval
11 // slotSteps[i] is the spacing of the slot offsets
12 // allowed for allowedIntervals[i]; it divides the interval.
13 // A step equal to the interval allows offset 0 only.
14 slotSteps []int64
15
16 maxClaimBatchSize int64 // most orders one ClaimGroupOrders call examines
17
18 // maxPoolPriceDeviationRate is how far, in basis points of price, a pool's
19 // price may sit on the favorable side of its swap price limit and still be
20 // quoted; 0 disables the check. It bounds the ticks a quote or swap walks
21 // when a pool's price is far from the oracle-derived limit.
22 maxPoolPriceDeviationRate int64
23
24 // maxPairPriceLimitAge is how long, in seconds, a pair price limit stays
25 // usable after it was set; a round or quote under an older limit finds
26 // no eligible pool. 0 is invalid and leaves no pool eligible.
27 maxPairPriceLimitAge int64
28
29 // executionFeeRate is the share of an order's gross output,
30 // in basis points, sent to the protocol fee realm.
31 // Each new order snapshots it; changing it leaves existing orders as is.
32 executionFeeRate int64
33}Config holds governance-controlled DCA parameters.
AddAllowedInterval allows interval, keeping the list ascending. The interval starts with a single slot, offset 0; see SetSlotStep.
AllowedIntervals returns a copy of the allowed intervals, ascending.
Clone returns a deep copy of the config.
IsAllowedInterval reports whether new orders may use interval.
IsAllowedSlot reports whether new orders may use slotOffset at interval: a multiple of the interval's slot step in [0, interval).
RemoveAllowedInterval disallows interval for new orders, dropping its slot step with it.
SetExecutionFeeRate sets the execution fee rate in basis points. It returns ErrInvalidInput outside [0, MaxExecutionFeeRate].
SetSlotStep sets the spacing of the slot offsets allowed for interval. It returns ErrInvalidInput if the interval is not allowed, or if step is not a positive divisor of the interval.
SlotStep returns the spacing of the slot offsets allowed for interval, or 0 if the interval is not allowed.
ExecutionLog is an order's record of up to ExecutionLogRoundCount consecutive rounds, [firstRound, lastRound], and the input the order sells in each. The rounds' swap results are in the DCAGroupExecuted events, and accounting uses the group accumulator.
AllocateExecutionLogs stores an order's logs in the realm's executionLogs tree, keyed by ExecutionLogKey(orderID, firstRound), so the order owner pays their storage deposit up front; ExecuteGroup writes none. Once every round of a log executed, anyone may release it through Claim or ClaimGroupOrders, and a finished order releases all of its logs; the freed deposit is refunded to the transaction signer.
The tree stores only lastRound, a primitive kept inside the B+tree leaf; firstRound comes from the key and amountIn from the order.
RoundCount returns the number of rounds the log covers.
1type Group struct {
2 id string
3 inputToken string
4 outputToken string
5 interval int64
6 slotOffset int64 // seconds after each interval boundary of the unix epoch
7
8 round uint64 // number of executed rounds
9 orderAmount int64 // input sold in the next round, sum of active amountPerExecution
10 accumulatedOutputPerAmountX128 *u256.Uint // cumulative output per unit of input, Q128
11 nextExecutionTimestamp int64 // earliest unix time of the next execution
12
13 activeOrderCount int64 // number of unfinalized orders
14
15 roundMarks *bptree.BPTree // EncodeUint64(round) -> *RoundMark
16}Group aggregates the orders selling inputToken for outputToken at the same interval and slot offset. Its rounds run at the unix times t with t % interval == slotOffset. A round sells the sum of their amountPerExecution (orderAmount) in one pool swap, on the pool chosen at execution time, and adds the gross output per unit of input to accumulatedOutputPerAmountX128; each order's execution fee is deducted when the order is paid out.
Clone returns a deep copy of the group, including its round marks, so callers can read it without aliasing stored state. Its cost grows with the number of round marks; getters use CloneWithoutRoundMarks instead.
CloneWithoutRoundMarks returns a copy of the group's fields with an empty round mark tree, at a cost independent of the number of round marks. Like Clone, it shares no state with g; read the marks through RoundMarks.
GetOrCreateRoundMark returns the mark of a round, creating it if missing.
GetRoundMark returns the mark of a round, or nil when no order ends there.
RoundMarks returns a read-only view of the round marks keyed by RoundKey. Each mark read from the view is a copy, so the view cannot reach stored state.
IDCAOrder is the implementation interface behind the order/dca proxy.
1type IDCAOrderAdmin interface {
2 // SetExecutionFeeRate sets the share of an order's gross output,
3 // in basis points, sent to the protocol fee realm.
4 // Orders snapshot it at creation; existing orders keep their rate.
5 SetExecutionFeeRate(_ int, rlm realm, executionFeeRate int64)
6
7 // AddAllowedInterval and RemoveAllowedInterval manage the intervals new
8 // orders may use; existing orders keep their interval.
9 AddAllowedInterval(_ int, rlm realm, interval int64)
10 RemoveAllowedInterval(_ int, rlm realm, interval int64)
11 // SetOrderLimits sets the minimum input per execution
12 // and the maximum executions per order.
13 SetOrderLimits(_ int, rlm realm, minAmountPerExecution int64, maxExecutionCount int64)
14
15 // SetMinExecutionGapRate sets the minimum gap between a group's
16 // executions, in basis points of its interval.
17 SetMinExecutionGapRate(_ int, rlm realm, minExecutionGapRate int64)
18
19 // SetMaxClaimBatchSize caps the orders one ClaimGroupOrders call examines.
20 SetMaxClaimBatchSize(_ int, rlm realm, maxClaimBatchSize int64)
21
22 // SetMaxPoolPriceDeviationRate sets how far, in basis points of price, a
23 // pool's price may sit on the favorable side of its swap price limit and
24 // still be quoted; 0 disables the check.
25 SetMaxPoolPriceDeviationRate(_ int, rlm realm, maxPoolPriceDeviationRate int64)
26
27 // SetMaxPairPriceLimitAge sets how long, in seconds, a pair price limit
28 // stays usable after it was set.
29 SetMaxPairPriceLimitAge(_ int, rlm realm, maxPairPriceLimitAge int64)
30
31 // SetSlotStep sets the spacing of the slot offsets
32 // new orders may use at interval.
33 SetSlotStep(_ int, rlm realm, interval int64, slotStep int64)
34
35 // SetTokenMinAmountPerExecution sets the minimum input per execution of
36 // orders selling tokenPath, on top of the global minimum; 0 removes it.
37 // Admin, governance, or the manager role assigned to the selector.
38 SetTokenMinAmountPerExecution(_ int, rlm realm, tokenPath string, minAmountPerExecution int64)
39
40 // SetPairPriceLimit sets the minimum pool output per unit of input,
41 // in Q128, of rounds selling inputToken for outputToken; "0" removes it.
42 // A pair direction without a limit cannot be quoted, executed,
43 // or receive new orders.
44 // Admin, governance, or the manager role assigned to the selector.
45 SetPairPriceLimit(_ int, rlm realm, inputToken string, outputToken string, minOutputPerInputX128 string)
46}IDCAOrderAdmin covers admin or governance operations. Every rate is in basis points of BasisPointDenominator.
1type IDCAOrderExecutor interface {
2 // ExecuteGroup sells the group's per-round input with a pool swap,
3 // on the pool with the best quote, and credits the output to the orders;
4 // each order's execution fee is deducted when it is paid out.
5 // amountOutMin (0 disables it) is the pool output floor
6 // quoted for expectedAmountIn.
7 // If the group orderAmount differs from expectedAmountIn,
8 // the round reverts so the keeper can quote again.
9 // Passing 0 for both runs the round without a floor.
10 // Every order of the round must be credited at least
11 // max(1, minOrderAmountOut) of output after its own execution fee
12 // rate, or the round reverts.
13 ExecuteGroup(
14 _ int,
15 rlm realm,
16 groupID string,
17 expectedAmountIn int64,
18 amountOutMin int64,
19 minOrderAmountOut int64,
20 ) (executedAmountIn int64, executedAmountOut int64)
21
22 // ClaimGroupOrders pays accrued output to the owners of up to
23 // maxOrderCount orders of a group, after startAfterOrderID in ID order.
24 // It returns the number of orders paid or completed,
25 // and the cursor for the next call (0 when the group is done).
26 ClaimGroupOrders(_ int, rlm realm, groupID string, startAfterOrderID uint64, maxOrderCount int) (claimedOrderCount int, nextCursor uint64)
27
28 // ForceCancelOrder closes an order that blocks its group's rounds,
29 // as CancelOrder does for its owner: accrued output and unsold input
30 // go to the owner. The implementation checks on-chain that the order
31 // blocks its group and rejects any other. Keeper role only.
32 ForceCancelOrder(_ int, rlm realm, orderID uint64) (refundedAmount int64, claimedAmount int64)
33
34 // CollectPendingExecutionFee forwards the execution fee pending for
35 // tokenPath to the protocol fee realm. Anyone may call it.
36 CollectPendingExecutionFee(_ int, rlm realm, tokenPath string) (forwardedAmount int64, pendingAmount int64)
37}IDCAOrderExecutor covers keeper-authorized execution and cancellation, and public batch-claim entry points.
1type IDCAOrderGetter interface {
2 GetConfig() *Config
3 GetNextOrderID() uint64
4
5 ExistsOrder(orderID uint64) bool
6 GetOrder(orderID uint64) (*Order, error)
7 GetOrders() *rotree.ReadOnlyTree
8 GetOrdersByOwner() *rotree.ReadOnlyTree
9 GetOrderIDsByOwner(owner address, startAfterID uint64, count int) []uint64
10 GetClaimableAmount(orderID uint64) int64
11 GetOrderExecutionLogs(orderID uint64, count int) ([]*ExecutionLog, error)
12 GetExecutionLogs() *rotree.ReadOnlyTree
13
14 ExistsGroup(groupID string) bool
15 GetGroup(groupID string) (*Group, error)
16 GetGroups() *rotree.ReadOnlyTree
17 GetGroupRoundMarks(groupID string) *rotree.ReadOnlyTree
18 GetOrdersByGroup() *rotree.ReadOnlyTree
19 GetOrderAmountsByGroup() *rotree.ReadOnlyTree
20 GetOrderIDsByGroup(groupID string, startAfterID uint64, count int) []uint64
21 GetScheduledGroups() *rotree.ReadOnlyTree
22 GetExecutableGroups(cursor string, count int) ([]*Group, error)
23 GetExecutionQuote(groupID string) string
24
25 GetTokenMinAmountPerExecution(tokenPath string) int64
26 GetMinAmountPerExecution(tokenPath string) int64
27 GetTokenMinAmountsPerExecution() *rotree.ReadOnlyTree
28 GetPairPriceLimit(inputToken string, outputToken string) (*PairPriceLimit, bool)
29 GetPairPriceLimits() *rotree.ReadOnlyTree
30
31 GetPendingExecutionFeeAmount(tokenPath string) int64
32 GetPendingExecutionFees() *rotree.ReadOnlyTree
33}IDCAOrderGetter covers read-only queries. Returned orders, groups, and configs are copies of the stored state. Store trees are exposed as read-only views keyed as in the store layout; entries that are pointers are copied on every read.
1type IDCAOrderManager interface {
2 // CreateOrder escrows amountPerExecution*executionCount of inputToken,
3 // and joins the (inputToken, outputToken, interval, slotOffset) group.
4 CreateOrder(
5 _ int,
6 rlm realm,
7 inputToken string,
8 outputToken string,
9 interval int64,
10 slotOffset int64,
11 amountPerExecution int64,
12 executionCount int64,
13 ) uint64
14
15 // CancelOrder pays accrued output, refunds unsold input,
16 // and closes the order. Owner only.
17 CancelOrder(_ int, rlm realm, orderID uint64) (refundedAmount int64, claimedAmount int64)
18
19 // Claim pays accrued output to the order owner. Anyone may call it.
20 Claim(_ int, rlm realm, orderID uint64) (claimedAmount int64)
21}IDCAOrderManager covers owner-facing order operations.
1type IDCAOrderStore interface {
2 HasOrders() bool
3 GetOrders() *bptree.BPTree
4 SetOrders(_ int, rlm realm, orders *bptree.BPTree) error
5
6 HasOrdersByOwner() bool
7 GetOrdersByOwner() *bptree.BPTree
8 SetOrdersByOwner(_ int, rlm realm, ordersByOwner *bptree.BPTree) error
9
10 HasGroups() bool
11 GetGroups() *bptree.BPTree
12 SetGroups(_ int, rlm realm, groups *bptree.BPTree) error
13
14 HasScheduledGroups() bool
15 GetScheduledGroups() *bptree.BPTree
16 SetScheduledGroups(_ int, rlm realm, groups *bptree.BPTree) error
17
18 HasNextOrderID() bool
19 GetNextOrderID() uint64
20 SetNextOrderID(_ int, rlm realm, id uint64) error
21
22 HasConfig() bool
23 GetConfig() *Config
24 SetConfig(_ int, rlm realm, config *Config) error
25
26 IsExecuting() bool
27 SetExecuting(_ int, rlm realm, executing bool) error
28
29 HasOrdersByGroup() bool
30 GetOrdersByGroup() *bptree.BPTree
31 SetOrdersByGroup(_ int, rlm realm, ordersByGroup *bptree.BPTree) error
32
33 HasPendingExecutionFees() bool
34 GetPendingExecutionFees() *bptree.BPTree
35 SetPendingExecutionFees(_ int, rlm realm, pendingExecutionFees *bptree.BPTree) error
36
37 HasExecutionLogs() bool
38 GetExecutionLogs() *bptree.BPTree
39 SetExecutionLogs(_ int, rlm realm, executionLogs *bptree.BPTree) error
40
41 HasOrderAmountsByGroup() bool
42 GetOrderAmountsByGroup() *bptree.BPTree
43 SetOrderAmountsByGroup(_ int, rlm realm, orderAmountsByGroup *bptree.BPTree) error
44
45 HasTokenMinAmountsPerExecution() bool
46 GetTokenMinAmountsPerExecution() *bptree.BPTree
47 SetTokenMinAmountsPerExecution(_ int, rlm realm, tokenMinAmounts *bptree.BPTree) error
48
49 HasPairPriceLimits() bool
50 GetPairPriceLimits() *bptree.BPTree
51 SetPairPriceLimits(_ int, rlm realm, pairPriceLimits *bptree.BPTree) error
52}IDCAOrderStore is the persistent storage shared by all versions.
1type Order struct {
2 id uint64
3 owner address
4
5 groupID string // tokens and interval are on the group
6
7 amountPerExecution int64
8 startRound uint64
9 endRound uint64
10
11 // executionFeeRate is the share of the order's gross output,
12 // in basis points, charged when it is paid out.
13 executionFeeRate int64
14
15 debtX128 *u256.Uint // group accumulator already paid out, see CalculateDebtX128AfterPayout
16 claimedAmount *u256.Uint // lifetime output paid to the owner, net of the execution fee; 256-bit so it never overflows
17
18 // executionFeeAmount is the lifetime execution fee charged on payouts;
19 // claimedAmount + executionFeeAmount is the gross output paid out.
20 executionFeeAmount *u256.Uint
21
22 // Last round whose execution log was released;
23 // the logs of rounds (releasedRound, endRound] are stored.
24 releasedRound uint64
25
26 createdTimestamp int64
27 createdHeight int64
28}Order is one user's active DCA order. It sells amountPerExecution of the group's input token in each group round of (startRound, endRound]. Accrued gross output is amountPerExecution * (acc(min(round, endRound)) - debtX128) / 2^128; each payout deducts the order's execution fee from it (see CalculatePayoutExecutionFeeAmount). The execution fee rate is snapshotted at creation for the order's lifetime. Only the payout state (debtX128, claimedAmount, executionFeeAmount) and the released execution logs change after creation.
Clone returns a deep copy of the order, so callers can read it without aliasing stored state.
ExecutionLogCount returns the number of the order's unreleased logs. Logs start at fixed offsets from the start round, so no lookup is needed.
PaidGrossAmount returns the gross output paid out so far: claimedAmount plus executionFeeAmount.
OrderStatus is the outcome reported in order events. Stored orders are always active: a completed or cancelled order is deleted, and its final state is kept in the event.
PairPriceLimit is the minimum pool output a round of one pair direction accepts per unit of input, set by the pool manager from an oracle price.
minOutputPerInputX128 is raw outputToken units, before the execution fee, per raw inputToken unit, in Q128 fixed point. Rounds use it as the pool swap price limit, so it bounds both the price and the ticks a quote or swap may cross. updatedAt is the unix time it was set; a limit older than Config.MaxPairPriceLimitAge leaves no pool eligible.
Clone returns a copy of the limit.
MinOutputPerInputX128 returns a copy of the limit.
Update replaces the limit and its update time in place.
UpdatedAt returns the unix time the limit was set.
RoundMark tracks the orders whose last round is the mark's round.
When the round executes, orderAmount leaves the group orderAmount, and accumulatedOutputPerAmountX128 snapshots the group accumulator, so finished orders are paid without per-round history. The mark is removed once orderCount, the number of unfinalized orders ending at the round, reaches zero.
Clone returns a deep copy of the mark.
SnapshotAccumulatedOutputPerAmountX128 records the group accumulator right after the round executes. It writes into the existing slot, so no new object is stored.