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

v0 source pure

Package dca holds the immutable building blocks of the GnoSwap DCA (dollar-cost averaging) order realm:

Overview

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

Example
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).

Constants 4

const BasisPointDenominator

1const BasisPointDenominator int64 = 10_000
source

BasisPointDenominator is 100% in basis points, the denominator of every rate in basis points: executionFeeRate, minExecutionGapRate, and maxPoolPriceDeviationRate.

const ExecutionLogRoundCount

1const ExecutionLogRoundCount uint64 = 3
source

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 MaxExecutionFeeRate

1const MaxExecutionFeeRate int64 = 1_000
source

MaxExecutionFeeRate is the largest execution fee rate: 1000 basis points (10%).

const OrderStatusActive, OrderStatusCompleted, OrderStatusCancelled

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)
source

Variables 1

var ErrInvalidInput, ErrOverflow, ErrAccumulatorBackwards, ErrInvalidCursor, ErrIntervalExists, ErrIntervalNotFound

 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)
source

Functions 39

func AllocateExecutionLogs

1func AllocateExecutionLogs(executionLogs *bptree.BPTree, order *Order) int64
source

AllocateExecutionLogs stores the logs of the order's unreleased rounds, ExecutionLogRoundCount rounds per log, and returns how many were stored.

func CalculateDebtX128AfterPayout

1func CalculateDebtX128AfterPayout(amountPerExecution int64, debtX128 *u256.Uint, payoutAmount int64) (*u256.Uint, error)
source

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 CalculateExecutionFeeAmount

1func CalculateExecutionFeeAmount(amount int64, executionFeeRate int64) (int64, error)
source

CalculateExecutionFeeAmount returns amount * executionFeeRate / BasisPointDenominator, rounded down, so the fee never exceeds the configured share. Config.SetExecutionFeeRate bounds the rate to [0, MaxExecutionFeeRate].

func CalculateFirstSlotTimestamp

1func CalculateFirstSlotTimestamp(currentTimestamp int64, interval int64, slotOffset int64) (int64, error)
source

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 CalculateMinExecutionGap

1func CalculateMinExecutionGap(interval int64, minExecutionGapRate int64) (int64, error)
source

CalculateMinExecutionGap returns minExecutionGapRate (basis points) of interval in seconds, rounded up: the minimum time between two executions of a group.

func CalculateMinNetAmountOut

1func CalculateMinNetAmountOut(grossAmount int64, executionFeeRate int64) (int64, error)
source

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 CalculateNextExecutionTimestamp

1func CalculateNextExecutionTimestamp(scheduledTimestamp int64, currentTimestamp int64, interval int64) (int64, error)
source

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 CalculateNextExecutionTimestampWithGap

1func CalculateNextExecutionTimestampWithGap(scheduledTimestamp int64, currentTimestamp int64, interval int64, minExecutionGap int64) (int64, error)
source

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 CalculateOutputPerAmountX128

1func CalculateOutputPerAmountX128(amountOut int64, amountIn int64) (*u256.Uint, error)
source

CalculateOutputPerAmountX128 returns amountOut * 2^128 / amountIn, rounded down: the output per unit of input of one round, added to the group accumulator.

func CalculateOwedAmount

1func CalculateOwedAmount(amountPerExecution int64, endAccumulatedX128 *u256.Uint, debtX128 *u256.Uint) (*u256.Uint, error)
source

CalculateOwedAmount returns amountPerExecution * (endAccumulatedX128 - debtX128) / 2^128, rounded down: the output accrued since the last payout.

func CalculatePayout

1func CalculatePayout(amountPerExecution int64, endAccumulatedX128 *u256.Uint, debtX128 *u256.Uint) (int64, error)
source

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 CalculatePayoutExecutionFeeAmount

1func CalculatePayoutExecutionFeeAmount(paidGrossAmount *u256.Uint, grossAmount int64, executionFeeRate int64) (int64, error)
source

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 ExecutionLogKey

1func ExecutionLogKey(orderID uint64, round uint64) string
source

ExecutionLogKey sorts an order's execution logs by round under ExecutionLogPrefix.

