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

Playground

config.gno

package dca

// BasisPointDenominator is 100% in basis points, the denominator of every
// rate in basis points: executionFeeRate, minExecutionGapRate, and
// maxPoolPriceDeviationRate.
const BasisPointDenominator int64 = 10_000

// MaxExecutionFeeRate is the largest execution fee rate: 1000 basis points
// (10%).
const MaxExecutionFeeRate int64 = 1_000

// Config holds governance-controlled DCA parameters.
type Config struct {
	minAmountPerExecution int64 // minimum input per execution
	maxExecutionCount     int64 // maximum executions per order

	// allowedIntervals lists the intervals new orders may use, ascending.
	// Removing one only blocks new orders; existing groups keep running.
	allowedIntervals []int64

	// Execution guard.
	minExecutionGapRate int64 // min gap between a group's executions, bps of interval
	// slotSteps[i] is the spacing of the slot offsets
	// allowed for allowedIntervals[i]; it divides the interval.
	// A step equal to the interval allows offset 0 only.
	slotSteps []int64

	maxClaimBatchSize int64 // most orders one ClaimGroupOrders call examines

	// maxPoolPriceDeviationRate is how far, in basis points of price, a pool's
	// price may sit on the favorable side of its swap price limit and still be
	// quoted; 0 disables the check. It bounds the ticks a quote or swap walks
	// when a pool's price is far from the oracle-derived limit.
	maxPoolPriceDeviationRate int64

	// maxPairPriceLimitAge is how long, in seconds, a pair price limit stays
	// usable after it was set; a round or quote under an older limit finds
	// no eligible pool. 0 is invalid and leaves no pool eligible.
	maxPairPriceLimitAge int64

	// executionFeeRate is the share of an order's gross output,
	// in basis points, sent to the protocol fee realm.
	// Each new order snapshots it; changing it leaves existing orders as is.
	executionFeeRate int64
}

// NewConfig 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.
func NewConfig(minAmountPerExecution, maxExecutionCount int64, allowedIntervals []int64) *Config {
	return &Config{
		minAmountPerExecution: minAmountPerExecution,
		maxExecutionCount:     maxExecutionCount,
		allowedIntervals:      cloneInt64s(allowedIntervals),
		minExecutionGapRate:   0,
		slotSteps:             cloneInt64s(allowedIntervals),
		maxClaimBatchSize:     0,
		executionFeeRate:      0,

		maxPoolPriceDeviationRate: 0,
		maxPairPriceLimitAge:      0,
	}
}

// Clone returns a deep copy of the config.
func (c *Config) Clone() *Config {
	return &Config{
		minAmountPerExecution: c.minAmountPerExecution,
		maxExecutionCount:     c.maxExecutionCount,
		allowedIntervals:      cloneInt64s(c.allowedIntervals),
		minExecutionGapRate:   c.minExecutionGapRate,
		slotSteps:             cloneInt64s(c.slotSteps),
		maxClaimBatchSize:     c.maxClaimBatchSize,
		executionFeeRate:      c.executionFeeRate,

		maxPoolPriceDeviationRate: c.maxPoolPriceDeviationRate,
		maxPairPriceLimitAge:      c.maxPairPriceLimitAge,
	}
}

func (c *Config) MinAmountPerExecution() int64     { return c.minAmountPerExecution }
func (c *Config) SetMinAmountPerExecution(v int64) { c.minAmountPerExecution = v }

func (c *Config) MaxExecutionCount() int64     { return c.maxExecutionCount }
func (c *Config) SetMaxExecutionCount(v int64) { c.maxExecutionCount = v }

func (c *Config) MinExecutionGapRate() int64     { return c.minExecutionGapRate }
func (c *Config) SetMinExecutionGapRate(v int64) { c.minExecutionGapRate = v }

func (c *Config) MaxClaimBatchSize() int64     { return c.maxClaimBatchSize }
func (c *Config) SetMaxClaimBatchSize(v int64) { c.maxClaimBatchSize = v }

func (c *Config) MaxPoolPriceDeviationRate() int64     { return c.maxPoolPriceDeviationRate }
func (c *Config) SetMaxPoolPriceDeviationRate(v int64) { c.maxPoolPriceDeviationRate = v }

func (c *Config) MaxPairPriceLimitAge() int64     { return c.maxPairPriceLimitAge }
func (c *Config) SetMaxPairPriceLimitAge(v int64) { c.maxPairPriceLimitAge = v }

func (c *Config) ExecutionFeeRate() int64 { return c.executionFeeRate }

// SetExecutionFeeRate sets the execution fee rate in basis points.
// It returns ErrInvalidInput outside [0, MaxExecutionFeeRate].
func (c *Config) SetExecutionFeeRate(v int64) error {
	if !isValidExecutionFeeRate(v) {
		return ErrInvalidInput
	}

	c.executionFeeRate = v

	return nil
}

// AllowedIntervals returns a copy of the allowed intervals, ascending.
func (c *Config) AllowedIntervals() []int64 {
	return cloneInt64s(c.allowedIntervals)
}

// IsAllowedInterval reports whether new orders may use interval.
func (c *Config) IsAllowedInterval(interval int64) bool {
	return c.intervalIndex(interval) >= 0
}

// AddAllowedInterval allows interval, keeping the list ascending.
// The interval starts with a single slot, offset 0; see SetSlotStep.
func (c *Config) AddAllowedInterval(interval int64) error {
	if c.IsAllowedInterval(interval) {
		return ErrIntervalExists
	}

	i := 0
	for i < len(c.allowedIntervals) && c.allowedIntervals[i] < interval {
		i++
	}

	c.allowedIntervals = insertInt64(c.allowedIntervals, i, interval)
	c.slotSteps = insertInt64(c.slotSteps, i, interval)

	return nil
}

// RemoveAllowedInterval disallows interval for new orders,
// dropping its slot step with it.
func (c *Config) RemoveAllowedInterval(interval int64) error {
	i := c.intervalIndex(interval)
	if i < 0 {
		return ErrIntervalNotFound
	}

	c.allowedIntervals = removeInt64(c.allowedIntervals, i)
	c.slotSteps = removeInt64(c.slotSteps, i)

	return nil
}

// SlotStep returns the spacing of the slot offsets allowed for interval,
// or 0 if the interval is not allowed.
func (c *Config) SlotStep(interval int64) int64 {
	i := c.intervalIndex(interval)
	if i < 0 {
		return 0
	}

	return c.slotSteps[i]
}