func ExecutionLogPrefix

1func ExecutionLogPrefix(orderID uint64) string
source

ExecutionLogPrefix is the common prefix of an order's execution log keys.

func FormatScheduleCursor

1func FormatScheduleCursor(nextExecutionTimestamp int64, groupID string) string
source

FormatScheduleCursor renders a schedule entry as "<nextExecutionTimestamp>|<groupID>".

func GroupOrderAmountKey

1func GroupOrderAmountKey(groupID string, executionFeeRate int64, amountPerExecution int64, orderID uint64) string
source

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 GroupOrderAmountKeyAmount

1func GroupOrderAmountKeyAmount(groupID string, key string) int64
source

GroupOrderAmountKeyAmount extracts amountPerExecution from a GroupOrderAmountKey of groupID.

func GroupOrderAmountKeyFeeRate

1func GroupOrderAmountKeyFeeRate(groupID string, key string) int64
source

GroupOrderAmountKeyFeeRate extracts executionFeeRate from a GroupOrderAmountKey of groupID.

func GroupOrderFeeRatePrefix

1func GroupOrderFeeRatePrefix(groupID string, executionFeeRate int64) string
source

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 GroupOrderKey

1func GroupOrderKey(groupID string, orderID uint64) string
source

GroupOrderKey sorts a group's orders by ID under GroupOrderPrefix.

func GroupOrderPrefix

1func GroupOrderPrefix(groupID string) string
source

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 MakeGroupID

1func MakeGroupID(inputToken string, outputToken string, interval int64, slotOffset int64) string
source

MakeGroupID builds the group key "inputToken:outputToken:interval:slotOffset".

func OrderKey

1func OrderKey(orderID uint64) string
source

OrderKey encodes an order ID so B+tree order matches numeric order.

func OwnerOrderKey

1func OwnerOrderKey(owner address, orderID uint64) string
source

OwnerOrderKey sorts an owner's orders by ID under OwnerOrderPrefix.

func OwnerOrderPrefix

1func OwnerOrderPrefix(owner address) string
source

OwnerOrderPrefix is the common prefix of an owner's index keys.

func PairKey

1func PairKey(inputToken string, outputToken string) string
source

PairKey builds the key of a pair direction, "inputToken:outputToken". Token paths contain no ':', so the key is unambiguous.

func ParseScheduleCursor

1func ParseScheduleCursor(cursor string) (string, error)
source

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 PrefixEnd

1func PrefixEnd(prefix string) string
source

PrefixEnd is an exclusive upper bound for prefix + 8-byte encoded ID keys. Nine 0xff bytes sort after every 8-byte suffix.

func Q128

1func Q128() *u256.Uint
source

Q128 returns a copy of 2^128, the accumulator scale.

func ReleaseAllExecutionLogs

1func ReleaseAllExecutionLogs(executionLogs *bptree.BPTree, order *Order) int64
source

ReleaseAllExecutionLogs removes every log of the order, executed or not, and returns how many were released.

func ReleaseExecutionLogs

1func ReleaseExecutionLogs(executionLogs *bptree.BPTree, order *Order, executedRound uint64) int64
source

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 RoundKey

1func RoundKey(round uint64) string
source

RoundKey encodes a round so B+tree order matches numeric order.

func ScheduleKey

1func ScheduleKey(nextExecutionTimestamp int64, groupID string) string
source

ScheduleKey orders groups by next execution timestamp, then group ID.

func ScheduleKeyTimestamp

1func ScheduleKeyTimestamp(key string) int64
source

ScheduleKeyTimestamp extracts the next execution timestamp from a ScheduleKey.

func NewConfig

1func NewConfig(minAmountPerExecution, maxExecutionCount int64, allowedIntervals []int64) *Config
source

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 ExecutionLogs

1func ExecutionLogs(executionLogs *bptree.BPTree, order *Order, count int) []*ExecutionLog
source

ExecutionLogs returns up to count of the order's unreleased logs, oldest first.

func NewGroup

1func NewGroup(id string, inputToken string, outputToken string, interval int64, slotOffset int64, nextExecutionTimestamp int64) *Group
source

NewGroup creates an empty group whose first round is due at nextExecutionTimestamp.

func NewOrder

 1func NewOrder(
 2	id uint64,
 3	owner address,
 4	group *Group,
 5	amountPerExecution int64,
 6	executionCount int64,
 7	executionFeeRate int64,
 8	createdTimestamp int64,
 9	createdHeight int64,
10) (*Order, error)
source

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 NewPairPriceLimit

1func NewPairPriceLimit(minOutputPerInputX128 *u256.Uint, updatedAt int64) *PairPriceLimit
source

NewPairPriceLimit returns a limit of minOutputPerInputX128, set at updatedAt.

Types 13

type Config

struct
 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}
source

Config holds governance-controlled DCA parameters.

Methods on Config

func AddAllowedInterval

method on Config
1func (c *Config) AddAllowedInterval(interval int64) error
source

AddAllowedInterval allows interval, keeping the list ascending. The interval starts with a single slot, offset 0; see SetSlotStep.

func AllowedIntervals

method on Config
1func (c *Config) AllowedIntervals() []int64
source

AllowedIntervals returns a copy of the allowed intervals, ascending.

func Clone

method on Config
1func (c *Config) Clone() *Config
source

Clone returns a deep copy of the config.

func IsAllowedInterval

method on Config
1func (c *Config) IsAllowedInterval(interval int64) bool
source

IsAllowedInterval reports whether new orders may use interval.

func IsAllowedSlot

method on Config
1func (c *Config) IsAllowedSlot(interval int64, slotOffset int64) bool
source

IsAllowedSlot reports whether new orders may use slotOffset at interval: a multiple of the interval's slot step in [0, interval).

func RemoveAllowedInterval

method on Config
1func (c *Config) RemoveAllowedInterval(interval int64) error
source

RemoveAllowedInterval disallows interval for new orders, dropping its slot step with it.

func SetExecutionFeeRate

method on Config
1func (c *Config) SetExecutionFeeRate(v int64) error
source

SetExecutionFeeRate sets the execution fee rate in basis points. It returns ErrInvalidInput outside [0, MaxExecutionFeeRate].

func SetSlotStep

method on Config
1func (c *Config) SetSlotStep(interval int64, step int64) error
source

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 SlotStep

method on Config
1func (c *Config) SlotStep(interval int64) int64
source

SlotStep returns the spacing of the slot offsets allowed for interval, or 0 if the interval is not allowed.

type ExecutionLog

struct
1type ExecutionLog struct {
2	firstRound uint64
3	lastRound  uint64
4	amountIn   int64 // input the order sells in each round, its amountPerExecution
5}
source

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.

Methods on ExecutionLog

func AmountIn

method on ExecutionLog
1func (l *ExecutionLog) AmountIn() int64
source

func FirstRound

method on ExecutionLog
1func (l *ExecutionLog) FirstRound() uint64
source

func LastRound

method on ExecutionLog
1func (l *ExecutionLog) LastRound() uint64
source

func RoundCount

method on ExecutionLog
1func (l *ExecutionLog) RoundCount() uint64
source

RoundCount returns the number of rounds the log covers.

type Group

struct
 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}
source

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.

Methods on Group

func Clone

method on Group
1func (g *Group) Clone() *Group
source

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 CloneWithoutRoundMarks

method on Group
1func (g *Group) CloneWithoutRoundMarks() *Group
source

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 GetOrCreateRoundMark

method on Group
1func (g *Group) GetOrCreateRoundMark(round uint64) *RoundMark
source

GetOrCreateRoundMark returns the mark of a round, creating it if missing.

func GetRoundMark

method on Group
1func (g *Group) GetRoundMark(round uint64) *RoundMark
source

GetRoundMark returns the mark of a round, or nil when no order ends there.

func ID

method on Group
1func (g *Group) ID() string
source

func Interval

method on Group
1func (g *Group) Interval() int64
source

func Round

method on Group
1func (g *Group) Round() uint64
source