// 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.
func (c *Config) SetSlotStep(interval int64, step int64) error {
	i := c.intervalIndex(interval)
	if i < 0 || step <= 0 || interval%step != 0 {
		return ErrInvalidInput
	}

	c.slotSteps[i] = step

	return nil
}

// IsAllowedSlot reports whether new orders may use slotOffset at interval:
// a multiple of the interval's slot step in [0, interval).
func (c *Config) IsAllowedSlot(interval int64, slotOffset int64) bool {
	step := c.SlotStep(interval)
	if step <= 0 {
		return false
	}

	return slotOffset >= 0 && slotOffset < interval && slotOffset%step == 0
}

func (c *Config) intervalIndex(interval int64) int {
	for i, v := range c.allowedIntervals {
		if v == interval {
			return i
		}
	}

	return -1
}

// insertInt64 returns a copy of values with v inserted at index i.
func insertInt64(values []int64, i int, v int64) []int64 {
	out := make([]int64, 0, len(values)+1)
	out = append(out, values[:i]...)
	out = append(out, v)

	return append(out, values[i:]...)
}

// removeInt64 returns a copy of values without the element at index i.
func removeInt64(values []int64, i int) []int64 {
	out := make([]int64, 0, len(values)-1)
	out = append(out, values[:i]...)

	return append(out, values[i+1:]...)
}

func cloneInt64s(values []int64) []int64 {
	out := make([]int64, len(values))
	copy(out, values)

	return out
}

doc.gno

// Package dca holds the immutable building blocks of the GnoSwap DCA
// (dollar-cost averaging) order realm:
//
//   - types.gno: interfaces between the proxy and its implementations
//   - order.gno, group.gno, config.gno: domain types stored by the realm
//   - math.gno: scheduling, accumulator, fee, and payout math
//   - keys.gno: B+tree key encodings
//
// 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
//
//	amountPerExecution * (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).
package dca

errors.gno

package dca

import (
	"errors"
)

var (
	// ErrInvalidInput is returned when an argument is out of its domain.
	ErrInvalidInput = errors.New("invalid input")

	// ErrOverflow is returned when a result does not fit in int64.
	ErrOverflow = errors.New("int64 overflow")

	// ErrAccumulatorBackwards is returned when the payout accumulator
	// is below the order's debt.
	ErrAccumulatorBackwards = errors.New("accumulator moved backwards")

	// ErrInvalidCursor is returned when a schedule cursor cannot be parsed.
	ErrInvalidCursor = errors.New("invalid cursor")

	// ErrIntervalExists is returned when adding an interval already allowed.
	ErrIntervalExists = errors.New("interval already allowed")

	// ErrIntervalNotFound is returned when removing an interval not allowed.
	ErrIntervalNotFound = errors.New("interval not allowed")
)

execution_log.gno

package dca

import (
	"gno.land/p/gnoswap/gnsmath/v1"
	bptree "gno.land/p/nt/bptree/v0"

	"gno.land/p/gnoswap/utils/v1"
)

// 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.
const ExecutionLogRoundCount uint64 = 3

// 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.
type ExecutionLog struct {
	firstRound uint64
	lastRound  uint64
	amountIn   int64 // input the order sells in each round, its amountPerExecution
}

func (l *ExecutionLog) FirstRound() uint64 { return l.firstRound }
func (l *ExecutionLog) LastRound() uint64  { return l.lastRound }
func (l *ExecutionLog) AmountIn() int64    { return l.amountIn }

// RoundCount returns the number of rounds the log covers.
func (l *ExecutionLog) RoundCount() uint64 { return l.lastRound - l.firstRound + 1 }

// AllocateExecutionLogs stores the logs of the order's unreleased rounds,
// ExecutionLogRoundCount rounds per log, and returns how many were stored.
func AllocateExecutionLogs(executionLogs *bptree.BPTree, order *Order) int64 {
	allocatedCount := int64(0)

	for firstRound := gnsmath.SafeAddUint64(order.releasedRound, 1); firstRound <= order.endRound; {
		lastRound := lastRoundOfLog(firstRound, order.endRound)
		executionLogs.Set(ExecutionLogKey(order.id, firstRound), lastRound)

		allocatedCount++

		if lastRound == order.endRound {
			break
		}

		firstRound = gnsmath.SafeAddUint64(lastRound, 1)
	}

	return allocatedCount
}

// ReleaseExecutionLogs 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.
func ReleaseExecutionLogs(executionLogs *bptree.BPTree, order *Order, executedRound uint64) int64 {
	if executedRound > order.endRound {
		executedRound = order.endRound
	}

	releasedCount := int64(0)

	for order.releasedRound < order.endRound {
		firstRound := gnsmath.SafeAddUint64(order.releasedRound, 1)

		lastRound := lastRoundOfLog(firstRound, order.endRound)
		if lastRound > executedRound {
			break
		}

		executionLogs.Remove(ExecutionLogKey(order.id, firstRound))
		order.setReleasedRound(lastRound)

		releasedCount++
	}

	return releasedCount
}

// ReleaseAllExecutionLogs removes every log of the order, executed or not,
// and returns how many were released.
func ReleaseAllExecutionLogs(executionLogs *bptree.BPTree, order *Order) int64 {
	return ReleaseExecutionLogs(executionLogs, order, order.endRound)
}

// ExecutionLogs returns up to count of the order's unreleased logs,
// oldest first.
func ExecutionLogs(executionLogs *bptree.BPTree, order *Order, count int) []*ExecutionLog {
	logs := []*ExecutionLog{}
	if count <= 0 {
		return logs
	}

	prefix := ExecutionLogPrefix(order.id)
	executionLogs.Iterate(prefix, PrefixEnd(prefix), func(key string, value any) bool {
		logs = append(logs, &ExecutionLog{
			firstRound: utils.DecodeUint64(key[len(prefix):]),
			lastRound:  value.(uint64),
			amountIn:   order.amountPerExecution,
		})

		return len(logs) >= count
	})

	return logs
}

// lastRoundOfLog returns the last round of the log starting at firstRound.
func lastRoundOfLog(firstRound uint64, endRound uint64) uint64 {
	if endRound-firstRound < ExecutionLogRoundCount {
		return endRound
	}

	return gnsmath.SafeAddUint64(firstRound, ExecutionLogRoundCount-1)
}

gnomod.toml

module = "gno.land/p/gnoswap/order/dca/v0"
gno = "0.9"

[addpkg]
  creator = "g1q5tjjv3kkslzwf2na9y9wk7e5a8ugph8xfsk04"
  height = 1108539
  max_deposit = "100000000ugnot"

group.gno

package dca

import (
	u256 "gno.land/p/gnoswap/uint256/v1"
	rotree "gno.land/p/nt/bptree/rotree/v0"
	bptree "gno.land/p/nt/bptree/v0"
)

// roundMarkBPTreeFanout is the fanout of a group's round mark B+tree.
const roundMarkBPTreeFanout = 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.
type Group struct {
	id          string
	inputToken  string
	outputToken string
	interval    int64
	slotOffset  int64 // seconds after each interval boundary of the unix epoch

	round                          uint64     // number of executed rounds
	orderAmount                    int64      // input sold in the next round, sum of active amountPerExecution
	accumulatedOutputPerAmountX128 *u256.Uint // cumulative output per unit of input, Q128
	nextExecutionTimestamp         int64      // earliest unix time of the next execution

	activeOrderCount int64 // number of unfinalized orders

	roundMarks *bptree.BPTree // EncodeUint64(round) -> *RoundMark
}

// NewGroup creates an empty group whose first round is due at nextExecutionTimestamp.
func NewGroup(id string, inputToken string, outputToken string, interval int64, slotOffset int64, nextExecutionTimestamp int64) *Group {
	return &Group{
		id:                             id,
		inputToken:                     inputToken,
		outputToken:                    outputToken,
		interval:                       interval,
		slotOffset:                     slotOffset,
		round:                          0,
		orderAmount:                    0,
		accumulatedOutputPerAmountX128: u256.Zero(),
		nextExecutionTimestamp:         nextExecutionTimestamp,
		activeOrderCount:               0,
		roundMarks:                     bptree.NewBPTreeN(roundMarkBPTreeFanout),
	}
}

// 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.
func (g *Group) Clone() *Group {
	clone := g.CloneWithoutRoundMarks()
	g.roundMarks.Iterate("", "", func(key string, value any) bool {
		clone.roundMarks.Set(key, value.(*RoundMark).Clone())
		return false
	})

	return clone
}

// 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.
func (g *Group) CloneWithoutRoundMarks() *Group {
	return &Group{
		id:                             g.id,
		inputToken:                     g.inputToken,
		outputToken:                    g.outputToken,
		interval:                       g.interval,
		slotOffset:                     g.slotOffset,
		round:                          g.round,
		orderAmount:                    g.orderAmount,
		accumulatedOutputPerAmountX128: g.accumulatedOutputPerAmountX128.Clone(),
		nextExecutionTimestamp:         g.nextExecutionTimestamp,
		activeOrderCount:               g.activeOrderCount,
		roundMarks:                     bptree.NewBPTreeN(roundMarkBPTreeFanout),
	}
}

func (g *Group) ID() string          { return g.id }
func (g *Group) InputToken() string  { return g.inputToken }
func (g *Group) OutputToken() string { return g.outputToken }
func (g *Group) Interval() int64     { return g.interval }
func (g *Group) SlotOffset() int64   { return g.slotOffset }

func (g *Group) Round() uint64     { return g.round }
func (g *Group) SetRound(v uint64) { g.round = v }

func (g *Group) OrderAmount() int64     { return g.orderAmount }
func (g *Group) SetOrderAmount(v int64) { g.orderAmount = v }

func (g *Group) AccumulatedOutputPerAmountX128() *u256.Uint {
	return g.accumulatedOutputPerAmountX128.Clone()
}
func (g *Group) SetAccumulatedOutputPerAmountX128(v *u256.Uint) {
	g.accumulatedOutputPerAmountX128.Set(v)
}

func (g *Group) NextExecutionTimestamp() int64     { return g.nextExecutionTimestamp }
func (g *Group) SetNextExecutionTimestamp(v int64) { g.nextExecutionTimestamp = v }

func (g *Group) ActiveOrderCount() int64     { return g.activeOrderCount }
func (g *Group) SetActiveOrderCount(v int64) { g.activeOrderCount = v }

func (g *Group) RoundMarkCount() int { return g.roundMarks.Size() }

// GetRoundMark returns the mark of a round, or nil when no order ends there.
func (g *Group) GetRoundMark(round uint64) *RoundMark {
	value := g.roundMarks.Get(RoundKey(round))
	if value == nil {
		return nil
	}

	return value.(*RoundMark)
}

// 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.
func (g *Group) RoundMarks() *rotree.ReadOnlyTree {
	return rotree.Wrap(g.roundMarks, cloneRoundMarkEntry)
}

// GetOrCreateRoundMark returns the mark of a round, creating it if missing.
func (g *Group) GetOrCreateRoundMark(round uint64) *RoundMark {
	mark := g.GetRoundMark(round)
	if mark != nil {
		return mark
	}

	// Allocate the snapshot slot now, while creating the first order
	// ending here, so that order's creator pays its storage deposit
	// instead of the keeper who later executes the round.
	mark = &RoundMark{orderAmount: 0, orderCount: 0, accumulatedOutputPerAmountX128: u256.Zero()}
	g.roundMarks.Set(RoundKey(round), mark)

	return mark
}

func (g *Group) RemoveRoundMark(round uint64) {
	g.roundMarks.Remove(RoundKey(round))
}

// 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.
type RoundMark struct {
	orderAmount                    int64      // sum of amountPerExecution of the orders ending at the round
	orderCount                     int64      // number of unfinalized orders ending at the round
	accumulatedOutputPerAmountX128 *u256.Uint // valid once the group round reaches the mark
}

// Clone returns a deep copy of the mark.
func (m *RoundMark) Clone() *RoundMark {
	return &RoundMark{
		orderAmount:                    m.orderAmount,
		orderCount:                     m.orderCount,
		accumulatedOutputPerAmountX128: m.accumulatedOutputPerAmountX128.Clone(),
	}
}

func cloneRoundMarkEntry(value any) any {
	mark, ok := value.(*RoundMark)
	if !ok {
		return nil
	}

	return mark.Clone()
}

func (m *RoundMark) OrderAmount() int64     { return m.orderAmount }
func (m *RoundMark) SetOrderAmount(v int64) { m.orderAmount = v }