func RoundMarks

method on Group
1func (g *Group) RoundMarks() *rotree.ReadOnlyTree
source

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 SetRound

method on Group
1func (g *Group) SetRound(v uint64)
source

type IDCAOrder

interface
1type IDCAOrder interface {
2	IDCAOrderManager
3	IDCAOrderExecutor
4	IDCAOrderAdmin
5	IDCAOrderGetter
6}
source

IDCAOrder is the implementation interface behind the order/dca proxy.

type IDCAOrderAdmin

interface
 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}
source

IDCAOrderAdmin covers admin or governance operations. Every rate is in basis points of BasisPointDenominator.

type IDCAOrderExecutor

interface
 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}
source

IDCAOrderExecutor covers keeper-authorized execution and cancellation, and public batch-claim entry points.

type IDCAOrderGetter

interface
 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}
source

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 IDCAOrderManager

interface
 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}
source

IDCAOrderManager covers owner-facing order operations.

type IDCAOrderStore

interface
 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}
source

IDCAOrderStore is the persistent storage shared by all versions.

type Order

struct
 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}
source

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.

Methods on Order

func Clone

method on Order
1func (o *Order) Clone() *Order
source

Clone returns a deep copy of the order, so callers can read it without aliasing stored state.

func DebtX128

method on Order
1func (o *Order) DebtX128() *u256.Uint
source

func EndRound

method on Order
1func (o *Order) EndRound() uint64
source

func ExecutionLogCount

method on Order
1func (o *Order) ExecutionLogCount() int64
source

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 GroupID

method on Order
1func (o *Order) GroupID() string
source

func ID

method on Order
1func (o *Order) ID() uint64
source

func Owner

method on Order
1func (o *Order) Owner() address
source

func PaidGrossAmount

method on Order
1func (o *Order) PaidGrossAmount() *u256.Uint
source

PaidGrossAmount returns the gross output paid out so far: claimedAmount plus executionFeeAmount.

type OrderStatus

ident
1type OrderStatus string
source

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.

Methods on OrderStatus

func String

method on OrderStatus
1func (s OrderStatus) String() string
source

type PairPriceLimit

struct
1type PairPriceLimit struct {
2	minOutputPerInputX128 *u256.Uint
3	updatedAt             int64
4}
source

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.

Methods on PairPriceLimit

func Clone

method on PairPriceLimit
1func (l *PairPriceLimit) Clone() *PairPriceLimit
source

Clone returns a copy of the limit.

func MinOutputPerInputX128

method on PairPriceLimit
1func (l *PairPriceLimit) MinOutputPerInputX128() *u256.Uint
source

MinOutputPerInputX128 returns a copy of the limit.

func Update

method on PairPriceLimit
1func (l *PairPriceLimit) Update(minOutputPerInputX128 *u256.Uint, updatedAt int64)
source

Update replaces the limit and its update time in place.

func UpdatedAt

method on PairPriceLimit
1func (l *PairPriceLimit) UpdatedAt() int64
source

UpdatedAt returns the unix time the limit was set.

type RoundMark

struct
1type RoundMark struct {
2	orderAmount                    int64      // sum of amountPerExecution of the orders ending at the round
3	orderCount                     int64      // number of unfinalized orders ending at the round
4	accumulatedOutputPerAmountX128 *u256.Uint // valid once the group round reaches the mark
5}
source

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.

Methods on RoundMark

func Clone

method on RoundMark
1func (m *RoundMark) Clone() *RoundMark
source

Clone returns a deep copy of the mark.

func OrderAmount

method on RoundMark
1func (m *RoundMark) OrderAmount() int64
source

func OrderCount

method on RoundMark
1func (m *RoundMark) OrderCount() int64
source

func SnapshotAccumulatedOutputPerAmountX128

method on RoundMark
1func (m *RoundMark) SnapshotAccumulatedOutputPerAmountX128(v *u256.Uint)
source

SnapshotAccumulatedOutputPerAmountX128 records the group accumulator right after the round executes. It writes into the existing slot, so no new object is stored.

Dependencies

Source Files 11