func (m *RoundMark) OrderCount() int64     { return m.orderCount }
func (m *RoundMark) SetOrderCount(v int64) { m.orderCount = v }

func (m *RoundMark) AccumulatedOutputPerAmountX128() *u256.Uint {
	return m.accumulatedOutputPerAmountX128.Clone()
}

// SnapshotAccumulatedOutputPerAmountX128 records the group accumulator
// right after the round executes.
// It writes into the existing slot, so no new object is stored.
func (m *RoundMark) SnapshotAccumulatedOutputPerAmountX128(v *u256.Uint) {
	m.accumulatedOutputPerAmountX128.Set(v)
}

keys.gno

package dca

import (
	"strconv"
	"strings"

	"gno.land/p/gnoswap/utils/v1"
)

// MakeGroupID builds the group key
// "inputToken:outputToken:interval:slotOffset".
func MakeGroupID(inputToken string, outputToken string, interval int64, slotOffset int64) string {
	return inputToken + ":" + outputToken + ":" + utils.FormatInt(interval) + ":" + utils.FormatInt(slotOffset)
}

// OrderKey encodes an order ID so B+tree order matches numeric order.
func OrderKey(orderID uint64) string {
	return utils.EncodeUint64(orderID)
}

// RoundKey encodes a round so B+tree order matches numeric order.
func RoundKey(round uint64) string {
	return utils.EncodeUint64(round)
}

// OwnerOrderPrefix is the common prefix of an owner's index keys.
func OwnerOrderPrefix(owner address) string {
	return owner.String() + "/"
}

// OwnerOrderKey sorts an owner's orders by ID under OwnerOrderPrefix.
func OwnerOrderKey(owner address, orderID uint64) string {
	return OwnerOrderPrefix(owner) + utils.EncodeUint64(orderID)
}

// 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.
func GroupOrderPrefix(groupID string) string {
	return groupID + "/"
}

// GroupOrderKey sorts a group's orders by ID under GroupOrderPrefix.
func GroupOrderKey(groupID string, orderID uint64) string {
	return GroupOrderPrefix(groupID) + utils.EncodeUint64(orderID)
}

// 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.
func GroupOrderFeeRatePrefix(groupID string, executionFeeRate int64) string {
	return GroupOrderPrefix(groupID) + utils.EncodeUint64(uint64(executionFeeRate))
}

// GroupOrderAmountKey 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.
func GroupOrderAmountKey(groupID string, executionFeeRate int64, amountPerExecution int64, orderID uint64) string {
	return GroupOrderFeeRatePrefix(groupID, executionFeeRate) + utils.EncodeUint64(uint64(amountPerExecution)) + utils.EncodeUint64(orderID)
}

// GroupOrderAmountKeyFeeRate extracts executionFeeRate from a
// GroupOrderAmountKey of groupID.
func GroupOrderAmountKeyFeeRate(groupID string, key string) int64 {
	start := len(GroupOrderPrefix(groupID))
	return int64(utils.DecodeUint64(key[start : start+8]))
}

// GroupOrderAmountKeyAmount extracts amountPerExecution from a
// GroupOrderAmountKey of groupID.
func GroupOrderAmountKeyAmount(groupID string, key string) int64 {
	start := len(GroupOrderPrefix(groupID)) + 8
	return int64(utils.DecodeUint64(key[start : start+8]))
}

// ExecutionLogPrefix is the common prefix of an order's execution log keys.
func ExecutionLogPrefix(orderID uint64) string {
	return utils.EncodeUint64(orderID)
}

// ExecutionLogKey sorts an order's execution logs by round
// under ExecutionLogPrefix.
func ExecutionLogKey(orderID uint64, round uint64) string {
	return ExecutionLogPrefix(orderID) + utils.EncodeUint64(round)
}

// PrefixEnd is an exclusive upper bound for prefix + 8-byte encoded ID keys.
// Nine 0xff bytes sort after every 8-byte suffix.
func PrefixEnd(prefix string) string {
	return prefix + "\xff\xff\xff\xff\xff\xff\xff\xff\xff"
}

// ScheduleKey orders groups by next execution timestamp, then group ID.
func ScheduleKey(nextExecutionTimestamp int64, groupID string) string {
	return utils.EncodeUint64(uint64(nextExecutionTimestamp)) + groupID
}

// ScheduleKeyTimestamp extracts the next execution timestamp from a ScheduleKey.
func ScheduleKeyTimestamp(key string) int64 {
	return int64(utils.DecodeUint64(key[:8]))
}

// FormatScheduleCursor renders a schedule entry as
// "<nextExecutionTimestamp>|<groupID>".
func FormatScheduleCursor(nextExecutionTimestamp int64, groupID string) string {
	return utils.FormatInt(nextExecutionTimestamp) + "|" + groupID
}

// 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.
func ParseScheduleCursor(cursor string) (string, error) {
	if cursor == "" {
		return "", nil
	}

	sep := strings.Index(cursor, "|")
	if sep <= 0 {
		return "", ErrInvalidCursor
	}

	nextExecutionTimestamp, err := strconv.ParseInt(cursor[:sep], 10, 64)
	if err != nil || nextExecutionTimestamp < 0 {
		return "", ErrInvalidCursor
	}

	return ScheduleKey(nextExecutionTimestamp, cursor[sep+1:]), nil
}

// PairKey builds the key of a pair direction, "inputToken:outputToken".
// Token paths contain no ':', so the key is unambiguous.
func PairKey(inputToken string, outputToken string) string {
	return inputToken + ":" + outputToken
}

math.gno

package dca

import (
	"math"

	"gno.land/p/gnoswap/gnsmath/v1"
	u256 "gno.land/p/gnoswap/uint256/v1"
)

// Read-only constants: never pass them to a mutating u256 method.
var (
	q128         = u256.Zero().Lsh(u256.One(), 128)
	maxInt64U256 = u256.NewUintFromInt64(math.MaxInt64)
)

// Q128 returns a copy of 2^128, the accumulator scale.
func Q128() *u256.Uint {
	return q128.Clone()
}

// 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.
func CalculateNextExecutionTimestamp(scheduledTimestamp int64, currentTimestamp int64, interval int64) (int64, error) {
	if interval <= 0 || scheduledTimestamp < 0 || currentTimestamp < 0 {
		return 0, ErrInvalidInput
	}

	// Slots from scheduledTimestamp to the next one, at least one,
	// and the most that stay within math.MaxInt64.
	maxSlotCount := (math.MaxInt64 - scheduledTimestamp) / interval

	slotCount := int64(1)

	if currentTimestamp >= scheduledTimestamp {
		elapsedSlotCount := (currentTimestamp - scheduledTimestamp) / interval
		if elapsedSlotCount >= maxSlotCount {
			return 0, ErrOverflow
		}

		slotCount = gnsmath.SafeAddInt64(elapsedSlotCount, 1)
	}

	if slotCount > maxSlotCount {
		return 0, ErrOverflow
	}

	return gnsmath.SafeAddInt64(scheduledTimestamp, gnsmath.SafeMulInt64(slotCount, interval)), nil
}

// 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).
func CalculateFirstSlotTimestamp(currentTimestamp int64, interval int64, slotOffset int64) (int64, error) {
	if interval <= 0 || slotOffset < 0 || slotOffset >= interval || currentTimestamp < 0 {
		return 0, ErrInvalidInput
	}

	// slotOffset and the remainder are both in [0, interval),
	// so the wait stays within [0, interval) without overflowing.
	wait := slotOffset - currentTimestamp%interval
	if wait < 0 {
		wait = gnsmath.SafeAddInt64(wait, interval)
	}

	if currentTimestamp > math.MaxInt64-wait {
		return 0, ErrOverflow
	}

	return gnsmath.SafeAddInt64(currentTimestamp, wait), nil
}

// CalculateMinExecutionGap returns minExecutionGapRate (basis points) of
// interval in seconds, rounded up: the minimum time between two executions
// of a group.
func CalculateMinExecutionGap(interval int64, minExecutionGapRate int64) (int64, error) {
	if interval < 0 || minExecutionGapRate < 0 {
		return 0, ErrInvalidInput
	}

	return toInt64(u256.MulDivRoundingUp(
		u256.NewUint(uint64(interval)),
		u256.NewUint(uint64(minExecutionGapRate)),
		u256.NewUint(uint64(BasisPointDenominator)),
	))
}

// 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.
func CalculateNextExecutionTimestampWithGap(scheduledTimestamp int64, currentTimestamp int64, interval int64, minExecutionGap int64) (int64, error) {
	if minExecutionGap < 0 {
		return 0, ErrInvalidInput
	}

	// The next slot is strictly after its argument, so it is at least
	// minExecutionGap seconds after currentTimestamp.
	after := currentTimestamp
	if minExecutionGap > 0 {
		if currentTimestamp > math.MaxInt64-(minExecutionGap-1) {
			return 0, ErrOverflow
		}

		after += minExecutionGap - 1
	}

	return CalculateNextExecutionTimestamp(scheduledTimestamp, after, interval)
}

// CalculateExecutionFeeAmount returns
// amount * executionFeeRate / BasisPointDenominator,
// rounded down, so the fee never exceeds the configured share.
// Config.SetExecutionFeeRate bounds the rate to [0, MaxExecutionFeeRate].
func CalculateExecutionFeeAmount(amount int64, executionFeeRate int64) (int64, error) {
	if amount < 0 || executionFeeRate < 0 {
		return 0, ErrInvalidInput
	}

	return toInt64(calculateExecutionFeeAmountU256(u256.NewUint(uint64(amount)), executionFeeRate))
}

// 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].
func CalculatePayoutExecutionFeeAmount(paidGrossAmount *u256.Uint, grossAmount int64, executionFeeRate int64) (int64, error) {
	if grossAmount < 0 || !isValidExecutionFeeRate(executionFeeRate) {
		return 0, ErrInvalidInput
	}

	if grossAmount == 0 || executionFeeRate == 0 {
		return 0, nil
	}

	totalGrossAmount, overflow := u256.Zero().AddOverflow(paidGrossAmount, u256.NewUint(uint64(grossAmount)))
	if overflow {
		return 0, ErrOverflow
	}

	totalFeeAmount := calculateExecutionFeeAmountU256(totalGrossAmount, executionFeeRate)
	paidFeeAmount := calculateExecutionFeeAmountU256(paidGrossAmount, executionFeeRate)

	return toInt64(u256.Zero().Sub(totalFeeAmount, paidFeeAmount))
}

// 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].
func CalculateMinNetAmountOut(grossAmount int64, executionFeeRate int64) (int64, error) {
	if grossAmount < 0 || !isValidExecutionFeeRate(executionFeeRate) {
		return 0, ErrInvalidInput
	}

	return toInt64(u256.MulDiv(
		u256.NewUint(uint64(grossAmount)),
		u256.NewUint(uint64(BasisPointDenominator-executionFeeRate)),
		u256.NewUint(uint64(BasisPointDenominator)),
	))
}

// calculateExecutionFeeAmountU256 returns
// floor(amount * executionFeeRate / BasisPointDenominator).
// It is the single rounding rule of every execution fee.
func calculateExecutionFeeAmountU256(amount *u256.Uint, executionFeeRate int64) *u256.Uint {
	return u256.MulDiv(
		amount,
		u256.NewUint(uint64(executionFeeRate)),
		u256.NewUint(uint64(BasisPointDenominator)),
	)
}

// isValidExecutionFeeRate reports whether executionFeeRate is in
// [0, MaxExecutionFeeRate].
func isValidExecutionFeeRate(executionFeeRate int64) bool {
	return executionFeeRate >= 0 && executionFeeRate <= MaxExecutionFeeRate
}

// CalculateOutputPerAmountX128 returns amountOut * 2^128 / amountIn,
// rounded down: the output per unit of input of one round,
// added to the group accumulator.
func CalculateOutputPerAmountX128(amountOut int64, amountIn int64) (*u256.Uint, error) {
	if amountIn <= 0 || amountOut < 0 {
		return nil, ErrInvalidInput
	}

	return u256.MulDiv(u256.NewUint(uint64(amountOut)), q128, u256.NewUint(uint64(amountIn))), nil
}

// CalculateOwedAmount returns
// amountPerExecution * (endAccumulatedX128 - debtX128) / 2^128, rounded down:
// the output accrued since the last payout.
func CalculateOwedAmount(amountPerExecution int64, endAccumulatedX128 *u256.Uint, debtX128 *u256.Uint) (*u256.Uint, error) {
	if endAccumulatedX128.Lt(debtX128) {
		return nil, ErrAccumulatorBackwards
	}

	delta := u256.Zero().Sub(endAccumulatedX128, debtX128)
	if delta.IsZero() || amountPerExecution <= 0 {
		return u256.Zero(), nil
	}

	return u256.MulDiv(delta, u256.NewUint(uint64(amountPerExecution)), q128), nil
}

// 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.
func CalculatePayout(amountPerExecution int64, endAccumulatedX128 *u256.Uint, debtX128 *u256.Uint) (int64, error) {
	owedAmount, err := CalculateOwedAmount(amountPerExecution, endAccumulatedX128, debtX128)
	if err != nil {
		return 0, err
	}

	return toInt64(owedAmount)
}

// 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.
func CalculateDebtX128AfterPayout(amountPerExecution int64, debtX128 *u256.Uint, payoutAmount int64) (*u256.Uint, error) {
	if amountPerExecution <= 0 || payoutAmount < 0 {
		return nil, ErrInvalidInput
	}

	settledX128 := u256.MulDivRoundingUp(u256.NewUint(uint64(payoutAmount)), q128, u256.NewUint(uint64(amountPerExecution)))

	nextDebtX128, overflow := u256.Zero().AddOverflow(debtX128, settledX128)
	if overflow {
		return nil, ErrOverflow
	}

	return nextDebtX128, nil
}

// toInt64 converts a non-negative u256 to int64, or returns ErrOverflow.
func toInt64(v *u256.Uint) (int64, error) {
	if v.Gt(maxInt64U256) {
		return 0, ErrOverflow
	}

	return int64(v.Uint64()), nil
}

order.gno

package dca

import (
	"gno.land/p/gnoswap/gnsmath/v1"
	"math"

	u256 "gno.land/p/gnoswap/uint256/v1"
)

// 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.
type OrderStatus string

const (
	// OrderStatusActive: still selling input or holding unclaimed output.
	OrderStatusActive OrderStatus = "ACTIVE"
	// OrderStatusCompleted: every round executed and all output was paid.
	OrderStatusCompleted OrderStatus = "COMPLETED"
	// OrderStatusCancelled: cancelled by the owner; unsold input was refunded.
	OrderStatusCancelled OrderStatus = "CANCELLED"
)

func (s OrderStatus) String() string {
	return string(s)
}

// Order u256 setters copy the value into the field's existing object
// instead of attaching a new one: updates create no objects, and an order
// can be deleted in the same transaction it was updated in.
// Getters return copies, so stored values are never shared.

// 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.
type Order struct {
	id    uint64
	owner address

	groupID string // tokens and interval are on the group

	amountPerExecution int64
	startRound         uint64
	endRound           uint64

	// executionFeeRate is the share of the order's gross output,
	// in basis points, charged when it is paid out.
	executionFeeRate int64

	debtX128      *u256.Uint // group accumulator already paid out, see CalculateDebtX128AfterPayout
	claimedAmount *u256.Uint // lifetime output paid to the owner, net of the execution fee; 256-bit so it never overflows

	// executionFeeAmount is the lifetime execution fee charged on payouts;
	// claimedAmount + executionFeeAmount is the gross output paid out.
	executionFeeAmount *u256.Uint

	// Last round whose execution log was released;
	// the logs of rounds (releasedRound, endRound] are stored.
	releasedRound uint64

	createdTimestamp int64
	createdHeight    int64
}

// 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.
func NewOrder(
	id uint64,
	owner address,
	group *Group,
	amountPerExecution int64,
	executionCount int64,
	executionFeeRate int64,
	createdTimestamp int64,
	createdHeight int64,
) (*Order, error) {
	if executionCount <= 0 || !isValidExecutionFeeRate(executionFeeRate) {
		return nil, ErrInvalidInput
	}

	startRound := group.Round()
	if uint64(executionCount) > math.MaxUint64-startRound {
		return nil, ErrOverflow
	}

	return &Order{
		id:                 id,
		owner:              owner,
		groupID:            group.ID(),
		amountPerExecution: amountPerExecution,
		startRound:         startRound,
		endRound:           gnsmath.SafeAddUint64(startRound, uint64(executionCount)),
		executionFeeRate:   executionFeeRate,
		debtX128:           group.AccumulatedOutputPerAmountX128(), // already a copy
		claimedAmount:      u256.Zero(),
		executionFeeAmount: u256.Zero(),
		releasedRound:      startRound,
		createdTimestamp:   createdTimestamp,
		createdHeight:      createdHeight,
	}, nil
}

// Clone returns a deep copy of the order,
// so callers can read it without aliasing stored state.
func (o *Order) Clone() *Order {
	return &Order{
		id:                 o.id,
		owner:              o.owner,
		groupID:            o.groupID,
		amountPerExecution: o.amountPerExecution,
		startRound:         o.startRound,
		endRound:           o.endRound,
		executionFeeRate:   o.executionFeeRate,
		debtX128:           o.debtX128.Clone(),
		claimedAmount:      o.claimedAmount.Clone(),
		executionFeeAmount: o.executionFeeAmount.Clone(),
		releasedRound:      o.releasedRound,
		createdTimestamp:   o.createdTimestamp,
		createdHeight:      o.createdHeight,
	}
}

func (o *Order) ID() uint64                { return o.id }
func (o *Order) Owner() address            { return o.owner }
func (o *Order) GroupID() string           { return o.groupID }
func (o *Order) AmountPerExecution() int64 { return o.amountPerExecution }
func (o *Order) ExecutionCount() int64     { return int64(o.endRound - o.startRound) }
func (o *Order) StartRound() uint64        { return o.startRound }
func (o *Order) EndRound() uint64          { return o.endRound }
func (o *Order) ExecutionFeeRate() int64   { return o.executionFeeRate }
func (o *Order) CreatedTimestamp() int64   { return o.createdTimestamp }
func (o *Order) CreatedHeight() int64      { return o.createdHeight }

func (o *Order) DebtX128() *u256.Uint     { return o.debtX128.Clone() }
func (o *Order) SetDebtX128(v *u256.Uint) { o.debtX128.Set(v) }

func (o *Order) ClaimedAmount() *u256.Uint     { return o.claimedAmount.Clone() }
func (o *Order) SetClaimedAmount(v *u256.Uint) { o.claimedAmount.Set(v) }

func (o *Order) ExecutionFeeAmount() *u256.Uint     { return o.executionFeeAmount.Clone() }
func (o *Order) SetExecutionFeeAmount(v *u256.Uint) { o.executionFeeAmount.Set(v) }

// PaidGrossAmount returns the gross output paid out so far:
// claimedAmount plus executionFeeAmount.
func (o *Order) PaidGrossAmount() *u256.Uint {
	return u256.Zero().Add(o.claimedAmount, o.executionFeeAmount)
}

// ExecutionLogCount returns the number of the order's unreleased logs.
// Logs start at fixed offsets from the start round, so no lookup is needed.
func (o *Order) ExecutionLogCount() int64 {
	remainingRoundCount := o.endRound - o.releasedRound

	logCount := remainingRoundCount / ExecutionLogRoundCount
	if remainingRoundCount%ExecutionLogRoundCount != 0 {
		logCount = gnsmath.SafeAddUint64(logCount, 1)
	}

	return gnsmath.SafeUint64ToInt64(logCount)
}

// setReleasedRound is a method, not a field write, so an implementation
// other than the order's creator can update it after an upgrade.
func (o *Order) setReleasedRound(round uint64) { o.releasedRound = round }

price_limit.gno

package dca

import (
	u256 "gno.land/p/gnoswap/uint256/v1"
)

// 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.
type PairPriceLimit struct {
	minOutputPerInputX128 *u256.Uint
	updatedAt             int64
}

// NewPairPriceLimit returns a limit of minOutputPerInputX128, set at updatedAt.
func NewPairPriceLimit(minOutputPerInputX128 *u256.Uint, updatedAt int64) *PairPriceLimit {
	return &PairPriceLimit{
		minOutputPerInputX128: minOutputPerInputX128.Clone(),
		updatedAt:             updatedAt,
	}
}

// MinOutputPerInputX128 returns a copy of the limit.
func (l *PairPriceLimit) MinOutputPerInputX128() *u256.Uint {
	return l.minOutputPerInputX128.Clone()
}

// UpdatedAt returns the unix time the limit was set.
func (l *PairPriceLimit) UpdatedAt() int64 { return l.updatedAt }

// Update replaces the limit and its update time in place.
func (l *PairPriceLimit) Update(minOutputPerInputX128 *u256.Uint, updatedAt int64) {
	l.minOutputPerInputX128 = minOutputPerInputX128.Clone()
	l.updatedAt = updatedAt
}

// Clone returns a copy of the limit.
func (l *PairPriceLimit) Clone() *PairPriceLimit {
	return NewPairPriceLimit(l.minOutputPerInputX128, l.updatedAt)
}

types.gno

package dca

import (
	rotree "gno.land/p/nt/bptree/rotree/v0"
	bptree "gno.land/p/nt/bptree/v0"
)

// These interfaces are the contract between the proxy realm
// gno.land/r/gnoswap/order/dca and its implementations.
// Keeping them in an immutable package lets every implementation version
// compile against the same definitions.

// IDCAOrder is the implementation interface behind the order/dca proxy.
type IDCAOrder interface {
	IDCAOrderManager
	IDCAOrderExecutor
	IDCAOrderAdmin
	IDCAOrderGetter
}

// IDCAOrderManager covers owner-facing order operations.
type IDCAOrderManager interface {
	// CreateOrder escrows amountPerExecution*executionCount of inputToken,
	// and joins the (inputToken, outputToken, interval, slotOffset) group.
	CreateOrder(
		_ int,
		rlm realm,
		inputToken string,
		outputToken string,
		interval int64,
		slotOffset int64,
		amountPerExecution int64,
		executionCount int64,
	) uint64

	// CancelOrder pays accrued output, refunds unsold input,
	// and closes the order. Owner only.
	CancelOrder(_ int, rlm realm, orderID uint64) (refundedAmount int64, claimedAmount int64)

	// Claim pays accrued output to the order owner. Anyone may call it.
	Claim(_ int, rlm realm, orderID uint64) (claimedAmount int64)
}

// IDCAOrderExecutor covers keeper-authorized execution and cancellation,
// and public batch-claim entry points.
type IDCAOrderExecutor interface {
	// ExecuteGroup sells the group's per-round input with a pool swap,
	// on the pool with the best quote, and credits the output to the orders;
	// each order's execution fee is deducted when it is paid out.
	// amountOutMin (0 disables it) is the pool output floor
	// quoted for expectedAmountIn.
	// If the group orderAmount differs from expectedAmountIn,
	// the round reverts so the keeper can quote again.
	// Passing 0 for both runs the round without a floor.
	// Every order of the round must be credited at least
	// max(1, minOrderAmountOut) of output after its own execution fee
	// rate, or the round reverts.
	ExecuteGroup(
		_ int,
		rlm realm,
		groupID string,
		expectedAmountIn int64,
		amountOutMin int64,
		minOrderAmountOut int64,
	) (executedAmountIn int64, executedAmountOut int64)

	// ClaimGroupOrders pays accrued output to the owners of up to
	// maxOrderCount orders of a group, after startAfterOrderID in ID order.
	// It returns the number of orders paid or completed,
	// and the cursor for the next call (0 when the group is done).
	ClaimGroupOrders(_ int, rlm realm, groupID string, startAfterOrderID uint64, maxOrderCount int) (claimedOrderCount int, nextCursor uint64)

	// ForceCancelOrder closes an order that blocks its group's rounds,
	// as CancelOrder does for its owner: accrued output and unsold input
	// go to the owner. The implementation checks on-chain that the order
	// blocks its group and rejects any other. Keeper role only.
	ForceCancelOrder(_ int, rlm realm, orderID uint64) (refundedAmount int64, claimedAmount int64)

	// CollectPendingExecutionFee forwards the execution fee pending for
	// tokenPath to the protocol fee realm. Anyone may call it.
	CollectPendingExecutionFee(_ int, rlm realm, tokenPath string) (forwardedAmount int64, pendingAmount int64)
}

// IDCAOrderAdmin covers admin or governance operations.
// Every rate is in basis points of BasisPointDenominator.
type IDCAOrderAdmin interface {
	// SetExecutionFeeRate sets the share of an order's gross output,
	// in basis points, sent to the protocol fee realm.
	// Orders snapshot it at creation; existing orders keep their rate.
	SetExecutionFeeRate(_ int, rlm realm, executionFeeRate int64)

	// AddAllowedInterval and RemoveAllowedInterval manage the intervals new
	// orders may use; existing orders keep their interval.
	AddAllowedInterval(_ int, rlm realm, interval int64)
	RemoveAllowedInterval(_ int, rlm realm, interval int64)
	// SetOrderLimits sets the minimum input per execution
	// and the maximum executions per order.
	SetOrderLimits(_ int, rlm realm, minAmountPerExecution int64, maxExecutionCount int64)

	// SetMinExecutionGapRate sets the minimum gap between a group's
	// executions, in basis points of its interval.
	SetMinExecutionGapRate(_ int, rlm realm, minExecutionGapRate int64)

	// SetMaxClaimBatchSize caps the orders one ClaimGroupOrders call examines.
	SetMaxClaimBatchSize(_ int, rlm realm, maxClaimBatchSize int64)

	// SetMaxPoolPriceDeviationRate sets how far, in basis points of price, a
	// pool's price may sit on the favorable side of its swap price limit and
	// still be quoted; 0 disables the check.
	SetMaxPoolPriceDeviationRate(_ int, rlm realm, maxPoolPriceDeviationRate int64)

	// SetMaxPairPriceLimitAge sets how long, in seconds, a pair price limit
	// stays usable after it was set.
	SetMaxPairPriceLimitAge(_ int, rlm realm, maxPairPriceLimitAge int64)

	// SetSlotStep sets the spacing of the slot offsets
	// new orders may use at interval.
	SetSlotStep(_ int, rlm realm, interval int64, slotStep int64)

	// SetTokenMinAmountPerExecution sets the minimum input per execution of
	// orders selling tokenPath, on top of the global minimum; 0 removes it.
	// Admin, governance, or the manager role assigned to the selector.
	SetTokenMinAmountPerExecution(_ int, rlm realm, tokenPath string, minAmountPerExecution int64)

	// SetPairPriceLimit sets the minimum pool output per unit of input,
	// in Q128, of rounds selling inputToken for outputToken; "0" removes it.
	// A pair direction without a limit cannot be quoted, executed,
	// or receive new orders.
	// Admin, governance, or the manager role assigned to the selector.
	SetPairPriceLimit(_ int, rlm realm, inputToken string, outputToken string, minOutputPerInputX128 string)
}

// 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.
type IDCAOrderGetter interface {
	GetConfig() *Config
	GetNextOrderID() uint64

	ExistsOrder(orderID uint64) bool
	GetOrder(orderID uint64) (*Order, error)
	GetOrders() *rotree.ReadOnlyTree
	GetOrdersByOwner() *rotree.ReadOnlyTree
	GetOrderIDsByOwner(owner address, startAfterID uint64, count int) []uint64
	GetClaimableAmount(orderID uint64) int64
	GetOrderExecutionLogs(orderID uint64, count int) ([]*ExecutionLog, error)
	GetExecutionLogs() *rotree.ReadOnlyTree

	ExistsGroup(groupID string) bool
	GetGroup(groupID string) (*Group, error)
	GetGroups() *rotree.ReadOnlyTree
	GetGroupRoundMarks(groupID string) *rotree.ReadOnlyTree
	GetOrdersByGroup() *rotree.ReadOnlyTree
	GetOrderAmountsByGroup() *rotree.ReadOnlyTree
	GetOrderIDsByGroup(groupID string, startAfterID uint64, count int) []uint64
	GetScheduledGroups() *rotree.ReadOnlyTree
	GetExecutableGroups(cursor string, count int) ([]*Group, error)
	GetExecutionQuote(groupID string) string

	GetTokenMinAmountPerExecution(tokenPath string) int64
	GetMinAmountPerExecution(tokenPath string) int64
	GetTokenMinAmountsPerExecution() *rotree.ReadOnlyTree
	GetPairPriceLimit(inputToken string, outputToken string) (*PairPriceLimit, bool)
	GetPairPriceLimits() *rotree.ReadOnlyTree

	GetPendingExecutionFeeAmount(tokenPath string) int64
	GetPendingExecutionFees() *rotree.ReadOnlyTree
}

// IDCAOrderStore is the persistent storage shared by all versions.
type IDCAOrderStore interface {
	HasOrders() bool
	GetOrders() *bptree.BPTree
	SetOrders(_ int, rlm realm, orders *bptree.BPTree) error

	HasOrdersByOwner() bool
	GetOrdersByOwner() *bptree.BPTree
	SetOrdersByOwner(_ int, rlm realm, ordersByOwner *bptree.BPTree) error

	HasGroups() bool
	GetGroups() *bptree.BPTree
	SetGroups(_ int, rlm realm, groups *bptree.BPTree) error

	HasScheduledGroups() bool
	GetScheduledGroups() *bptree.BPTree
	SetScheduledGroups(_ int, rlm realm, groups *bptree.BPTree) error

	HasNextOrderID() bool
	GetNextOrderID() uint64
	SetNextOrderID(_ int, rlm realm, id uint64) error

	HasConfig() bool
	GetConfig() *Config
	SetConfig(_ int, rlm realm, config *Config) error

	IsExecuting() bool
	SetExecuting(_ int, rlm realm, executing bool) error

	HasOrdersByGroup() bool
	GetOrdersByGroup() *bptree.BPTree
	SetOrdersByGroup(_ int, rlm realm, ordersByGroup *bptree.BPTree) error

	HasPendingExecutionFees() bool
	GetPendingExecutionFees() *bptree.BPTree
	SetPendingExecutionFees(_ int, rlm realm, pendingExecutionFees *bptree.BPTree) error

	HasExecutionLogs() bool
	GetExecutionLogs() *bptree.BPTree
	SetExecutionLogs(_ int, rlm realm, executionLogs *bptree.BPTree) error

	HasOrderAmountsByGroup() bool
	GetOrderAmountsByGroup() *bptree.BPTree
	SetOrderAmountsByGroup(_ int, rlm realm, orderAmountsByGroup *bptree.BPTree) error

	HasTokenMinAmountsPerExecution() bool
	GetTokenMinAmountsPerExecution() *bptree.BPTree
	SetTokenMinAmountsPerExecution(_ int, rlm realm, tokenMinAmounts *bptree.BPTree) error

	HasPairPriceLimits() bool
	GetPairPriceLimits() *bptree.BPTree
	SetPairPriceLimits(_ int, rlm realm, pairPriceLimits *bptree.BPTree) error
}