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

assert.gno

package impl

import (
	"gno.land/p/gnoswap/order/access/manager/v0"
	pdca "gno.land/p/gnoswap/order/dca/v0"
	prbac "gno.land/p/gnoswap/rbac/v1"
	bptree "gno.land/p/nt/bptree/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/order/halt"
	"gno.land/r/gnoswap/order/keeper"
	"gno.land/r/gnoswap/order/whitelist"
)

// assertIsAdminCall runs the checks shared by admin entry points
// and returns the calling realm.
func (d *dcaOrderImpl) assertIsAdminCall(_ int, rlm realm) realm {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()
	d.assertIsNotExecuting()

	prev := rlm.Previous()
	access.AssertIsAdminOrGovernance(prev.Address())

	return prev
}

// assertIsNotExecuting rejects re-entry from the swap
// into any state-changing entry point.
func (d *dcaOrderImpl) assertIsNotExecuting() {
	if d.store.IsExecuting() {
		panic(makeErrorWithDetails(errReentrant, "group execution in progress").Error())
	}
}

// assertIsNotHalted rejects the call while any of operations is halted
// for DCA orders in gno.land/r/gnoswap/order/halt.
func assertIsNotHalted(operations ...string) {
	if operation, halted := haltedOperation(operations...); halted {
		panic(makeErrorWithDetails(errHalted, ufmt.Sprintf("operation(%s)", operation)).Error())
	}
}

// haltedOperation returns the first of operations halted for DCA orders.
func haltedOperation(operations ...string) (string, bool) {
	for _, operation := range operations {
		if halt.IsHalted(halt.TargetDCA, operation) {
			return operation, true
		}
	}

	return "", false
}

// assertIsAuthorizedKeeper rejects callers that gno.land/r/gnoswap/order/keeper
// does not allow to run rounds on target, the DCA proxy package path.
// ExecuteGroup is assigned to DCAKeeperRole at deployment; admin or
// governance grants it to keepers or reassigns the selector.
func assertIsAuthorizedKeeper(target string, caller address) {
	if !keeper.IsAuthorized(target, keeper.SelectorExecuteGroup, caller) {
		panic(makeErrorWithDetails(errNotKeeper, ufmt.Sprintf("caller(%s)", caller.String())).Error())
	}
}

// assertIsManagerCall runs the checks shared by the manager entry points
// (token minimums and pair price limits) and returns the calling realm.
// Admin and governance may always call them; other callers need the
// PoolManagerRole that gno.land/r/gnoswap/order/keeper assigns on the DCA
// proxy package path.
func (d *dcaOrderImpl) assertIsManagerCall(_ int, rlm realm, selector manager.Selector) realm {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()
	d.assertIsNotExecuting()

	prev := rlm.Previous()
	caller := prev.Address()

	if isAdminOrGovernance(caller) || keeper.IsAuthorized(rlm.PkgPath(), selector, caller) {
		return prev
	}

	panic(makeErrorWithDetails(errNotKeeper, ufmt.Sprintf("caller(%s) selector(%s)", caller.String(), string(selector))).Error())
}

// isAdminOrGovernance reports whether caller is the GnoSwap admin or governance.
func isAdminOrGovernance(caller address) bool {
	return access.IsAuthorized(prbac.ROLE_ADMIN.String(), caller) || access.IsAuthorized(prbac.ROLE_GOVERNANCE.String(), caller)
}

// assertIsValidPair checks that inputToken and outputToken differ
// and that at least one whitelisted direct pool connects them.
func assertIsValidPair(inputToken string, outputToken string) {
	if inputToken == outputToken {
		panic(makeErrorWithDetails(errInvalidToken, ufmt.Sprintf("inputToken and outputToken are both %s", inputToken)).Error())
	}

	if !whitelist.HasWhitelistedPool(whitelist.TargetDCA, inputToken, outputToken) {
		panic(makeErrorWithDetails(errInvalidPool, ufmt.Sprintf("no whitelisted pool for %s -> %s", inputToken, outputToken)).Error())
	}
}

// assertHasPairPriceLimit checks that the pair direction has a price limit,
// without which its rounds cannot trade.
func assertHasPairPriceLimit(pairPriceLimits *bptree.BPTree, inputToken string, outputToken string) {
	if getPairPriceLimit(pairPriceLimits, inputToken, outputToken) == nil {
		panic(makeErrorWithDetails(errMissingPriceLimit, ufmt.Sprintf("no price limit for %s -> %s", inputToken, outputToken)).Error())
	}
}

// assertIsAllowedInterval checks that new orders may use interval.
func assertIsAllowedInterval(config *pdca.Config, interval int64) {
	if !config.IsAllowedInterval(interval) {
		panic(makeErrorWithDetails(errInvalidInterval, ufmt.Sprintf("interval(%d)", interval)).Error())
	}
}

// assertIsAllowedSlot checks that new orders may use slotOffset at interval.
func assertIsAllowedSlot(config *pdca.Config, interval int64, slotOffset int64) {
	if !config.IsAllowedSlot(interval, slotOffset) {
		panic(makeErrorWithDetails(
			errInvalidSlotOffset,
			ufmt.Sprintf("slotOffset(%d) must be a multiple of %d in [0, %d)", slotOffset, config.SlotStep(interval), interval),
		).Error())
	}
}

// assertIsValidOrderSize checks the order against the configured limits;
// minAmountPerExecution is the effective minimum of the input token
// (see minAmountPerExecution).
func assertIsValidOrderSize(config *pdca.Config, minAmountPerExecution int64, amountPerExecution int64, executionCount int64) {
	if amountPerExecution < minAmountPerExecution {
		panic(makeErrorWithDetails(
			errInvalidAmount,
			ufmt.Sprintf("amountPerExecution(%d) must be >= %d", amountPerExecution, minAmountPerExecution),
		).Error())
	}

	if executionCount <= 0 || executionCount > config.MaxExecutionCount() {
		panic(makeErrorWithDetails(
			errInvalidExecutionCount,
			ufmt.Sprintf("executionCount(%d) must be in [1, %d]", executionCount, config.MaxExecutionCount()),
		).Error())
	}
}

// assertIsOrderOwner checks that caller owns the order.
func assertIsOrderOwner(order *pdca.Order, caller address) {
	if order.Owner() != caller {
		panic(makeErrorWithDetails(errNotOrderOwner, ufmt.Sprintf("orderId(%d)", order.ID())).Error())
	}
}

// assertIsQuotedAmountIn checks that the round sells the input
// amountOutMin was quoted for.
// A floor quoted for a larger input would keep that trade's price impact,
// which is looser than the smaller round needs, so a changed orderAmount
// needs a new quote instead of a rescaled floor.
// Passing 0 for both skips the check.
func assertIsQuotedAmountIn(group *pdca.Group, expectedAmountIn int64, amountOutMin int64) {
	if expectedAmountIn == 0 && amountOutMin == 0 {
		return
	}

	if expectedAmountIn != group.OrderAmount() {
		panic(makeErrorWithDetails(
			errAmountInMismatch,
			ufmt.Sprintf("groupId(%s) expectedAmountIn(%d) orderAmount(%d)", group.ID(), expectedAmountIn, group.OrderAmount()),
		).Error())
	}
}

claim_group_orders.gno

package impl

import (
	"gno.land/p/gnoswap/gnsmath/v1"
	pdca "gno.land/p/gnoswap/order/dca/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/order/halt"
)

// ClaimGroupOrders pays accrued output to the owners of a group's active
// orders, like Claim, so owners receive output without claiming.
// Anyone may call it; output always goes to the order owner.
//
// The call releases each examined order's execution logs whose rounds all executed
// and deletes finished orders. The freed storage deposit is refunded to the
// caller, a fixed reward per log of three executed rounds.
//
// One call examines at most min(maxOrderCount, maxClaimBatchSize) orders
// after startAfterOrderID, in ID order, so its gas stays bounded.
// The returned cursor is the last examined order ID; pass it back until it
// is 0. New orders get higher IDs and finished orders leave the index,
// so changes between calls neither skip nor repeat an order.
func (d *dcaOrderImpl) ClaimGroupOrders(_ int, rlm realm, groupID string, startAfterOrderID uint64, maxOrderCount int) (int, uint64) {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()
	assertIsNotHalted(halt.OperationWithdraw)
	d.assertIsNotExecuting()

	if maxOrderCount <= 0 {
		panic(makeErrorWithDetails(errInvalidAmount, ufmt.Sprintf("maxOrderCount(%d) must be positive", maxOrderCount)).Error())
	}

	group, err := d.getGroup(groupID)
	if err != nil {
		panic(err.Error())
	}

	prev := rlm.Previous()

	result, err := d.claimGroupOrders(0, rlm, prev.Address(), prev.PkgPath(), group, startAfterOrderID, maxOrderCount)
	if err != nil {
		panic(err.Error())
	}

	emitGroupOrdersClaimed(
		prev.Address(),
		prev.PkgPath(),
		groupID,
		result.examinedOrderCount,
		result.claimedOrderCount,
		result.releasedExecutionLogCount,
		result.nextCursor,
	)

	emitPayoutExecutionFee(prev.Address(), prev.PkgPath(), group, result.executionFeeAmount, d.pendingExecutionFeeAmount(group.OutputToken()))

	return result.claimedOrderCount, result.nextCursor
}

// groupOrdersClaimResult describes one page of claimGroupOrders.
type groupOrdersClaimResult struct {
	examinedOrderCount        int
	claimedOrderCount         int    // orders paid or completed
	releasedExecutionLogCount int64  // order logs freed for the caller
	executionFeeAmount        int64  // execution fee the payouts kept as pending
	nextCursor                uint64 // last examined order ID, 0 when the group is done
}

// claimGroupOrders claims one page of the group's orders.
func (d *dcaOrderImpl) claimGroupOrders(
	_ int,
	rlm realm,
	prevAddr address,
	prevRealm string,
	group *pdca.Group,
	startAfterOrderID uint64,
	maxOrderCount int,
) (groupOrdersClaimResult, error) {
	limit := int64(maxOrderCount)
	if maxClaimBatchSize := d.store.GetConfig().MaxClaimBatchSize(); limit > maxClaimBatchSize {
		limit = maxClaimBatchSize
	}

	orderIDs, hasMore := d.getGroupOrderIDs(group.ID(), startAfterOrderID, int(limit))

	result := groupOrdersClaimResult{examinedOrderCount: len(orderIDs)}
	for _, orderID := range orderIDs {
		order, err := d.getOrder(orderID)
		if err != nil {
			return groupOrdersClaimResult{}, err
		}

		payout, releasedCount, isUpdated, err := d.claimOrder(0, rlm, prevAddr, prevRealm, order, group)
		if err != nil {
			return groupOrdersClaimResult{}, err
		}

		result.executionFeeAmount = gnsmath.SafeAddInt64(result.executionFeeAmount, payout.executionFeeAmount)

		result.releasedExecutionLogCount = gnsmath.SafeAddInt64(result.releasedExecutionLogCount, releasedCount)

		if isUpdated {
			result.claimedOrderCount++
		}
	}

	if hasMore {
		result.nextCursor = orderIDs[len(orderIDs)-1]
	}

	return result, nil
}

// getGroupOrderIDs returns up to count active order IDs of a group after
// startAfterID, and whether more remain. IDs are collected before any
// order is claimed, since a claim may remove entries from the index.
func (d *dcaOrderImpl) getGroupOrderIDs(groupID string, startAfterID uint64, count int) ([]uint64, bool) {
	if startAfterID == ^uint64(0) {
		return nil, false
	}

	prefix := pdca.GroupOrderPrefix(groupID)
	start := pdca.GroupOrderKey(groupID, gnsmath.SafeAddUint64(startAfterID, 1))

	orderIDs := []uint64{}
	hasMore := false

	d.store.GetOrdersByGroup().Iterate(start, pdca.PrefixEnd(prefix), func(_ string, value any) bool {
		if len(orderIDs) == count {
			hasMore = true
			return true
		}

		orderIDs = append(orderIDs, value.(uint64))

		return false
	})

	return orderIDs, hasMore
}

config.gno

package impl

import (
	pdca "gno.land/p/gnoswap/order/dca/v0"
	ufmt "gno.land/p/nt/ufmt/v0"
)

// SetOrderLimits sets the minimum input per execution
// and the maximum executions per order.
// Existing orders are unaffected. Admin or governance only.
func (d *dcaOrderImpl) SetOrderLimits(_ int, rlm realm, minAmountPerExecution int64, maxExecutionCount int64) {
	prev := d.assertIsAdminCall(0, rlm)

	if minAmountPerExecution <= 0 {
		panic(makeErrorWithDetails(
			errInvalidConfig,
			ufmt.Sprintf("minAmountPerExecution(%d) must be positive", minAmountPerExecution),
		).Error())
	}

	if maxExecutionCount <= 0 || maxExecutionCount > maxExecutionCountLimit {
		panic(makeErrorWithDetails(
			errInvalidConfig,
			ufmt.Sprintf("maxExecutionCount(%d) must be in [1, %d]", maxExecutionCount, maxExecutionCountLimit),
		).Error())
	}

	config := d.store.GetConfig()
	previousMinAmountPerExecution := config.MinAmountPerExecution()
	previousMaxExecutionCount := config.MaxExecutionCount()
	config.SetMinAmountPerExecution(minAmountPerExecution)
	config.SetMaxExecutionCount(maxExecutionCount)

	emitConfigUpdated(prev.Address(), prev.PkgPath(), "minAmountPerExecution", previousMinAmountPerExecution, minAmountPerExecution)
	emitConfigUpdated(prev.Address(), prev.PkgPath(), "maxExecutionCount", previousMaxExecutionCount, maxExecutionCount)
}

// AddAllowedInterval allows new orders to use interval.
// Admin or governance only.
func (d *dcaOrderImpl) AddAllowedInterval(_ int, rlm realm, interval int64) {
	prev := d.assertIsAdminCall(0, rlm)

	if interval < minAllowedInterval || interval > maxAllowedInterval {
		panic(makeErrorWithDetails(
			errInvalidInterval,
			ufmt.Sprintf("interval(%d) must be in [%d, %d]", interval, minAllowedInterval, maxAllowedInterval),
		).Error())
	}

	if err := d.store.GetConfig().AddAllowedInterval(interval); err != nil {
		panic(makeErrorWithDetails(errInvalidInterval, ufmt.Sprintf("interval(%d): %s", interval, err.Error())).Error())
	}

	emitAllowedIntervalUpdated(prev.Address(), prev.PkgPath(), interval, true)
}

// RemoveAllowedInterval stops new orders from using interval.
// Existing orders and groups of that interval keep running.
// At least one interval must stay allowed. Admin or governance only.
func (d *dcaOrderImpl) RemoveAllowedInterval(_ int, rlm realm, interval int64) {
	prev := d.assertIsAdminCall(0, rlm)

	config := d.store.GetConfig()
	if len(config.AllowedIntervals()) == 1 && config.IsAllowedInterval(interval) {
		panic(makeErrorWithDetails(errInvalidConfig, "at least one interval must stay allowed").Error())
	}

	if err := config.RemoveAllowedInterval(interval); err != nil {
		panic(makeErrorWithDetails(errInvalidInterval, ufmt.Sprintf("interval(%d): %s", interval, err.Error())).Error())
	}

	emitAllowedIntervalUpdated(prev.Address(), prev.PkgPath(), interval, false)
}

// SetMinExecutionGapRate sets the minimum gap between a group's executions,
// in basis points of its interval. Admin or governance only.
func (d *dcaOrderImpl) SetMinExecutionGapRate(_ int, rlm realm, minExecutionGapRate int64) {
	prev := d.assertIsAdminCall(0, rlm)

	if minExecutionGapRate < 0 || minExecutionGapRate > pdca.BasisPointDenominator {
		panic(makeErrorWithDetails(
			errInvalidConfig,
			ufmt.Sprintf("minExecutionGapRate(%d) must be in [0, %d]", minExecutionGapRate, pdca.BasisPointDenominator),
		).Error())
	}

	config := d.store.GetConfig()
	previousMinExecutionGapRate := config.MinExecutionGapRate()
	config.SetMinExecutionGapRate(minExecutionGapRate)

	emitConfigUpdated(prev.Address(), prev.PkgPath(), "minExecutionGapRate", previousMinExecutionGapRate, minExecutionGapRate)
}

// 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 to 10000; 0 disables the check). Admin or governance only.
func (d *dcaOrderImpl) SetMaxPoolPriceDeviationRate(_ int, rlm realm, maxPoolPriceDeviationRate int64) {
	prev := d.assertIsAdminCall(0, rlm)

	if maxPoolPriceDeviationRate < 0 || maxPoolPriceDeviationRate > pdca.BasisPointDenominator {
		panic(makeErrorWithDetails(
			errInvalidConfig,
			ufmt.Sprintf("maxPoolPriceDeviationRate(%d) must be in [0, %d]", maxPoolPriceDeviationRate, pdca.BasisPointDenominator),
		).Error())
	}

	config := d.store.GetConfig()
	previousMaxPoolPriceDeviationRate := config.MaxPoolPriceDeviationRate()
	config.SetMaxPoolPriceDeviationRate(maxPoolPriceDeviationRate)

	emitConfigUpdated(
		prev.Address(),
		prev.PkgPath(),
		"maxPoolPriceDeviationRate",
		previousMaxPoolPriceDeviationRate,
		maxPoolPriceDeviationRate,
	)
}

// SetMaxPairPriceLimitAge sets how long, in seconds, a pair price limit stays
// usable after the pool manager set it (60 to 604800). A quote or round under
// an older limit finds no eligible pool, so rounds stop when the manager stops
// refreshing limits instead of trading at a stale price. Admin or governance only.
func (d *dcaOrderImpl) SetMaxPairPriceLimitAge(_ int, rlm realm, maxPairPriceLimitAge int64) {
	prev := d.assertIsAdminCall(0, rlm)

	if maxPairPriceLimitAge < minMaxPairPriceLimitAge || maxPairPriceLimitAge > maxMaxPairPriceLimitAge {
		panic(makeErrorWithDetails(
			errInvalidConfig,
			ufmt.Sprintf("maxPairPriceLimitAge(%d) must be in [%d, %d]", maxPairPriceLimitAge, minMaxPairPriceLimitAge, maxMaxPairPriceLimitAge),
		).Error())
	}

	config := d.store.GetConfig()
	previousMaxPairPriceLimitAge := config.MaxPairPriceLimitAge()
	config.SetMaxPairPriceLimitAge(maxPairPriceLimitAge)

	emitConfigUpdated(prev.Address(), prev.PkgPath(), "maxPairPriceLimitAge", previousMaxPairPriceLimitAge, maxPairPriceLimitAge)
}

// SetMaxClaimBatchSize caps the orders one ClaimGroupOrders call examines.
// Admin or governance only.
func (d *dcaOrderImpl) SetMaxClaimBatchSize(_ int, rlm realm, maxClaimBatchSize int64) {
	prev := d.assertIsAdminCall(0, rlm)

	if maxClaimBatchSize <= 0 || maxClaimBatchSize > maxClaimBatchSizeLimit {
		panic(makeErrorWithDetails(
			errInvalidConfig,
			ufmt.Sprintf("maxClaimBatchSize(%d) must be in [1, %d]", maxClaimBatchSize, maxClaimBatchSizeLimit),
		).Error())
	}

	config := d.store.GetConfig()
	previousMaxClaimBatchSize := config.MaxClaimBatchSize()
	config.SetMaxClaimBatchSize(maxClaimBatchSize)

	emitConfigUpdated(prev.Address(), prev.PkgPath(), "maxClaimBatchSize", previousMaxClaimBatchSize, maxClaimBatchSize)
}

// SetSlotStep sets the spacing of the slot offsets new orders may use
// at interval. Existing groups keep their slot.
// Admin or governance only.
func (d *dcaOrderImpl) SetSlotStep(_ int, rlm realm, interval int64, slotStep int64) {
	prev := d.assertIsAdminCall(0, rlm)

	config := d.store.GetConfig()
	assertIsAllowedInterval(config, interval)
	previousSlotStep := config.SlotStep(interval)

	if err := config.SetSlotStep(interval, slotStep); err != nil {
		panic(makeErrorWithDetails(
			errInvalidSlotStep,
			ufmt.Sprintf("slotStep(%d) must be a positive divisor of interval(%d)", slotStep, interval),
		).Error())
	}

	emitSlotStepChanged(prev.Address(), prev.PkgPath(), interval, previousSlotStep, slotStep)
}

consts.gno

package impl

const (
	dcaBPTreeFanOut int = 16

	// maxExecutionCountLimit bounds the configurable executions per order,
	// so cancelling an order releases its execution logs within one block.
	maxExecutionCountLimit int64 = 10_000

	// Bounds of an allowed interval: one minute to one year.
	minAllowedInterval int64 = 60
	maxAllowedInterval int64 = 365 * 24 * 60 * 60

	// maxClaimBatchSizeLimit bounds the configurable ClaimGroupOrders batch.
	maxClaimBatchSizeLimit int64 = 500

	// minOrderAmountOutFloor is the least output a round credits each of
	// its orders, whatever minOrderAmountOut ExecuteGroup is given.
	minOrderAmountOutFloor int64 = 1

	defaultMinAmountPerExecution int64 = 1
	defaultMaxExecutionCount     int64 = 1_000
	defaultMaxClaimBatchSize     int64 = 50
	defaultExecutionFeeRate      int64 = 15 // basis points

	// Starting execution gap: half an interval; tune per deployment.
	defaultMinExecutionGapRate int64 = 5_000

	// defaultMaxPoolPriceDeviationRate is the starting
	// Config.MaxPoolPriceDeviationRate: 20%, in basis points of price.
	defaultMaxPoolPriceDeviationRate int64 = 2_000

	// defaultMaxPairPriceLimitAge is the starting Config.MaxPairPriceLimitAge:
	// one hour, in seconds.
	defaultMaxPairPriceLimitAge int64 = 60 * 60

	// Bounds of Config.MaxPairPriceLimitAge: one minute to seven days.
	minMaxPairPriceLimitAge int64 = 60
	maxMaxPairPriceLimitAge int64 = 7 * 24 * 60 * 60
)

// Intervals new orders may use after deployment, in seconds.
// A month is a fixed 30 days, so every round in a group has the same length.
const (
	intervalMinute int64 = 60
	intervalHour   int64 = 60 * intervalMinute
	intervalDay    int64 = 24 * intervalHour
	intervalWeek   int64 = 7 * intervalDay
	intervalMonth  int64 = 30 * intervalDay
)

// defaultAllowedIntervals returns the initial allowed intervals, ascending.
func defaultAllowedIntervals() []int64 {
	return []int64{intervalMinute, intervalHour, intervalDay, intervalWeek, intervalMonth}
}

// defaultSlotSteps returns the initial slot step of the intervals split
// into several slots: daily orders pick an hour, weekly and 30-day orders
// a day. A 30-day slot is a day of the 30-day cycle counted from the unix
// epoch, not a calendar date.
// Minute and hourly orders keep a single slot, offset 0: finer slots would
// split liquidity for little gain.
// Each slot is its own group, so the steps bound the groups per pair.
func defaultSlotSteps() map[int64]int64 {
	return map[int64]int64{
		intervalDay:   intervalHour,
		intervalWeek:  intervalDay,
		intervalMonth: intervalDay,
	}
}

doc.gno

// Package impl is the v0 implementation of the GnoSwap DCA order realm.
// It registers itself with gno.land/r/gnoswap/order/dca at init.
//
// Files:
//   - order.gno: CreateOrder, CancelOrder, Claim, ForceCancelOrder
//   - execute.gno: ExecuteGroup and the pool swap; rounds credit gross output
//   - execution_fee.gno: SetExecutionFeeRate, pending payout fees, and forwarding them to the protocol fee realm
//   - pool_selection.gno: choosing the pool of a round
//   - swap.gno: the pool swap of a round and its callback
//   - manager.gno: per-token minimum order sizes and pair price limits
//   - price_limit.gno: converting a pair price limit to a swap price limit
//   - claim_group_orders.gno: ClaimGroupOrders
//   - config.gno: admin configuration and slot steps
//   - getter.gno: read-only queries
//   - assert.gno, utils.gno: shared checks and helpers
//
// The executed amount is protected by the pair price limit the pool manager
// sets from an oracle price, which every quote and swap passes to the pool as
// its price limit, by the best-quote pool selection, and by the keeper's
// amountOutMin, quoted for the round's input. The price limit also bounds the
// ticks a quote or swap crosses, and so its gas. The execution gap keeps
// a group's next execution at least minExecutionGapRate of its interval after
// the previous one, even after a late execution.
// A round reverts unless it credits each of its orders at least the keeper's
// minOrderAmountOut, and never less than one unit, of output after its own
// execution fee rate. The order amount index sorts orders by fee rate, then
// amount, so the smallest order of each fee rate bounds every order of that rate.
// Roles: gno.land/r/gnoswap/order/keeper restricts executions and force cancellations
// to DCAKeeperRole, and the shared pool whitelist, token minimums, and price
// limits to PoolManagerRole, at deployment.
//
// Keepers earn storage deposits: each order stores one execution log per
// three rounds at creation, paid by its owner. Claim and ClaimGroupOrders
// release the order's logs whose rounds all executed and delete finished
// orders, which refunds the freed deposit to the transaction signer.
package impl

emits.gno

package impl

import (
	"chain"

	pdca "gno.land/p/gnoswap/order/dca/v0"
	"gno.land/p/gnoswap/utils/v1"
)

// Events carry the accumulator state
// (accumulatedOutputPerAmountX128, round, orderAmount) and each order's
// payout state, so indexers can compute claimable amounts without querying
// state. The accumulator is gross of execution fees:
//
//	gross = amountPerExecution * (acc(min(round, endRound)) - debtX128) / 2^128
//	paid  = totalClaimedAmount + totalExecutionFeeAmount
//	fee   = floor((paid + gross) * executionFeeRate / 10000) - floor(paid * executionFeeRate / 10000)
//	claimable = gross - fee

func emitGroupCreated(prevAddr address, prevRealm string, group *pdca.Group) {
	chain.Emit(
		"DCAGroupCreated",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"groupId", group.ID(),
		"inputToken", group.InputToken(),
		"outputToken", group.OutputToken(),
		"interval", utils.FormatInt(group.Interval()),
		"slotOffset", utils.FormatInt(group.SlotOffset()),
		"nextExecutionTimestamp", utils.FormatInt(group.NextExecutionTimestamp()),
	)
}

// emitOrderCreated reports a new order. executionFeeRate is the rate the
// order snapshotted. referenceAmountOut is the output of selling the whole
// deposit at once when the order was placed, net of the order's execution
// fee (see quoteReferenceAmountOut), 0 when no pool could absorb it.
func emitOrderCreated(
	prevAddr address,
	prevRealm string,
	order *pdca.Order,
	group *pdca.Group,
	depositAmount int64,
	referenceAmountOut int64,
) {
	chain.Emit(
		"DCAOrderCreated",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"orderId", utils.FormatUint(order.ID()),
		"owner", order.Owner().String(),
		"groupId", order.GroupID(),
		"inputToken", group.InputToken(),
		"outputToken", group.OutputToken(),
		"interval", utils.FormatInt(group.Interval()),
		"slotOffset", utils.FormatInt(group.SlotOffset()),
		"amountPerExecution", utils.FormatInt(order.AmountPerExecution()),
		"executionCount", utils.FormatInt(order.ExecutionCount()),
		"executionFeeRate", utils.FormatInt(order.ExecutionFeeRate()),
		"depositAmount", utils.FormatInt(depositAmount),
		"startRound", utils.FormatUint(order.StartRound()),
		"endRound", utils.FormatUint(order.EndRound()),
		"debtX128", order.DebtX128().ToString(),
		"executionLogCount", utils.FormatInt(order.ExecutionLogCount()),
		"groupOrderAmount", utils.FormatInt(group.OrderAmount()),
		"groupNextExecutionTimestamp", utils.FormatInt(group.NextExecutionTimestamp()),
		"referenceAmountOut", utils.FormatInt(referenceAmountOut),
	)
}

// emitGroupExecuted reports a round. executedAmountOut, the output credited
// to the orders, equals swapAmountOut: orders pay their execution fees when
// paid out.
func emitGroupExecuted(prevAddr address, prevRealm string, group *pdca.Group, result groupRoundResult) {
	chain.Emit(
		"DCAGroupExecuted",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"groupId", group.ID(),
		"poolPath", result.poolPath,
		"inputToken", group.InputToken(),
		"outputToken", group.OutputToken(),
		"round", utils.FormatUint(group.Round()),
		"executedAmountIn", utils.FormatInt(result.executedAmountIn),
		"swapAmountOut", utils.FormatInt(result.swapAmountOut),
		"executedAmountOut", utils.FormatInt(result.executedAmountOut),
		"accumulatedOutputPerAmountX128", group.AccumulatedOutputPerAmountX128().ToString(),
		"endedOrderAmount", utils.FormatInt(result.endedOrderAmount),
		"nextOrderAmount", utils.FormatInt(group.OrderAmount()),
		"scheduledTimestamp", utils.FormatInt(result.scheduledTimestamp),
		"executionTimestamp", utils.FormatInt(result.executionTimestamp),
		"nextExecutionTimestamp", utils.FormatInt(group.NextExecutionTimestamp()),
	)
}

func emitGroupOrdersClaimed(
	prevAddr address,
	prevRealm string,
	groupID string,
	examinedOrderCount int,
	claimedOrderCount int,
	releasedExecutionLogCount int64,
	nextCursor uint64,
) {
	chain.Emit(
		"DCAGroupOrdersClaimed",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"groupId", groupID,
		"examinedOrderCount", utils.FormatInt(int64(examinedOrderCount)),
		"claimedOrderCount", utils.FormatInt(int64(claimedOrderCount)),
		"releasedExecutionLogCount", utils.FormatInt(releasedExecutionLogCount),
		"nextCursor", utils.FormatUint(nextCursor),
	)
}

// emitOrderClaimed reports a payout. grossAmount is the accrued output paid
// out, executionFeeAmount the order's fee on it, and claimedAmount the rest,
// sent to the owner; the totals are the order's lifetime values.
func emitOrderClaimed(
	prevAddr address,
	prevRealm string,
	order *pdca.Order,
	group *pdca.Group,
	payout orderPayout,
	status pdca.OrderStatus,
) {
	chain.Emit(
		"DCAOrderClaimed",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"orderId", utils.FormatUint(order.ID()),
		"owner", order.Owner().String(),
		"groupId", order.GroupID(),
		"outputToken", group.OutputToken(),
		"grossAmount", utils.FormatInt(payout.grossAmount),
		"executionFeeRate", utils.FormatInt(order.ExecutionFeeRate()),
		"executionFeeAmount", utils.FormatInt(payout.executionFeeAmount),
		"claimedAmount", utils.FormatInt(payout.claimedAmount),
		"totalClaimedAmount", order.ClaimedAmount().ToString(),
		"totalExecutionFeeAmount", order.ExecutionFeeAmount().ToString(),
		"debtX128", order.DebtX128().ToString(),
		"status", status.String(),
	)
}

func emitOrderCancelled(
	prevAddr address,
	prevRealm string,
	order *pdca.Order,
	group *pdca.Group,
	payout orderPayout,
	refundedAmount int64,
) {
	chain.Emit(
		"DCAOrderCancelled",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"orderId", utils.FormatUint(order.ID()),
		"owner", order.Owner().String(),
		"groupId", order.GroupID(),
		"inputToken", group.InputToken(),
		"outputToken", group.OutputToken(),
		"refundedAmount", utils.FormatInt(refundedAmount),
		"grossAmount", utils.FormatInt(payout.grossAmount),
		"executionFeeRate", utils.FormatInt(order.ExecutionFeeRate()),
		"executionFeeAmount", utils.FormatInt(payout.executionFeeAmount),
		"claimedAmount", utils.FormatInt(payout.claimedAmount),
		"totalClaimedAmount", order.ClaimedAmount().ToString(),
		"totalExecutionFeeAmount", order.ExecutionFeeAmount().ToString(),
		"debtX128", order.DebtX128().ToString(),
		"status", pdca.OrderStatusCancelled.String(),
		"cancelRound", utils.FormatUint(group.Round()),
		"groupOrderAmount", utils.FormatInt(group.OrderAmount()),
	)
}

// emitPayoutExecutionFee reports the execution fee a payout of the group's
// orders charged and kept as pending, if any.
func emitPayoutExecutionFee(prevAddr address, prevRealm string, group *pdca.Group, executionFeeAmount int64, pendingAmount int64) {
	if executionFeeAmount <= 0 {
		return
	}

	emitExecutionFeeCollected(prevAddr, prevRealm, group.ID(), group.OutputToken(), group.Round(), executionFeeAmount, 0, pendingAmount)
}

// emitExecutionFeeCollected reports execution fees of tokenPath.
// executionFeeAmount is the fee payouts charged (0 for a round or
// CollectPendingExecutionFee), forwardedAmount what was sent to the protocol
// fee realm, and pendingAmount what this realm still holds.
// groupId is empty and round 0 for CollectPendingExecutionFee.
func emitExecutionFeeCollected(
	prevAddr address,
	prevRealm string,
	groupID string,
	tokenPath string,
	round uint64,
	executionFeeAmount int64,
	forwardedAmount int64,
	pendingAmount int64,
) {
	chain.Emit(
		"DCAExecutionFeeCollected",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"groupId", groupID,
		"tokenPath", tokenPath,
		"round", utils.FormatUint(round),
		"executionFeeAmount", utils.FormatInt(executionFeeAmount),
		"forwardedAmount", utils.FormatInt(forwardedAmount),
		"pendingAmount", utils.FormatInt(pendingAmount),
	)
}

func emitExecutionFeeRateChanged(prevAddr address, prevRealm string, previousExecutionFeeRate int64, executionFeeRate int64) {
	chain.Emit(
		"DCAExecutionFeeRateChanged",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"previousExecutionFeeRate", utils.FormatInt(previousExecutionFeeRate),
		"executionFeeRate", utils.FormatInt(executionFeeRate),
	)
}

func emitSlotStepChanged(prevAddr address, prevRealm string, interval int64, previousSlotStep int64, slotStep int64) {
	chain.Emit(
		"DCASlotStepChanged",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"interval", utils.FormatInt(interval),
		"previousSlotStep", utils.FormatInt(previousSlotStep),
		"slotStep", utils.FormatInt(slotStep),
	)
}

func emitExecutionLogsReleased(prevAddr address, prevRealm string, order *pdca.Order, group *pdca.Group, releasedExecutionLogCount int64) {
	chain.Emit(
		"DCAExecutionLogsReleased",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"orderId", utils.FormatUint(order.ID()),
		"groupId", group.ID(),
		"round", utils.FormatUint(group.Round()),
		"releasedExecutionLogCount", utils.FormatInt(releasedExecutionLogCount),
		"remainingExecutionLogCount", utils.FormatInt(order.ExecutionLogCount()),
	)
}

func emitConfigUpdated(prevAddr address, prevRealm string, key string, previousValue int64, value int64) {
	chain.Emit(
		"DCAConfigUpdated",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"key", key,
		"previousValue", utils.FormatInt(previousValue),
		"value", utils.FormatInt(value),
	)
}

func emitAllowedIntervalUpdated(prevAddr address, prevRealm string, interval int64, allowed bool) {
	chain.Emit(
		"DCAAllowedIntervalUpdated",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"interval", utils.FormatInt(interval),
		"allowed", utils.FormatBool(allowed),
	)
}

// emitOrderForceCancelled reports an order closed by a keeper with ForceCancelOrder.
// It carries the fields of DCAOrderCancelled and the reason the order blocked
// its group (see ForceCancelOrder); the order's status is
// cancelled, and its output and refund went to the owner.
func emitOrderForceCancelled(
	prevAddr address,
	prevRealm string,
	order *pdca.Order,
	group *pdca.Group,
	payout orderPayout,
	refundedAmount int64,
	reason string,
) {
	chain.Emit(
		"DCAOrderForceCancelled",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"orderId", utils.FormatUint(order.ID()),
		"owner", order.Owner().String(),
		"groupId", order.GroupID(),
		"inputToken", group.InputToken(),
		"outputToken", group.OutputToken(),
		"refundedAmount", utils.FormatInt(refundedAmount),
		"grossAmount", utils.FormatInt(payout.grossAmount),
		"executionFeeRate", utils.FormatInt(order.ExecutionFeeRate()),
		"executionFeeAmount", utils.FormatInt(payout.executionFeeAmount),
		"claimedAmount", utils.FormatInt(payout.claimedAmount),
		"totalClaimedAmount", order.ClaimedAmount().ToString(),
		"totalExecutionFeeAmount", order.ExecutionFeeAmount().ToString(),
		"debtX128", order.DebtX128().ToString(),
		"status", pdca.OrderStatusCancelled.String(),
		"cancelRound", utils.FormatUint(group.Round()),
		"groupOrderAmount", utils.FormatInt(group.OrderAmount()),
		"reason", reason,
	)
}

func emitTokenMinAmountPerExecutionUpdated(
	prevAddr address,
	prevRealm string,
	tokenPath string,
	previousMinAmountPerExecution int64,
	minAmountPerExecution int64,
) {
	chain.Emit(
		"DCATokenMinAmountPerExecutionUpdated",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"tokenPath", tokenPath,
		"prevMinAmountPerExecution", utils.FormatInt(previousMinAmountPerExecution),
		"minAmountPerExecution", utils.FormatInt(minAmountPerExecution),
	)
}

// emitPairPriceLimitUpdated reports a pair price limit change;
// minOutputPerInputX128 "0" and updatedAt 0 mean the limit was removed.
func emitPairPriceLimitUpdated(
	prevAddr address,
	prevRealm string,
	inputToken string,
	outputToken string,
	previousMinOutputPerInputX128 string,
	minOutputPerInputX128 string,
	updatedAt int64,
) {
	chain.Emit(
		"DCAPairPriceLimitUpdated",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"inputToken", inputToken,
		"outputToken", outputToken,
		"prevMinOutputPerInputX128", previousMinOutputPerInputX128,
		"minOutputPerInputX128", minOutputPerInputX128,
		"updatedAt", utils.FormatInt(updatedAt),
	)
}

errors.gno

package impl

import (
	ufmt "gno.land/p/nt/ufmt/v0"
)

const (
	errInvalidPool             = "[GNOSWAP-ORDER-DCA-001] invalid pool"
	errInvalidToken            = "[GNOSWAP-ORDER-DCA-002] invalid token"
	errInvalidInterval         = "[GNOSWAP-ORDER-DCA-003] invalid interval"
	errInvalidAmount           = "[GNOSWAP-ORDER-DCA-004] invalid amount"
	errInvalidExecutionCount   = "[GNOSWAP-ORDER-DCA-005] invalid number of executions"
	errOrderNotFound           = "[GNOSWAP-ORDER-DCA-006] order not found"
	errNotOrderOwner           = "[GNOSWAP-ORDER-DCA-007] caller is not the order owner"
	errGroupNotFound           = "[GNOSWAP-ORDER-DCA-008] group not found"
	errGroupNotExecutable      = "[GNOSWAP-ORDER-DCA-009] group is not executable"
	errSwapMismatch            = "[GNOSWAP-ORDER-DCA-010] swap result mismatch"
	errInvalidConfig           = "[GNOSWAP-ORDER-DCA-011] invalid config"
	errInvalidState            = "[GNOSWAP-ORDER-DCA-012] invalid accounting state"
	errOverflow                = "[GNOSWAP-ORDER-DCA-013] overflow"
	errReentrant               = "[GNOSWAP-ORDER-DCA-014] reentrant call during group execution"
	errInvalidCursor           = "[GNOSWAP-ORDER-DCA-015] invalid cursor"
	errNotKeeper               = "[GNOSWAP-ORDER-DCA-016] caller is not an authorized keeper"
	errNoEligiblePool          = "[GNOSWAP-ORDER-DCA-017] no eligible pool"
	errInvalidExecutionFeeRate = "[GNOSWAP-ORDER-DCA-018] invalid execution fee rate"
	errInvalidSlotOffset       = "[GNOSWAP-ORDER-DCA-019] invalid slot offset"
	errInvalidSlotStep         = "[GNOSWAP-ORDER-DCA-020] invalid slot step"
	errHalted                  = "[GNOSWAP-ORDER-DCA-021] operation halted"
	errAmountInMismatch        = "[GNOSWAP-ORDER-DCA-022] round input does not match the quote"
	errInsufficientOrderOutput = "[GNOSWAP-ORDER-DCA-024] insufficient output per order"
	errInsufficientSwapOutput  = "[GNOSWAP-ORDER-DCA-025] swap output below amountOutMin"
	errInvalidPriceLimit       = "[GNOSWAP-ORDER-DCA-026] invalid price limit"
	errMissingPriceLimit       = "[GNOSWAP-ORDER-DCA-027] missing price limit"
	errOrderNotBlocking        = "[GNOSWAP-ORDER-DCA-028] order does not block its group"
)

func makeErrorWithDetails(message string, details string) error {
	return ufmt.Errorf("%s || %s", message, details)
}

execute.gno

package impl

import (
	"time"

	"gno.land/p/gnoswap/gnsmath/v1"
	pdca "gno.land/p/gnoswap/order/dca/v0"
	u256 "gno.land/p/gnoswap/uint256/v1"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/order/halt"
	"gno.land/r/gnoswap/order/whitelist"
)

// ExecuteGroup sells one round of a group with a pool swap
// and credits the swap output to the group accumulator.
// Each order's execution fee is deducted when the order is paid out;
// the round forwards the fee already pending for its output token.
// Only keepers allowed by gno.land/r/gnoswap/order/keeper may call it
// (DCAKeeperRole at deployment): the schedule and the swap result are checked on-chain,
// and a failed swap reverts so the round can be retried.
// minOrderAmountOut, raised to minOrderAmountOutFloor, is the least output
// every order of the round must be credited.
func (d *dcaOrderImpl) ExecuteGroup(
	_ int,
	rlm realm,
	groupID string,
	expectedAmountIn int64,
	amountOutMin int64,
	minOrderAmountOut int64,
) (int64, int64) {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()
	assertIsNotHalted(halt.OperationExecute, halt.OperationWithdraw)
	d.assertIsNotExecuting()

	if amountOutMin < 0 || expectedAmountIn < 0 || minOrderAmountOut < 0 {
		panic(makeErrorWithDetails(
			errInvalidAmount,
			ufmt.Sprintf(
				"expectedAmountIn(%d) amountOutMin(%d) minOrderAmountOut(%d)",
				expectedAmountIn, amountOutMin, minOrderAmountOut,
			),
		).Error())
	}

	if minOrderAmountOut < minOrderAmountOutFloor {
		minOrderAmountOut = minOrderAmountOutFloor
	}

	prev := rlm.Previous()
	assertIsAuthorizedKeeper(rlm.PkgPath(), prev.Address())

	group, err := d.getGroup(groupID)
	if err != nil {
		panic(err.Error())
	}

	currentTimestamp := time.Now().Unix()

	result, err := d.executeGroupRound(0, rlm, group, expectedAmountIn, amountOutMin, minOrderAmountOut, currentTimestamp)
	if err != nil {
		panic(err.Error())
	}

	emitGroupExecuted(prev.Address(), prev.PkgPath(), group, result)

	if result.forwardedExecutionFeeAmount > 0 || result.pendingExecutionFeeAmount > 0 {
		emitExecutionFeeCollected(
			prev.Address(),
			prev.PkgPath(),
			group.ID(),
			group.OutputToken(),
			group.Round(),
			0,
			result.forwardedExecutionFeeAmount,
			result.pendingExecutionFeeAmount,
		)
	}

	return result.executedAmountIn, result.executedAmountOut
}

// groupRoundResult describes one executed round.
type groupRoundResult struct {
	poolPath           string
	scheduledTimestamp int64
	executionTimestamp int64
	executedAmountIn   int64 // input sold, the group orderAmount
	swapAmountOut      int64 // pool output of the round
	executedAmountOut  int64 // output credited to the orders, before their execution fees
	endedOrderAmount   int64 // orderAmount of the orders whose last round this was

	forwardedExecutionFeeAmount int64 // pending execution fee sent to the protocol fee realm
	pendingExecutionFeeAmount   int64 // execution fee still held by this realm
}

// executeGroupRound runs the group's next round: it checks the schedule
// and the quoted input, picks the pool, swaps the whole round input within
// the pair price limit, and credits the pool output (swapAmountOut) to the
// accumulator per unit of the round input.
//
// The round charges no fee itself. Each order's execution fee is its own
// snapshotted executionFeeRate of its gross output, deducted when the order
// is paid out (Claim, ClaimGroupOrders, CancelOrder, ForceCancelOrder) and
// held as pending. The round forwards the fee pending for its output token to
// the protocol fee realm, so the fee still costs one transfer per round
// instead of one per order.
//
// Every order of the round must be credited at least minOrderAmountOut of
// output after its own execution fee rate. A round that cannot
// pay its smallest order that much is treated as lacking liquidity: it
// reverts, like a failed swap, so it can be retried.
//
// Checks-effects-interactions:
// the round, schedule, and next orderAmount are written before the pool
// swap, and an execution lock blocks re-entry while the swap and the
// pending execution fee transfer run.
// Only the swap-dependent accumulator is written after the swap.
func (d *dcaOrderImpl) executeGroupRound(
	_ int,
	rlm realm,
	group *pdca.Group,
	expectedAmountIn,
	amountOutMin,
	minOrderAmountOut,
	currentTimestamp int64,
) (groupRoundResult, error) {
	config := d.store.GetConfig()

	orderAmount := group.OrderAmount()
	if orderAmount <= 0 {
		return groupRoundResult{}, makeErrorWithDetails(errGroupNotExecutable, ufmt.Sprintf("groupId(%s) has no active order amount", group.ID()))
	}

	// Check the schedule first,
	// so a round already run by someone else reports "not executable".
	scheduledTimestamp := group.NextExecutionTimestamp()
	if currentTimestamp < scheduledTimestamp {
		return groupRoundResult{}, makeErrorWithDetails(
			errGroupNotExecutable,
			ufmt.Sprintf("groupId(%s) next execution at %d, now %d", group.ID(), scheduledTimestamp, currentTimestamp),
		)
	}

	// Orders may join or leave between the keeper's quote and inclusion;
	// the keeper then quotes again.
	assertIsQuotedAmountIn(group, expectedAmountIn, amountOutMin)

	// The pair price limit bounds the round's price and the pool's tick walk.
	priceLimit := getPairPriceLimit(d.store.GetPairPriceLimits(), group.InputToken(), group.OutputToken())

	selectedPool, err := selectRoundPool(whitelist.GetWhitelistedPools(whitelist.TargetDCA), priceLimit, config.MaxPoolPriceDeviationRate(), config.MaxPairPriceLimitAge(), group, orderAmount)
	if err != nil {
		return groupRoundResult{}, err
	}

	// Effects independent of the swap result.
	round := gnsmath.SafeAddUint64(group.Round(), 1)

	group.SetRound(round)

	// Orders ending at this round stop selling from the next round.
	roundMark := group.GetRoundMark(round)

	endedOrderAmount := int64(0)
	if roundMark != nil {
		endedOrderAmount = roundMark.OrderAmount()
	}

	// Move to the next slot without the ended order amount,
	// at least the execution gap after now.
	// A group with no order amount left drops out of the schedule index.
	minExecutionGap, err := pdca.CalculateMinExecutionGap(group.Interval(), config.MinExecutionGapRate())
	if err != nil {
		return groupRoundResult{}, err
	}

	nextExecutionTimestamp, err := pdca.CalculateNextExecutionTimestampWithGap(scheduledTimestamp, currentTimestamp, group.Interval(), minExecutionGap)
	if err != nil {
		return groupRoundResult{}, err
	}

	nextOrderAmount := gnsmath.SafeSubInt64(orderAmount, endedOrderAmount)
	if err := d.rescheduleGroup(group, nextOrderAmount, nextExecutionTimestamp); err != nil {
		return groupRoundResult{}, err
	}

	// Net payouts grow with amountPerExecution at one fee rate,
	// so the smallest order of each rate bounds every order's output.
	minAmounts := d.getFeeRateMinAmounts(group, round, true)
	if len(minAmounts) == 0 {
		return groupRoundResult{}, makeErrorWithDetails(
			errInvalidState,
			ufmt.Sprintf("groupId(%s) has no indexed order for round %d", group.ID(), round),
		)
	}

	if err := d.store.SetExecuting(0, rlm, true); err != nil {
		return groupRoundResult{}, err
	}

	swapAmountOut, err := swapExactIn(0, rlm, group, selectedPool.fee, selectedPool.sqrtPriceLimitX96, orderAmount, amountOutMin)
	if err != nil {
		return groupRoundResult{}, err
	}

	executedAmountOut := swapAmountOut

	outputPerAmountX128, err := pdca.CalculateOutputPerAmountX128(executedAmountOut, orderAmount)
	if err != nil {
		return groupRoundResult{}, err
	}

	if err := validateOrderOutput(group, minAmounts, minOrderAmountOut, outputPerAmountX128, executedAmountOut, orderAmount); err != nil {
		return groupRoundResult{}, err
	}

	accumulatedOutputPerAmountX128, overflow := u256.Zero().AddOverflow(group.AccumulatedOutputPerAmountX128(), outputPerAmountX128)
	if overflow {
		return groupRoundResult{}, makeErrorWithDetails(errOverflow, "accumulator overflow")
	}

	group.SetAccumulatedOutputPerAmountX128(accumulatedOutputPerAmountX128)

	if roundMark != nil {
		roundMark.SnapshotAccumulatedOutputPerAmountX128(accumulatedOutputPerAmountX128)
	}

	forwardedExecutionFeeAmount, pendingExecutionFeeAmount := d.collectExecutionFee(0, rlm, group.OutputToken(), 0)

	if err := d.store.SetExecuting(0, rlm, false); err != nil {
		return groupRoundResult{}, err
	}

	return groupRoundResult{
		poolPath:                    selectedPool.poolPath,
		scheduledTimestamp:          scheduledTimestamp,
		executionTimestamp:          currentTimestamp,
		executedAmountIn:            orderAmount,
		swapAmountOut:               swapAmountOut,
		executedAmountOut:           executedAmountOut,
		endedOrderAmount:            endedOrderAmount,
		forwardedExecutionFeeAmount: forwardedExecutionFeeAmount,
		pendingExecutionFeeAmount:   pendingExecutionFeeAmount,
	}, nil
}

execution_fee.gno

package impl

import (
	"gno.land/p/gnoswap/gnsmath/v1"
	pdca "gno.land/p/gnoswap/order/dca/v0"
	prbac "gno.land/p/gnoswap/rbac/v1"
	bptree "gno.land/p/nt/bptree/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/order/halt"

	pf "gno.land/r/gnoswap/protocol_fee"
	_ "gno.land/r/gnoswap/protocol_fee/v1"
)

// SetExecutionFeeRate sets the execution fee rate, in basis points,
// snapshotted by orders created afterwards.
// Existing orders keep the rate they were created with.
// Admin or governance only.
func (d *dcaOrderImpl) SetExecutionFeeRate(_ int, rlm realm, executionFeeRate int64) {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()
	d.assertIsNotExecuting()

	prev := rlm.Previous()
	access.AssertIsAdminOrGovernance(prev.Address())

	config := d.store.GetConfig()
	previousExecutionFeeRate := config.ExecutionFeeRate()

	if err := config.SetExecutionFeeRate(executionFeeRate); err != nil {
		panic(makeErrorWithDetails(
			errInvalidExecutionFeeRate,
			ufmt.Sprintf("executionFeeRate(%d) must be in [0, %d]", executionFeeRate, pdca.MaxExecutionFeeRate),
		).Error())
	}

	emitExecutionFeeRateChanged(prev.Address(), prev.PkgPath(), previousExecutionFeeRate, executionFeeRate)
}

// CollectPendingExecutionFee forwards the execution fee pending for
// tokenPath to the protocol fee realm. Payouts keep their execution fee as
// pending and rounds forward the pending fee of their output token; this
// forwards it when no round of that output token runs.
// Anyone may call it: the fee only moves to the protocol fee realm.
// It returns the amount forwarded and the amount left pending.
func (d *dcaOrderImpl) CollectPendingExecutionFee(_ int, rlm realm, tokenPath string) (int64, int64) {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()
	assertIsNotHalted(halt.OperationWithdraw)
	d.assertIsNotExecuting()

	prev := rlm.Previous()

	// The execution lock blocks re-entry while the protocol fee realm pulls
	// the fee, as it does during a round.
	if err := d.store.SetExecuting(0, rlm, true); err != nil {
		panic(err.Error())
	}

	forwardedAmount, pendingAmount := d.collectExecutionFee(0, rlm, tokenPath, 0)

	if err := d.store.SetExecuting(0, rlm, false); err != nil {
		panic(err.Error())
	}

	if forwardedAmount > 0 || pendingAmount > 0 {
		emitExecutionFeeCollected(prev.Address(), prev.PkgPath(), "", tokenPath, 0, 0, forwardedAmount, pendingAmount)
	}

	return forwardedAmount, pendingAmount
}

// addPendingExecutionFee holds a payout's execution fee for tokenPath
// until a round or CollectPendingExecutionFee forwards it.
// A payout never calls the protocol fee realm,
// so that realm cannot block withdrawals.
func (d *dcaOrderImpl) addPendingExecutionFee(tokenPath string, executionFeeAmount int64) {
	if executionFeeAmount <= 0 {
		return
	}

	pendingExecutionFees := d.store.GetPendingExecutionFees()
	pendingAmount := getPendingExecutionFeeAmount(pendingExecutionFees, tokenPath)

	pendingExecutionFees.Set(tokenPath, gnsmath.SafeAddInt64(pendingAmount, executionFeeAmount))
}

// pendingExecutionFeeAmount returns the execution fee of tokenPath
// held by this realm, 0 if none.
func (d *dcaOrderImpl) pendingExecutionFeeAmount(tokenPath string) int64 {
	return getPendingExecutionFeeAmount(d.store.GetPendingExecutionFees(), tokenPath)
}

// collectExecutionFee forwards executionFeeAmount, plus anything already
// pending for tokenPath, to the protocol fee realm.
// When collection is halted or the protocol fee realm rejects it,
// the total is held as pending and forwarded by a later collection
// of the same token, so a halt never blocks execution.
// It returns the amount forwarded and the amount left pending.
func (d *dcaOrderImpl) collectExecutionFee(_ int, rlm realm, tokenPath string, executionFeeAmount int64) (int64, int64) {
	pendingExecutionFees := d.store.GetPendingExecutionFees()

	pendingAmount := getPendingExecutionFeeAmount(pendingExecutionFees, tokenPath)

	totalAmount := gnsmath.SafeAddInt64(pendingAmount, executionFeeAmount)
	if totalAmount <= 0 {
		return 0, 0
	}

	protocolFeeAddress := access.MustGetAddress(prbac.ROLE_PROTOCOL_FEE.String())
	common.SafeGRC20Approve(0, rlm, tokenPath, protocolFeeAddress, totalAmount)

	// AddToProtocolFee pulls the approved amount from this realm. It returns
	// an error while its collection is halted; nothing was pulled then:
	// withdraw the approval and keep it pending.
	if err := pf.AddToProtocolFee(cross(rlm), tokenPath, totalAmount); err != nil {
		common.SafeGRC20Approve(0, rlm, tokenPath, protocolFeeAddress, 0)
		pendingExecutionFees.Set(tokenPath, totalAmount)

		return 0, totalAmount
	}

	// Keep the token's entry at zero rather than removing it: payouts add to
	// it again, and recreating it would charge the next payout its storage.
	if pendingAmount > 0 {
		pendingExecutionFees.Set(tokenPath, int64(0))
	}

	return totalAmount, 0
}

// getPendingExecutionFeeAmount returns the execution fee of tokenPath
// held by this realm, 0 if none.
func getPendingExecutionFeeAmount(pendingExecutionFees *bptree.BPTree, tokenPath string) int64 {
	value := pendingExecutionFees.Get(tokenPath)
	if value == nil {
		return 0
	}

	return value.(int64)
}

getter.gno

package impl

import (
	"time"

	"gno.land/p/gnoswap/gnsmath/v1"
	pdca "gno.land/p/gnoswap/order/dca/v0"
	"gno.land/p/gnoswap/utils/v1"
	rotree "gno.land/p/nt/bptree/rotree/v0"
	"gno.land/p/onbloc/json/v0"

	"gno.land/r/gnoswap/order/halt"
	"gno.land/r/gnoswap/order/whitelist"
)

// Getters return copies of stored orders, groups, and configs.
// A stored pointer must never leave the realm: methods of pdca types run
// with the storing realm's authority, so a caller holding the pointer
// could mutate state through its setters.
// Store trees are wrapped in read-only views for the same reason:
// views of trees holding pointers copy every entry they return.
// Group copies leave out the round marks, so their cost does not grow with
// the marks any order creator can add; GetGroupRoundMarks reads them.

// GetConfig returns a copy of the configuration.
func (d *dcaOrderImpl) GetConfig() *pdca.Config {
	return d.store.GetConfig().Clone()
}

// GetNextOrderID returns the ID the next created order receives.
func (d *dcaOrderImpl) GetNextOrderID() uint64 {
	return d.store.GetNextOrderID()
}

// ExistsOrder reports whether orderID is an active order.
func (d *dcaOrderImpl) ExistsOrder(orderID uint64) bool {
	return d.store.GetOrders().Has(pdca.OrderKey(orderID))
}

// GetOrder returns a copy of an active order.
func (d *dcaOrderImpl) GetOrder(orderID uint64) (*pdca.Order, error) {
	order, err := d.getOrder(orderID)
	if err != nil {
		return nil, err
	}

	return order.Clone(), nil
}

// GetOrders returns a read-only view of active orders keyed by OrderKey.
func (d *dcaOrderImpl) GetOrders() *rotree.ReadOnlyTree {
	return rotree.Wrap(d.store.GetOrders(), cloneOrderEntry)
}

// GetOrdersByOwner returns the read-only OwnerOrderKey -> orderID index.
func (d *dcaOrderImpl) GetOrdersByOwner() *rotree.ReadOnlyTree {
	return rotree.Wrap(d.store.GetOrdersByOwner(), nil)
}

// GetClaimableAmount returns what the next Claim of an active order pays.
func (d *dcaOrderImpl) GetClaimableAmount(orderID uint64) int64 {
	order, group, err := d.getOrderWithGroup(orderID)
	if err != nil {
		return 0
	}

	claimableAmount, err := calculateClaimableAmount(order, group)
	if err != nil {
		panic(err.Error())
	}

	return claimableAmount
}

// GetOrderIDsByOwner pages an owner's active order IDs.
func (d *dcaOrderImpl) GetOrderIDsByOwner(owner address, startAfterID uint64, count int) []uint64 {
	if count <= 0 {
		return []uint64{}
	}

	prefix := pdca.OwnerOrderPrefix(owner)
	start := prefix

	if startAfterID > 0 {
		if startAfterID == ^uint64(0) {
			return []uint64{}
		}

		start = pdca.OwnerOrderKey(owner, gnsmath.SafeAddUint64(startAfterID, 1))
	}

	orderIDs := []uint64{}

	d.store.GetOrdersByOwner().Iterate(start, pdca.PrefixEnd(prefix), func(_ string, value any) bool {
		orderIDs = append(orderIDs, value.(uint64))

		return len(orderIDs) >= count
	})

	return orderIDs
}

// GetOrderIDsByGroup pages a group's active order IDs.
func (d *dcaOrderImpl) GetOrderIDsByGroup(groupID string, startAfterID uint64, count int) []uint64 {
	if count <= 0 {
		return []uint64{}
	}

	orderIDs, _ := d.getGroupOrderIDs(groupID, startAfterID, count)

	return orderIDs
}

// ExistsGroup reports whether groupID is a stored group.
func (d *dcaOrderImpl) ExistsGroup(groupID string) bool {
	return d.store.GetGroups().Has(groupID)
}

// GetGroup returns a copy of a group without its round marks.
func (d *dcaOrderImpl) GetGroup(groupID string) (*pdca.Group, error) {
	group, err := d.getGroup(groupID)
	if err != nil {
		return nil, err
	}

	return group.CloneWithoutRoundMarks(), nil
}

// GetGroups returns a read-only view of groups keyed by group ID.
func (d *dcaOrderImpl) GetGroups() *rotree.ReadOnlyTree {
	return rotree.Wrap(d.store.GetGroups(), cloneGroupEntry)
}

// GetGroupRoundMarks returns a read-only view of a group's round marks
// keyed by RoundKey, or nil if the group does not exist.
func (d *dcaOrderImpl) GetGroupRoundMarks(groupID string) *rotree.ReadOnlyTree {
	group, err := d.getGroup(groupID)
	if err != nil {
		return nil
	}

	return group.RoundMarks()
}

// GetOrdersByGroup returns the read-only GroupOrderKey -> orderID index.
func (d *dcaOrderImpl) GetOrdersByGroup() *rotree.ReadOnlyTree {
	return rotree.Wrap(d.store.GetOrdersByGroup(), nil)
}

// GetOrderAmountsByGroup returns the read-only
// GroupOrderAmountKey -> endRound index.
func (d *dcaOrderImpl) GetOrderAmountsByGroup() *rotree.ReadOnlyTree {
	return rotree.Wrap(d.store.GetOrderAmountsByGroup(), nil)
}

// GetScheduledGroups returns the read-only ScheduleKey -> groupID index.
func (d *dcaOrderImpl) GetScheduledGroups() *rotree.ReadOnlyTree {
	return rotree.Wrap(d.store.GetScheduledGroups(), nil)
}

// GetTokenMinAmountPerExecution returns the minimum input per execution set
// for tokenPath, or 0 if none is set.
func (d *dcaOrderImpl) GetTokenMinAmountPerExecution(tokenPath string) int64 {
	return getTokenMinAmountPerExecution(d.store, tokenPath)
}

// GetMinAmountPerExecution returns the minimum input per execution a new order
// selling tokenPath needs: the larger of the global and the token minimum.
func (d *dcaOrderImpl) GetMinAmountPerExecution(tokenPath string) int64 {
	return d.minAmountPerExecution(tokenPath)
}

// GetTokenMinAmountsPerExecution returns the read-only tokenPath -> int64
// index of per-token minimums.
func (d *dcaOrderImpl) GetTokenMinAmountsPerExecution() *rotree.ReadOnlyTree {
	return rotree.Wrap(d.store.GetTokenMinAmountsPerExecution(), nil)
}

// GetPairPriceLimit returns a copy of the price limit of selling inputToken
// for outputToken, and whether one is set.
func (d *dcaOrderImpl) GetPairPriceLimit(inputToken string, outputToken string) (*pdca.PairPriceLimit, bool) {
	limit := getPairPriceLimit(d.store.GetPairPriceLimits(), inputToken, outputToken)
	if limit == nil {
		return nil, false
	}

	return limit.Clone(), true
}

// GetPairPriceLimits returns a read-only view of the pair price limits keyed
// by PairKey.
func (d *dcaOrderImpl) GetPairPriceLimits() *rotree.ReadOnlyTree {
	return rotree.Wrap(d.store.GetPairPriceLimits(), clonePairPriceLimitEntry)
}

// GetExecutableGroups lists copies of due groups after the cursor entry.
// The schedule index is ordered by next execution timestamp,
// so the scan stops at the first group that is not yet due.
// Pools are not quoted; a listed round may still revert.
// Nothing is listed while rounds are halted.
func (d *dcaOrderImpl) GetExecutableGroups(cursor string, count int) ([]*pdca.Group, error) {
	if count <= 0 {
		return []*pdca.Group{}, nil
	}

	start, err := pdca.ParseScheduleCursor(cursor)
	if err != nil {
		return nil, makeErrorWithDetails(errInvalidCursor, cursor)
	}

	// Rounds cannot run while execution is halted.
	if isExecutionHalted() {
		return []*pdca.Group{}, nil
	}

	currentTimestamp := time.Now().Unix()
	groupIDs := []string{}
	d.store.GetScheduledGroups().Iterate(start, "", func(key string, value any) bool {
		if key == start && start != "" {
			return false
		}

		if pdca.ScheduleKeyTimestamp(key) > currentTimestamp {
			return true
		}

		groupIDs = append(groupIDs, value.(string))

		return len(groupIDs) >= count
	})

	groups := make([]*pdca.Group, 0, len(groupIDs))
	for _, groupID := range groupIDs {
		group, err := d.GetGroup(groupID)
		if err != nil {
			return nil, err
		}

		groups = append(groups, group)
	}

	return groups, nil
}

// GetOrderExecutionLogs returns copies of up to count of an order's unreleased
// execution logs, oldest first.
func (d *dcaOrderImpl) GetOrderExecutionLogs(orderID uint64, count int) ([]*pdca.ExecutionLog, error) {
	order, err := d.getOrder(orderID)
	if err != nil {
		return nil, err
	}

	return pdca.ExecutionLogs(d.store.GetExecutionLogs(), order, count), nil
}

// GetExecutionLogs returns the read-only ExecutionLogKey -> lastRound index
// of unreleased execution logs.
func (d *dcaOrderImpl) GetExecutionLogs() *rotree.ReadOnlyTree {
	return rotree.Wrap(d.store.GetExecutionLogs(), nil)
}

// GetPendingExecutionFeeAmount returns the execution fee of tokenPath
// held by this realm until the protocol fee realm accepts it.
func (d *dcaOrderImpl) GetPendingExecutionFeeAmount(tokenPath string) int64 {
	return getPendingExecutionFeeAmount(d.store.GetPendingExecutionFees(), tokenPath)
}

// GetPendingExecutionFees returns the read-only tokenPath -> amount index
// of execution fees held until the protocol fee realm accepts them.
func (d *dcaOrderImpl) GetPendingExecutionFees() *rotree.ReadOnlyTree {
	return rotree.Wrap(d.store.GetPendingExecutionFees(), nil)
}

// GetExecutionQuote reports how the group's next round would trade now.
// Every pool is quoted here, even a single one,
// so the selection and output match ExecuteGroup in the same block.
func (d *dcaOrderImpl) GetExecutionQuote(groupID string) string {
	group, err := d.getGroup(groupID)
	if err != nil {
		return ""
	}

	config := d.store.GetConfig()
	amountIn := group.OrderAmount()
	selectedPoolPath := ""
	expectedAmountOut := int64(0)
	expectedExecutionFeeAmount := int64(0)
	expectedMinOrderAmountOut := int64(0)
	candidateNodes := []*json.Node{}
	minAmountNodes := []*json.Node{}

	// The round checks the smallest order of each execution fee rate after
	// that rate. The quote's fee and order output assume the highest rate of
	// the orders the round sells, the most any of them pays.
	minAmounts := []feeRateMinAmount{}
	if amountIn > 0 {
		minAmounts = d.getFeeRateMinAmounts(group, group.Round()+1, false)
	}

	minAmountPerExecution := minAmountPerExecutionOf(minAmounts)
	executionFeeRate := maxExecutionFeeRateOf(minAmounts)

	priceLimit := getPairPriceLimit(d.store.GetPairPriceLimits(), group.InputToken(), group.OutputToken())
	minOutputPerInputX128 := "0"
	priceLimitUpdatedAt := int64(0)

	if priceLimit != nil {
		minOutputPerInputX128 = priceLimit.MinOutputPerInputX128().ToString()
		priceLimitUpdatedAt = priceLimit.UpdatedAt()
	}

	if amountIn > 0 {
		selectedPool, candidates := selectPool(whitelist.GetWhitelistedPools(whitelist.TargetDCA), priceLimit, config.MaxPoolPriceDeviationRate(), config.MaxPairPriceLimitAge(), group.InputToken(), group.OutputToken(), amountIn, true)
		if selectedPool != nil {
			expectedAmountOut = selectedPool.quotedAmountOut
			selectedPoolPath = selectedPool.poolPath

			expectedOrderAmountOut, err := pdca.CalculateMinNetAmountOut(expectedAmountOut, executionFeeRate)
			if err != nil {
				panic(err.Error())
			}

			expectedExecutionFeeAmount = expectedAmountOut - expectedOrderAmountOut
		}

		// The least output the round's per-order check would compare with
		// max(1, minOrderAmountOut).
		outputPerAmountX128, err := pdca.CalculateOutputPerAmountX128(expectedAmountOut, amountIn)
		if err != nil {
			panic(err.Error())
		}

		for i, minAmount := range minAmounts {
			orderAmountOut, err := calculateMinOrderAmountOut(minAmount, outputPerAmountX128)
			if err != nil {
				panic(err.Error())
			}

			if i == 0 || orderAmountOut < expectedMinOrderAmountOut {
				expectedMinOrderAmountOut = orderAmountOut
			}

			minAmountNodes = append(minAmountNodes, json.ObjectNode("", map[string]*json.Node{
				"executionFeeRate":      intNode(minAmount.executionFeeRate),
				"minAmountPerExecution": intNode(minAmount.minAmountPerExecution),
			}))
		}

		for _, candidate := range candidates {
			candidateAmountOut := int64(0)
			if candidate.isQuoted {
				candidateAmountOut = candidate.quotedAmountOut
			}

			candidateNodes = append(candidateNodes, json.ObjectNode("", map[string]*json.Node{
				"poolPath":         json.StringNode("", candidate.poolPath),
				"eligible":         json.BoolNode("", candidate.isEligible()),
				"ineligibleCode":   json.StringNode("", candidate.ineligibleCode),
				"ineligibleReason": json.StringNode("", candidate.ineligibleReason),
				"amountOut":        intNode(candidateAmountOut),
			}))
		}
	}

	return marshal(map[string]*json.Node{
		"groupId":                      json.StringNode("", group.ID()),
		"inputToken":                   json.StringNode("", group.InputToken()),
		"outputToken":                  json.StringNode("", group.OutputToken()),
		"amountIn":                     intNode(amountIn),
		"minAmountPerExecution":        intNode(minAmountPerExecution),
		"executable":                   json.BoolNode("", isGroupExecutable(group, time.Now().Unix())),
		"selectedPool":                 json.StringNode("", selectedPoolPath),
		"expectedAmountOut":            intNode(expectedAmountOut),
		"executionFeeRate":             intNode(executionFeeRate),
		"expectedExecutionFeeAmount":   intNode(expectedExecutionFeeAmount),
		"expectedOrderAmountOut":       intNode(expectedAmountOut - expectedExecutionFeeAmount),
		"expectedMinOrderAmountOut":    intNode(expectedMinOrderAmountOut),
		"minAmountsByExecutionFeeRate": json.ArrayNode("", minAmountNodes),
		"minOutputPerInputX128":        json.StringNode("", minOutputPerInputX128),
		"priceLimitUpdatedAt":          intNode(priceLimitUpdatedAt),
		"candidates":                   json.ArrayNode("", candidateNodes),
	})
}

// calculateClaimableAmount returns what the next Claim pays the owner,
// net of the order's execution fee.
func calculateClaimableAmount(order *pdca.Order, group *pdca.Group) (int64, error) {
	endAccumulatedX128, _, err := getOrderEndAccumulatedOutputPerAmountX128(order, group)
	if err != nil {
		return 0, err
	}

	payout, err := calculateOrderPayout(order, endAccumulatedX128)
	if err != nil {
		return 0, err
	}

	return payout.claimedAmount, nil
}

// isGroupExecutable reports whether the schedule and the halts allow
// the group's next round now.
// Pools are not quoted here.
func isGroupExecutable(group *pdca.Group, currentTimestamp int64) bool {
	return group.OrderAmount() > 0 && currentTimestamp >= group.NextExecutionTimestamp() && !isExecutionHalted()
}

// isExecutionHalted reports whether execute or withdraw is halted,
// matching the checks ExecuteGroup makes before running a round.
func isExecutionHalted() bool {
	_, halted := haltedOperation(halt.OperationExecute, halt.OperationWithdraw)
	return halted
}

func marshal(fields map[string]*json.Node) string {
	b, err := json.Marshal(json.ObjectNode("", fields))
	if err != nil {
		panic(err.Error())
	}

	return string(b)
}

func intNode(v int64) *json.Node {
	return json.StringNode("", utils.FormatInt(v))
}

func cloneOrderEntry(value any) any {
	order, ok := value.(*pdca.Order)
	if !ok {
		return nil
	}

	return order.Clone()
}

func cloneGroupEntry(value any) any {
	group, ok := value.(*pdca.Group)
	if !ok {
		return nil
	}

	return group.CloneWithoutRoundMarks()
}

func clonePairPriceLimitEntry(value any) any {
	limit, ok := value.(*pdca.PairPriceLimit)
	if !ok {
		return nil
	}

	return limit.Clone()
}

gnomod.toml

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

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

init.gno

package impl

import (
	pdca "gno.land/p/gnoswap/order/dca/v0"

	dca "gno.land/r/gnoswap/order/dca"
)

func init(cur realm) {
	registerDCAOrderImpl(cur)
}

func registerDCAOrderImpl(cur realm) {
	dca.RegisterInitializer(cross(cur), func(_ int, rlm realm, dcaStore pdca.IDCAOrderStore) pdca.IDCAOrder {
		err := initStoreData(0, rlm, dcaStore)
		if err != nil {
			panic(err.Error())
		}

		return NewDCAOrderImpl(dcaStore)
	})
}

func initStoreData(_ int, rlm realm, s pdca.IDCAOrderStore) error {
	if !s.HasOrders() {
		if err := s.SetOrders(0, rlm, dca.NewBPTreeN(dcaBPTreeFanOut)); err != nil {
			return err
		}
	}

	if !s.HasOrdersByOwner() {
		if err := s.SetOrdersByOwner(0, rlm, dca.NewBPTreeN(dcaBPTreeFanOut)); err != nil {
			return err
		}
	}

	if !s.HasGroups() {
		if err := s.SetGroups(0, rlm, dca.NewBPTreeN(dcaBPTreeFanOut)); err != nil {
			return err
		}
	}

	if !s.HasScheduledGroups() {
		if err := s.SetScheduledGroups(0, rlm, dca.NewBPTreeN(dcaBPTreeFanOut)); err != nil {
			return err
		}
	}

	if !s.HasOrdersByGroup() {
		if err := s.SetOrdersByGroup(0, rlm, dca.NewBPTreeN(dcaBPTreeFanOut)); err != nil {
			return err
		}
	}

	if !s.HasPendingExecutionFees() {
		if err := s.SetPendingExecutionFees(0, rlm, dca.NewBPTreeN(dcaBPTreeFanOut)); err != nil {
			return err
		}
	}

	if !s.HasExecutionLogs() {
		if err := s.SetExecutionLogs(0, rlm, dca.NewBPTreeN(dcaBPTreeFanOut)); err != nil {
			return err
		}
	}

	if !s.HasOrderAmountsByGroup() {
		if err := s.SetOrderAmountsByGroup(0, rlm, dca.NewBPTreeN(dcaBPTreeFanOut)); err != nil {
			return err
		}
	}

	if !s.HasTokenMinAmountsPerExecution() {
		if err := s.SetTokenMinAmountsPerExecution(0, rlm, dca.NewBPTreeN(dcaBPTreeFanOut)); err != nil {
			return err
		}
	}

	if !s.HasPairPriceLimits() {
		if err := s.SetPairPriceLimits(0, rlm, dca.NewBPTreeN(dcaBPTreeFanOut)); err != nil {
			return err
		}
	}

	if !s.HasNextOrderID() {
		if err := s.SetNextOrderID(0, rlm, 1); err != nil {
			return err
		}
	}

	if !s.HasConfig() {
		config := pdca.NewConfig(defaultMinAmountPerExecution, defaultMaxExecutionCount, defaultAllowedIntervals())
		config.SetMinExecutionGapRate(defaultMinExecutionGapRate)
		config.SetMaxPoolPriceDeviationRate(defaultMaxPoolPriceDeviationRate)
		config.SetMaxPairPriceLimitAge(defaultMaxPairPriceLimitAge)
		config.SetMaxClaimBatchSize(defaultMaxClaimBatchSize)

		for interval, step := range defaultSlotSteps() {
			if err := config.SetSlotStep(interval, step); err != nil {
				return err
			}
		}

		if err := config.SetExecutionFeeRate(defaultExecutionFeeRate); err != nil {
			return err
		}

		if err := s.SetConfig(0, rlm, config); err != nil {
			return err
		}
	}

	return nil
}

instance.gno

package impl

import (
	pdca "gno.land/p/gnoswap/order/dca/v0"
)

type dcaOrderImpl struct {
	store pdca.IDCAOrderStore
}

// NewDCAOrderImpl creates the implementation over the shared store.
func NewDCAOrderImpl(dcaStore pdca.IDCAOrderStore) pdca.IDCAOrder {
	return &dcaOrderImpl{store: dcaStore}
}

manager.gno

package impl

import (
	"time"

	pdca "gno.land/p/gnoswap/order/dca/v0"
	u256 "gno.land/p/gnoswap/uint256/v1"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/order/keeper"
)

// Manager settings.
//
// The pool manager (PoolManagerRole at deployment, admin and governance too)
// sets, from an off-chain oracle price:
//   - the minimum input per execution of each token, so a new order is worth
//     at least a set value per round whatever the token's decimals; it applies
//     on top of the global minimum (Config.MinAmountPerExecution) and only to
//     new orders
//   - the price limit of each pair direction (see price_limit.gno)

// SetTokenMinAmountPerExecution sets the minimum input per execution of new
// orders selling tokenPath; 0 removes it, leaving the global minimum.
func (d *dcaOrderImpl) SetTokenMinAmountPerExecution(_ int, rlm realm, tokenPath string, minAmountPerExecution int64) {
	prev := d.assertIsManagerCall(0, rlm, keeper.SelectorSetTokenMinAmountPerExecution)

	if minAmountPerExecution < 0 {
		panic(makeErrorWithDetails(
			errInvalidConfig,
			ufmt.Sprintf("minAmountPerExecution(%d) must not be negative", minAmountPerExecution),
		).Error())
	}

	tokenMinAmounts := d.store.GetTokenMinAmountsPerExecution()
	previousMinAmountPerExecution := getTokenMinAmountPerExecution(d.store, tokenPath)

	if minAmountPerExecution == 0 {
		tokenMinAmounts.Remove(tokenPath)
	} else {
		if err := common.IsRegistered(tokenPath); err != nil {
			panic(makeErrorWithDetails(errInvalidToken, ufmt.Sprintf("tokenPath(%s): %s", tokenPath, err.Error())).Error())
		}

		tokenMinAmounts.Set(tokenPath, minAmountPerExecution)
	}

	emitTokenMinAmountPerExecutionUpdated(prev.Address(), prev.PkgPath(), tokenPath, previousMinAmountPerExecution, minAmountPerExecution)
}

// SetPairPriceLimit sets the minimum pool output per unit of input, in Q128,
// of rounds selling inputToken for outputToken; "0" removes it, which stops
// the pair direction from trading and from receiving new orders.
// It takes effect from the next quote or round, for existing orders too.
func (d *dcaOrderImpl) SetPairPriceLimit(_ int, rlm realm, inputToken string, outputToken string, minOutputPerInputX128 string) {
	prev := d.assertIsManagerCall(0, rlm, keeper.SelectorSetPairPriceLimit)

	if inputToken == outputToken {
		panic(makeErrorWithDetails(errInvalidToken, ufmt.Sprintf("inputToken and outputToken are both %s", inputToken)).Error())
	}

	limitX128, err := parseMinOutputPerInputX128(minOutputPerInputX128)
	if err != nil {
		panic(err.Error())
	}

	pairPriceLimits := d.store.GetPairPriceLimits()
	pairKey := pdca.PairKey(inputToken, outputToken)

	previous := getPairPriceLimit(pairPriceLimits, inputToken, outputToken)

	previousLimitX128 := u256.Zero()
	if previous != nil {
		previousLimitX128 = previous.MinOutputPerInputX128()
	}

	updatedAt := time.Now().Unix()

	switch {
	case limitX128.IsZero():
		pairPriceLimits.Remove(pairKey)

		updatedAt = 0
	case previous != nil:
		// Stored limits are updated in place, like other stored entries.
		previous.Update(limitX128, updatedAt)
	default:
		if err := common.ValidateRegistered(inputToken, outputToken); err != nil {
			panic(makeErrorWithDetails(errInvalidToken, err.Error()).Error())
		}

		pairPriceLimits.Set(pairKey, pdca.NewPairPriceLimit(limitX128, updatedAt))
	}

	emitPairPriceLimitUpdated(
		prev.Address(),
		prev.PkgPath(),
		inputToken,
		outputToken,
		previousLimitX128.ToString(),
		limitX128.ToString(),
		updatedAt,
	)
}

// getTokenMinAmountPerExecution returns the minimum input per execution set
// for tokenPath, or 0 if none is set.
func getTokenMinAmountPerExecution(s pdca.IDCAOrderStore, tokenPath string) int64 {
	value := s.GetTokenMinAmountsPerExecution().Get(tokenPath)
	if value == nil {
		return 0
	}

	return value.(int64)
}

// minAmountPerExecution returns the minimum input per execution of a new order
// selling tokenPath: the larger of the global and the token minimum.
func (d *dcaOrderImpl) minAmountPerExecution(tokenPath string) int64 {
	minAmount := d.store.GetConfig().MinAmountPerExecution()

	if tokenMinAmount := getTokenMinAmountPerExecution(d.store, tokenPath); tokenMinAmount > minAmount {
		return tokenMinAmount
	}

	return minAmount
}

order.gno

package impl

import (
	"chain/runtime"
	"time"

	"gno.land/p/gnoswap/gnsmath/v1"
	pdca "gno.land/p/gnoswap/order/dca/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/order/halt"
	"gno.land/r/gnoswap/order/keeper"
	"gno.land/r/gnoswap/order/whitelist"
)

// CreateOrder escrows the order input
// and adds the order's per-round amount to its group.
// The group runs at the slotOffset of each interval, see pdca.Group.
// The order takes part in the group's next executionCount rounds only;
// the caller pays for the order's execution logs, one per three rounds.
// The order snapshots the execution fee rate in effect, charged on its
// output when it is paid out; later rate changes leave it unchanged.
func (d *dcaOrderImpl) CreateOrder(
	_ int,
	rlm realm,
	inputToken string,
	outputToken string,
	interval int64,
	slotOffset int64,
	amountPerExecution int64,
	executionCount int64,
) uint64 {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()
	// A new order only joins rounds, so it is rejected while rounds are halted.
	assertIsNotHalted(halt.OperationExecute)
	d.assertIsNotExecuting()

	prev := rlm.Previous()
	caller := prev.Address()
	access.AssertIsValidAddress(caller)

	config := d.store.GetConfig()

	assertIsValidPair(inputToken, outputToken)
	assertHasPairPriceLimit(d.store.GetPairPriceLimits(), inputToken, outputToken)
	assertIsAllowedInterval(config, interval)
	assertIsAllowedSlot(config, interval, slotOffset)
	assertIsValidOrderSize(config, d.minAmountPerExecution(inputToken), amountPerExecution, executionCount)

	order, group, isNewGroup, depositAmount, err := d.createOrder(
		0, rlm, caller, inputToken, outputToken, interval, slotOffset, amountPerExecution, executionCount,
	)
	if err != nil {
		panic(err.Error())
	}

	if isNewGroup {
		emitGroupCreated(caller, prev.PkgPath(), group)
	}

	// The escrow transfer does not touch the pools, so this quotes the state
	// the order was placed in.
	// The order's execution fee is deducted up front, as its payouts deduct
	// it, so the reference is comparable with the output the owner receives.
	referenceSwapAmountOut := quoteReferenceAmountOut(
		whitelist.GetWhitelistedPools(whitelist.TargetDCA),
		getPairPriceLimit(d.store.GetPairPriceLimits(), inputToken, outputToken),
		config.MaxPoolPriceDeviationRate(),
		config.MaxPairPriceLimitAge(),
		inputToken,
		outputToken,
		depositAmount,
	)

	referenceExecutionFeeAmount, err := pdca.CalculateExecutionFeeAmount(referenceSwapAmountOut, order.ExecutionFeeRate())
	if err != nil {
		panic(err.Error())
	}

	referenceAmountOut := gnsmath.SafeSubInt64(referenceSwapAmountOut, referenceExecutionFeeAmount)

	emitOrderCreated(caller, prev.PkgPath(), order, group, depositAmount, referenceAmountOut)

	return order.ID()
}

// createOrder stores the order, joins or creates its group,
// and pulls the deposit from the owner.
func (d *dcaOrderImpl) createOrder(
	_ int,
	rlm realm,
	owner address,
	inputToken string,
	outputToken string,
	interval int64,
	slotOffset int64,
	amountPerExecution int64,
	executionCount int64,
) (*pdca.Order, *pdca.Group, bool, int64, error) {
	depositAmount := gnsmath.SafeMulInt64(amountPerExecution, executionCount)

	currentTimestamp := time.Now().Unix()
	groups := d.store.GetGroups()
	groupID := pdca.MakeGroupID(inputToken, outputToken, interval, slotOffset)

	// A new or idle group runs its next round at the first slot from now,
	// instead of at a stale slot that would run at once.
	firstSlotTimestamp, err := pdca.CalculateFirstSlotTimestamp(currentTimestamp, interval, slotOffset)
	if err != nil {
		return nil, nil, false, 0, makeErrorWithDetails(errInvalidSlotOffset, err.Error())
	}

	var group *pdca.Group

	isNewGroup := false

	if value := groups.Get(groupID); value != nil {
		group = value.(*pdca.Group)
	} else {
		group = pdca.NewGroup(groupID, inputToken, outputToken, interval, slotOffset, firstSlotTimestamp)
		groups.Set(groupID, group)

		isNewGroup = true
	}

	nextExecutionTimestamp := group.NextExecutionTimestamp()
	if group.OrderAmount() == 0 {
		nextExecutionTimestamp = firstSlotTimestamp
	}

	orderID := d.store.GetNextOrderID()
	if err := d.store.SetNextOrderID(0, rlm, gnsmath.SafeAddUint64(orderID, 1)); err != nil {
		return nil, nil, false, 0, err
	}

	executionFeeRate := d.store.GetConfig().ExecutionFeeRate()

	order, err := pdca.NewOrder(orderID, owner, group, amountPerExecution, executionCount, executionFeeRate, currentTimestamp, runtime.ChainHeight())
	if err != nil {
		return nil, nil, false, 0, makeErrorWithDetails(errInvalidExecutionCount, err.Error())
	}

	// Store the order's execution logs now,
	// so the owner pays their storage deposit up front.
	pdca.AllocateExecutionLogs(d.store.GetExecutionLogs(), order)

	roundMark := group.GetOrCreateRoundMark(order.EndRound())
	roundMark.SetOrderAmount(gnsmath.SafeAddInt64(roundMark.OrderAmount(), amountPerExecution))
	roundMark.SetOrderCount(gnsmath.SafeAddInt64(roundMark.OrderCount(), 1))

	groupOrderAmount := gnsmath.SafeAddInt64(group.OrderAmount(), amountPerExecution)
	if err := d.rescheduleGroup(group, groupOrderAmount, nextExecutionTimestamp); err != nil {
		return nil, nil, false, 0, err
	}

	group.SetActiveOrderCount(gnsmath.SafeAddInt64(group.ActiveOrderCount(), 1))

	d.store.GetOrders().Set(pdca.OrderKey(orderID), order)
	d.store.GetOrdersByOwner().Set(pdca.OwnerOrderKey(owner, orderID), orderID)
	d.store.GetOrdersByGroup().Set(pdca.GroupOrderKey(groupID, orderID), orderID)
	d.store.GetOrderAmountsByGroup().Set(pdca.GroupOrderAmountKey(groupID, executionFeeRate, amountPerExecution, orderID), order.EndRound())

	// Pull funds last; a failure reverts every write above.
	common.SafeGRC20TransferFrom(0, rlm, inputToken, owner, rlm.Address(), depositAmount)

	return order, group, isNewGroup, depositAmount, nil
}

// CancelOrder pays accrued output, refunds the input of unexecuted rounds,
// and closes the order, releasing all of its execution logs.
// If every round already executed, the order completes instead,
// with nothing to refund.
func (d *dcaOrderImpl) CancelOrder(_ int, rlm realm, orderID uint64) (int64, int64) {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()
	assertIsNotHalted(halt.OperationWithdraw)
	d.assertIsNotExecuting()

	prev := rlm.Previous()
	caller := prev.Address()

	order, group, err := d.getOrderWithGroup(orderID)
	if err != nil {
		panic(err.Error())
	}

	assertIsOrderOwner(order, caller)

	result, err := d.cancelOrder(0, rlm, caller, prev.PkgPath(), order, group)
	if err != nil {
		panic(err.Error())
	}

	if result.isCompleted {
		// Every round already executed: a completion, not a cancellation.
		emitOrderClaimed(caller, prev.PkgPath(), order, group, result.payout, pdca.OrderStatusCompleted)
	} else {
		emitOrderCancelled(caller, prev.PkgPath(), order, group, result.payout, result.refundedAmount)
	}

	emitPayoutExecutionFee(caller, prev.PkgPath(), group, result.payout.executionFeeAmount, d.pendingExecutionFeeAmount(group.OutputToken()))

	return result.refundedAmount, result.payout.claimedAmount
}

// ForceCancelOrder closes an order that blocks its group's rounds exactly as
// CancelOrder would for its owner: accrued output and unsold input go to the
// owner, never to the caller. The freed storage deposit of its execution logs
// goes to the transaction signer, as for any release.
//
// The order must have rounds left and meet one of the conditions checked
// on-chain by forceCancelReason, reported as the event's reason:
//   - below_min_amount: its amountPerExecution is below the minimum a new
//     order selling its token needs now
//   - no_order_output: the next round is due and, as quoted now, would credit
//     it less than minOrderAmountOutFloor after its execution fee
//   - exceeds_pool_capacity: the next round is due, no pool can fill it
//     as quoted now, a pool fills part of it within the price limit, and no
//     order of the round sells more per execution than this one
//
// Any other order is rejected, so a keeper cannot close healthy orders.
//
// Only keepers allowed by gno.land/r/gnoswap/order/keeper may call it
// (DCAKeeperRole at deployment).
func (d *dcaOrderImpl) ForceCancelOrder(_ int, rlm realm, orderID uint64) (int64, int64) {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()
	assertIsNotHalted(halt.OperationWithdraw)
	d.assertIsNotExecuting()

	prev := rlm.Previous()
	caller := prev.Address()

	if !keeper.IsAuthorized(rlm.PkgPath(), keeper.SelectorForceCancelOrder, caller) {
		panic(makeErrorWithDetails(errNotKeeper, ufmt.Sprintf("caller(%s) selector(%s)", caller.String(), string(keeper.SelectorForceCancelOrder))).Error())
	}

	order, group, err := d.getOrderWithGroup(orderID)
	if err != nil {
		panic(err.Error())
	}

	// Check before the order leaves its group, against the state it blocks.
	reason, err := d.forceCancelReason(order, group, time.Now().Unix())
	if err != nil {
		panic(err.Error())
	}

	result, err := d.cancelOrder(0, rlm, caller, prev.PkgPath(), order, group)
	if err != nil {
		panic(err.Error())
	}

	emitOrderForceCancelled(caller, prev.PkgPath(), order, group, result.payout, result.refundedAmount, reason)

	emitPayoutExecutionFee(caller, prev.PkgPath(), group, result.payout.executionFeeAmount, d.pendingExecutionFeeAmount(group.OutputToken()))

	return result.refundedAmount, result.payout.claimedAmount
}

// Reasons ForceCancelOrder accepts, reported by DCAOrderForceCancelled.
const (
	forceCancelBelowMinAmount      = "below_min_amount"
	forceCancelNoOrderOutput       = "no_order_output"
	forceCancelExceedsPoolCapacity = "exceeds_pool_capacity"
)

// forceCancelReason returns why the order blocks its group, or
// errOrderNotBlocking if it does not (see ForceCancelOrder).
// The round conditions quote the group's next round as ExecuteGroup would
// run it at currentTimestamp, so they hold only while that round is due.
func (d *dcaOrderImpl) forceCancelReason(order *pdca.Order, group *pdca.Group, currentTimestamp int64) (string, error) {
	nextRound := group.Round() + 1
	if nextRound > order.EndRound() {
		// Every round executed: Claim completes it.
		return "", makeErrorWithDetails(errOrderNotBlocking, ufmt.Sprintf("orderId(%d) has no round left", order.ID()))
	}

	if order.AmountPerExecution() < d.minAmountPerExecution(group.InputToken()) {
		return forceCancelBelowMinAmount, nil
	}

	// An active order sells in every round up to its last, so it sells in
	// the next one; it blocks rounds only while that round is due.
	if !isGroupExecutable(group, currentTimestamp) {
		return "", makeErrorWithDetails(
			errOrderNotBlocking,
			ufmt.Sprintf("orderId(%d): groupId(%s) has no due round", order.ID(), group.ID()),
		)
	}

	config := d.store.GetConfig()
	whitelistedPools := whitelist.GetWhitelistedPools(whitelist.TargetDCA)
	priceLimit := getPairPriceLimit(d.store.GetPairPriceLimits(), group.InputToken(), group.OutputToken())
	amountIn := group.OrderAmount()

	selectedPool, candidates := selectPool(whitelistedPools, priceLimit, config.MaxPoolPriceDeviationRate(), config.MaxPairPriceLimitAge(), group.InputToken(), group.OutputToken(), amountIn, true)

	if selectedPool == nil {
		// The round is too large only when a pool fills part of it within
		// the price limit, with some output; a missing or stale price limit, a pool
		// past its limit or without a price or liquidity, or a failed quote
		// blocks every order alike.
		if !hasPartialFill(candidates) {
			return "", makeErrorWithDetails(
				errOrderNotBlocking,
				ufmt.Sprintf("orderId(%d): no pool of groupId(%s) fills part of the round", order.ID(), group.ID()),
			)
		}

		// Shrink the round from its largest orders, one per call: a round that
		// needs several orders gone gets them one after the other, while a
		// keeper cannot pick a smaller order instead.
		if d.sellsLargerOrder(group, nextRound, order.AmountPerExecution()) {
			return "", makeErrorWithDetails(
				errOrderNotBlocking,
				ufmt.Sprintf("orderId(%d): a larger order sells in round %d of groupId(%s)", order.ID(), nextRound, group.ID()),
			)
		}

		return forceCancelExceedsPoolCapacity, nil
	}

	outputPerAmountX128, err := pdca.CalculateOutputPerAmountX128(selectedPool.quotedAmountOut, amountIn)
	if err != nil {
		return "", err
	}

	orderAmountOut, err := calculateMinOrderAmountOut(
		feeRateMinAmount{executionFeeRate: order.ExecutionFeeRate(), minAmountPerExecution: order.AmountPerExecution()},
		outputPerAmountX128,
	)
	if err != nil {
		return "", err
	}

	if orderAmountOut < minOrderAmountOutFloor {
		return forceCancelNoOrderOutput, nil
	}

	return "", makeErrorWithDetails(
		errOrderNotBlocking,
		ufmt.Sprintf("orderId(%d) would be credited %d in the next round", order.ID(), orderAmountOut),
	)
}

// hasPartialFill reports whether a candidate pool fills only part of the
// round within the price limit, with some output, so that a smaller round
// may fill. A pool that swaps nothing, such as one without liquidity, also
// reports codePartialFill but cannot fill any smaller round.
func hasPartialFill(candidates []*poolCandidate) bool {
	for _, candidate := range candidates {
		if candidate.ineligibleCode == codePartialFill && candidate.partialAmountOut > 0 {
			return true
		}
	}

	return false
}

// sellsLargerOrder reports whether an order of the group selling in round
// has a larger amountPerExecution than amountPerExecution.
// The amount index sorts a group's orders by fee rate, then amount, so each
// fee rate costs one reverse seek past its finished orders, as in
// getFeeRateMinAmounts.
func (d *dcaOrderImpl) sellsLargerOrder(group *pdca.Group, round uint64, amountPerExecution int64) bool {
	orderAmountsByGroup := d.store.GetOrderAmountsByGroup()
	prefix := pdca.GroupOrderPrefix(group.ID())
	end := pdca.PrefixEnd(prefix)
	start := prefix

	for {
		found := false
		executionFeeRate := int64(0)

		orderAmountsByGroup.Iterate(start, end, func(key string, _ any) bool {
			executionFeeRate = pdca.GroupOrderAmountKeyFeeRate(group.ID(), key)
			found = true

			return true
		})

		if !found {
			return false
		}

		ratePrefix := pdca.GroupOrderFeeRatePrefix(group.ID(), executionFeeRate)
		rateEnd := pdca.PrefixEnd(ratePrefix)
		larger := false

		// The largest selling order of the rate; finished orders, whose last
		// round is before round, are skipped.
		orderAmountsByGroup.ReverseIterate(ratePrefix, rateEnd, func(key string, value any) bool {
			if key >= rateEnd || value.(uint64) < round {
				return false
			}

			larger = pdca.GroupOrderAmountKeyAmount(group.ID(), key) > amountPerExecution

			return true
		})

		if larger {
			return true
		}

		start = rateEnd
	}
}

// orderCancelResult describes a closed order.
type orderCancelResult struct {
	payout         orderPayout
	refundedAmount int64 // unsold input returned to the owner
	isCompleted    bool  // every round had already executed
}

// cancelOrder closes an active order and transfers its output and refund.
// The order's execution fee on its output is kept as pending.
func (d *dcaOrderImpl) cancelOrder(
	_ int,
	rlm realm,
	prevAddr address,
	prevRealm string,
	order *pdca.Order,
	group *pdca.Group,
) (orderCancelResult, error) {
	endAccumulatedX128, isLastRoundExecuted, err := getOrderEndAccumulatedOutputPerAmountX128(order, group)
	if err != nil {
		return orderCancelResult{}, err
	}

	payout, err := calculateOrderPayout(order, endAccumulatedX128)
	if err != nil {
		return orderCancelResult{}, err
	}

	refundedAmount := int64(0)

	if !isLastRoundExecuted {
		remainingRoundCount := order.EndRound() - group.Round()
		refundedAmount = gnsmath.SafeMulInt64(order.AmountPerExecution(), int64(remainingRoundCount))

		groupOrderAmount := gnsmath.SafeSubInt64(group.OrderAmount(), order.AmountPerExecution())
		if err := d.rescheduleGroup(group, groupOrderAmount, group.NextExecutionTimestamp()); err != nil {
			return orderCancelResult{}, err
		}

		roundMark := group.GetRoundMark(order.EndRound())
		if roundMark == nil {
			return orderCancelResult{}, makeErrorWithDetails(errInvalidState, ufmt.Sprintf("missing mark for round %d", order.EndRound()))
		}

		roundMark.SetOrderAmount(gnsmath.SafeSubInt64(roundMark.OrderAmount(), order.AmountPerExecution()))
	}

	order.SetDebtX128(endAccumulatedX128)
	recordOrderPayout(order, payout)
	d.addPendingExecutionFee(group.OutputToken(), payout.executionFeeAmount)

	d.releaseExecutionLogs(prevAddr, prevRealm, order, group, true)

	if err := d.finalizeOrder(order, group); err != nil {
		return orderCancelResult{}, err
	}

	if payout.claimedAmount > 0 {
		common.SafeGRC20Transfer(0, rlm, group.OutputToken(), order.Owner(), payout.claimedAmount)
	}

	if refundedAmount > 0 {
		common.SafeGRC20Transfer(0, rlm, group.InputToken(), order.Owner(), refundedAmount)
	}

	return orderCancelResult{payout: payout, refundedAmount: refundedAmount, isCompleted: isLastRoundExecuted}, nil
}

// Claim pays the order's accrued output to its owner,
// and releases the order's execution logs whose rounds all executed.
// Anyone may call it; the freed storage deposit goes to the caller.
// The order completes once every round executed.
func (d *dcaOrderImpl) Claim(_ int, rlm realm, orderID uint64) int64 {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()
	assertIsNotHalted(halt.OperationWithdraw)
	d.assertIsNotExecuting()

	prev := rlm.Previous()

	order, group, err := d.getOrderWithGroup(orderID)
	if err != nil {
		panic(err.Error())
	}

	payout, _, _, err := d.claimOrder(0, rlm, prev.Address(), prev.PkgPath(), order, group)
	if err != nil {
		panic(err.Error())
	}

	emitPayoutExecutionFee(prev.Address(), prev.PkgPath(), group, payout.executionFeeAmount, d.pendingExecutionFeeAmount(group.OutputToken()))

	return payout.claimedAmount
}

// claimOrder pays an active order's accrued output, net of its execution
// fee, to its owner, completing the order once its last round ran,
// and releases its execution logs whose rounds all executed.
// The execution fee is kept as pending for the protocol fee realm.
// It returns the payout, the number of logs released,
// and whether anything was paid or completed.
func (d *dcaOrderImpl) claimOrder(
	_ int,
	rlm realm,
	prevAddr address,
	prevRealm string,
	order *pdca.Order,
	group *pdca.Group,
) (orderPayout, int64, bool, error) {
	endAccumulatedX128, isLastRoundExecuted, err := getOrderEndAccumulatedOutputPerAmountX128(order, group)
	if err != nil {
		return orderPayout{}, 0, false, err
	}

	payout, err := calculateOrderPayout(order, endAccumulatedX128)
	if err != nil {
		return orderPayout{}, 0, false, err
	}

	// Nothing accrued or to finalize: skip the payout writes and events,
	// so anyone calling Claim cannot spam the owner's event history.
	if payout.grossAmount == 0 && !isLastRoundExecuted {
		releasedCount := d.releaseExecutionLogs(prevAddr, prevRealm, order, group, false)
		return orderPayout{}, releasedCount, false, nil
	}

	// An active order's debt moves only by the gross output paid,
	// so the remainder below one unit stays owed until later rounds
	// add it up to a whole unit; a completed order settles at its end.
	nextDebtX128 := endAccumulatedX128
	if !isLastRoundExecuted {
		nextDebtX128, err = calculateDebtX128AfterPayout(order.AmountPerExecution(), order.DebtX128(), payout.grossAmount)
		if err != nil {
			return orderPayout{}, 0, false, err
		}
	}

	order.SetDebtX128(nextDebtX128)
	recordOrderPayout(order, payout)
	d.addPendingExecutionFee(group.OutputToken(), payout.executionFeeAmount)

	releasedCount := d.releaseExecutionLogs(prevAddr, prevRealm, order, group, isLastRoundExecuted)

	status := pdca.OrderStatusActive
	if isLastRoundExecuted {
		status = pdca.OrderStatusCompleted

		if err := d.finalizeOrder(order, group); err != nil {
			return orderPayout{}, 0, false, err
		}
	}

	if payout.claimedAmount > 0 {
		common.SafeGRC20Transfer(0, rlm, group.OutputToken(), order.Owner(), payout.claimedAmount)
	}

	emitOrderClaimed(prevAddr, prevRealm, order, group, payout, status)

	return payout, releasedCount, true, nil
}

// releaseExecutionLogs releases the order's logs whose rounds all executed,
// or every log of an order being finalized,
// so the freed storage deposit is refunded to the caller.
// Call it before finalizeOrder deletes the order.
func (d *dcaOrderImpl) releaseExecutionLogs(prevAddr address, prevRealm string, order *pdca.Order, group *pdca.Group, isFinalized bool) int64 {
	executionLogs := d.store.GetExecutionLogs()

	releasedCount := int64(0)
	if isFinalized {
		releasedCount = pdca.ReleaseAllExecutionLogs(executionLogs, order)
	} else {
		releasedCount = pdca.ReleaseExecutionLogs(executionLogs, order, group.Round())
	}

	if releasedCount > 0 {
		emitExecutionLogsReleased(prevAddr, prevRealm, order, group, releasedCount)
	}

	return releasedCount
}

// finalizeOrder releases a completed or cancelled order from its group
// and deletes all of its stored data: the order record, its owner and
// group index entries, and its end-round mark once no order references it.
// A finished order's amount index entry may already be pruned by a round.
//
// Freeing the storage refunds its deposit to the transaction signer,
// which pays keepers that finalize orders through ClaimGroupOrders.
// The order's final state is kept in the emitted event, not in state.
func (d *dcaOrderImpl) finalizeOrder(order *pdca.Order, group *pdca.Group) error {
	if err := releaseRoundMark(group, order.EndRound()); err != nil {
		return err
	}

	group.SetActiveOrderCount(group.ActiveOrderCount() - 1)

	d.store.GetOrders().Remove(pdca.OrderKey(order.ID()))
	d.store.GetOrdersByOwner().Remove(pdca.OwnerOrderKey(order.Owner(), order.ID()))
	d.store.GetOrdersByGroup().Remove(pdca.GroupOrderKey(group.ID(), order.ID()))
	d.store.GetOrderAmountsByGroup().Remove(pdca.GroupOrderAmountKey(group.ID(), order.ExecutionFeeRate(), order.AmountPerExecution(), order.ID()))

	return nil
}

pool_selection.gno

package impl

import (
	"errors"
	"sort"
	"strconv"

	pdca "gno.land/p/gnoswap/order/dca/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/pool"
)

// Pool selection.
//
// A round trades on one direct pool of the pair, chosen at execution time:
//
//  1. candidates: whitelisted pools of the pair, one per fee tier, by fee
//  2. price limit: each pool sells only down to the pair price limit
//     (see price_limit.gno); a pair direction without a limit, a pool
//     already past it, or a pool displaced far on its favorable side
//     (Config.MaxPoolPriceDeviationRate) is ineligible without a quote, and
//     so is every pool while the limit is older than
//     Config.MaxPairPriceLimitAge
//  3. ranking: the pool whose DrySwap of the full round amount, within its
//     price limit, returns the most output, consuming all input;
//     ties keep the lower fee
//
// The price limit bounds the ticks a quote or a swap may cross, so a pool
// without liquidity near its price costs bounded gas and is simply ineligible
// when it cannot fill the round within the limit. Liquidity outside the
// current tick still counts.
//
// To save gas, a round quotes only when the pair has two or more pools.
// A single pool is used directly; the round reverts
// if that pool cannot absorb the full input within the limit.

// poolCandidate is one pool of the pair and its evaluation for a round.
type poolCandidate struct {
	poolPath          string
	fee               uint32
	sqrtPriceLimitX96 string // swap price limit under the pair price limit
	ineligibleCode    string // why the pool is ineligible, as a code; "" when eligible
	ineligibleReason  string // ineligibleCode in words, with details
	isQuoted          bool
	quotedAmountOut   int64 // pool output for the full round
	partialAmountOut  int64 // pool output of the consumed input of a partial fill; 0 otherwise
}

func (c *poolCandidate) isEligible() bool { return c.ineligibleCode == "" }

// poolWhitelist is the read-only membership contract used by pool selection.
// Production passes the common whitelist realm's read-only view; focused
// selection tests use an in-memory tree.
type poolWhitelist interface {
	Has(key string) bool
}

// getCandidatePools returns the whitelisted pools of the pair,
// ordered by fee tier.
func getCandidatePools(whitelistedPools poolWhitelist, inputToken string, outputToken string) []*poolCandidate {
	tickSpacings := pool.GetFeeAmountTickSpacings()

	fees := make([]int, 0, len(tickSpacings))
	for fee := range tickSpacings {
		fees = append(fees, int(fee))
	}

	sort.Ints(fees)

	candidates := []*poolCandidate{}

	for _, fee := range fees {
		poolPath := pool.GetPoolPath(inputToken, outputToken, uint32(fee))
		if whitelistedPools.Has(poolPath) && pool.ExistsPoolPath(poolPath) {
			candidates = append(candidates, &poolCandidate{poolPath: poolPath, fee: uint32(fee)})
		}
	}

	return candidates
}

// selectPool evaluates the pair's whitelisted pools for a round of amountIn
// under limit, the pair price limit (nil if none is set), and
// maxDeviationRate (Config.MaxPoolPriceDeviationRate), and maxLimitAge
// (Config.MaxPairPriceLimitAge), and returns the chosen
// pool (nil if none can fill it) with all candidates.
// quoteAll quotes every pool, even when the pair has only one.
func selectPool(
	whitelistedPools poolWhitelist,
	limit *pdca.PairPriceLimit,
	maxDeviationRate int64,
	maxLimitAge int64,
	inputToken string,
	outputToken string,
	amountIn int64,
	quoteAll bool,
) (*poolCandidate, []*poolCandidate) {
	candidates := getCandidatePools(whitelistedPools, inputToken, outputToken)
	if len(candidates) == 0 {
		return nil, candidates
	}

	zeroForOne, _, _ := swapDirection(inputToken, outputToken)
	for _, candidate := range candidates {
		candidate.sqrtPriceLimitX96, candidate.ineligibleCode, candidate.ineligibleReason = poolSqrtPriceLimit(
			candidate.poolPath, candidate.fee, zeroForOne, limit, maxDeviationRate, maxLimitAge,
		)
	}

	if len(candidates) == 1 && !quoteAll {
		if !candidates[0].isEligible() {
			return nil, candidates
		}

		return candidates[0], candidates
	}

	var bestCandidate *poolCandidate

	for _, candidate := range candidates {
		if !candidate.isEligible() {
			continue
		}

		quotedAmountOut, code, err := quoteExactIn(inputToken, outputToken, candidate.fee, candidate.sqrtPriceLimitX96, amountIn)
		if err != nil {
			candidate.ineligibleCode = code
			candidate.ineligibleReason = err.Error()

			if code == codePartialFill {
				candidate.partialAmountOut = quotedAmountOut
			}

			continue
		}

		candidate.isQuoted = true
		candidate.quotedAmountOut = quotedAmountOut

		if bestCandidate == nil || quotedAmountOut > bestCandidate.quotedAmountOut {
			bestCandidate = candidate
		}
	}

	return bestCandidate, candidates
}

// quoteReferenceAmountOut quotes selling amountIn at once, now, on the pair's
// best whitelisted pool within the pair price limit: what a one-off swap of
// the whole order would return. Order fills are measured against it. It is 0
// when no pool can absorb the whole amount within the limit.
func quoteReferenceAmountOut(
	whitelistedPools poolWhitelist,
	limit *pdca.PairPriceLimit,
	maxDeviationRate int64,
	maxLimitAge int64,
	inputToken string,
	outputToken string,
	amountIn int64,
) int64 {
	selectedPool, _ := selectPool(whitelistedPools, limit, maxDeviationRate, maxLimitAge, inputToken, outputToken, amountIn, true)
	if selectedPool == nil {
		return 0
	}

	return selectedPool.quotedAmountOut
}

// selectRoundPool is selectPool for execution. When no pool can fill the
// round, it returns an error listing each candidate's reason.
// A pair without a whitelisted pool has no candidates.
func selectRoundPool(
	whitelistedPools poolWhitelist,
	limit *pdca.PairPriceLimit,
	maxDeviationRate int64,
	maxLimitAge int64,
	group *pdca.Group,
	amountIn int64,
) (*poolCandidate, error) {
	selectedPool, candidates := selectPool(whitelistedPools, limit, maxDeviationRate, maxLimitAge, group.InputToken(), group.OutputToken(), amountIn, false)
	if selectedPool != nil {
		return selectedPool, nil
	}

	details := ufmt.Sprintf("groupId(%s)", group.ID())
	for _, candidate := range candidates {
		details += ufmt.Sprintf("; %s: %s", candidate.poolPath, candidate.ineligibleReason)
	}

	return nil, makeErrorWithDetails(errNoEligiblePool, details)
}

// quoteExactIn simulates selling amountIn on the pair's pool of fee tier fee,
// down to sqrtPriceLimitX96, and returns the pool output.
// It fails unless the whole input is consumed within the limit, and then
// also returns the ineligibility code of the failure. A partial fill
// (codePartialFill) returns the output of the input it consumed, 0 when the
// pool swapped nothing, such as one without liquidity; every other failure
// returns 0.
func quoteExactIn(inputToken string, outputToken string, fee uint32, sqrtPriceLimitX96 string, amountIn int64) (int64, string, error) {
	zeroForOne, token0, token1 := swapDirection(inputToken, outputToken)

	amount0, amount1, err := pool.DrySwap(token0, token1, fee, zeroForOne, strconv.FormatInt(amountIn, 10), sqrtPriceLimitX96)
	if err != nil {
		return 0, codeQuoteFailed, err
	}

	consumedAmount, outputAmount := amount0, amount1
	if !zeroForOne {
		consumedAmount, outputAmount = amount1, amount0
	}

	consumedAmountIn, err := strconv.ParseInt(consumedAmount, 10, 64)
	if err != nil {
		return 0, codeQuoteFailed, err
	}

	amountOut, err := strconv.ParseInt(outputAmount, 10, 64)
	if err != nil {
		return 0, codeQuoteFailed, err
	}

	if consumedAmountIn != amountIn {
		partialAmountOut := int64(0)
		if consumedAmountIn > 0 && amountOut < 0 {
			partialAmountOut = -amountOut
		}

		return partialAmountOut, codePartialFill, ufmt.Errorf("quote consumed %d of %d input", consumedAmountIn, amountIn)
	}

	if amountOut >= 0 {
		return 0, codeNoOutput, errors.New("quote returned no output")
	}

	return -amountOut, "", nil
}

price_limit.gno

package impl

import (
	"time"

	pdca "gno.land/p/gnoswap/order/dca/v0"
	u256 "gno.land/p/gnoswap/uint256/v1"
	bptree "gno.land/p/nt/bptree/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/pool"
)

// Pair price limits.
//
// A pair direction (inputToken -> outputToken) trades only with a price limit
// set by the pool manager from an oracle price: minOutputPerInputX128,
// the least pool output, in raw outputToken units before the execution fee,
// per raw inputToken unit, in Q128.
//
// Every quote and swap of the pair passes it to the pool as sqrtPriceLimitX96,
// after removing the pool's fee tier, so that:
//   - each unit of input is filled at a marginal rate of at least the limit,
//     which bounds what a round can lose to a moved pool price,
//     even when the keeper passes a loose amountOutMin;
//   - the pool walks ticks only between its current price and the limit,
//     which bounds the gas of a quote or a round on a pool without enough
//     liquidity near its price.
//
// A pool whose price is already past the limit is ineligible: it would have
// to sell at a worse rate than the limit from the first unit.
//
// A pool whose price sits far on the favorable side of the limit is
// ineligible too (Config.MaxPoolPriceDeviationRate): the limit derives from an
// oracle price, not from each pool's price, so a pool displaced far from the
// oracle price, such as an empty pool or one pushed past its liquidity, would
// make its quote or swap walk every tick between its price and the limit.
//
// A limit set more than Config.MaxPairPriceLimitAge seconds ago leaves every
// pool ineligible: the oracle price behind it may be gone, so rounds wait for
// the pool manager to refresh it instead of trading at a stale price.

// Sqrt price bounds a swap price limit is clamped to; the pool requires
// a limit strictly inside (MIN_SQRT_RATIO, MAX_SQRT_RATIO).
const (
	minSqrtRatioPlusOne  = "4295128740"
	maxSqrtRatioMinusOne = "1461446703485210103287273052203988822378723970341"
)

// poolFeeDenominator is the denominator of pool fee tiers (3000 is 0.3%).
const poolFeeDenominator uint64 = 1_000_000

const q96Shift uint = 96

// Ineligibility codes of a candidate pool, reported by GetExecutionQuote as
// ineligibleCode next to the human-readable ineligibleReason. Keepers classify
// a blocked round by code, never by reason text; "" means eligible.
const (
	codeNoPriceLimit     = "no_price_limit"    // the pair direction has no limit
	codePriceLimitStale  = "price_limit_stale" // the limit is older than its maximum age
	codePricePastLimit   = "price_past_limit"  // the pool price is already past the limit
	codePriceDisplaced   = "price_displaced"   // the pool price is too far on the favorable side
	codePriceUnavailable = "price_unavailable" // the pool price could not be read
	codePartialFill      = "partial_fill"      // the quote fills only part of the input
	codeNoOutput         = "no_output"         // the quote returns no output
	codeQuoteFailed      = "quote_failed"      // the pool rejected the quote
)

const (
	reasonNoPriceLimit     = "no price limit for the pair"
	reasonPriceLimitStale  = "pair price limit is older than its maximum age"
	reasonInvalidLimitAge  = "invalid max pair price limit age"
	reasonPricePastLimit   = "pool price is past the pair price limit"
	reasonPriceDisplaced   = "pool price deviates too far from the pair price limit"
	reasonPoolPriceAbsent  = "pool price unavailable"
	reasonInvalidDeviation = "invalid max pool price deviation rate"
)

// getPairPriceLimit returns the price limit of selling inputToken for
// outputToken, or nil if none is set.
func getPairPriceLimit(pairPriceLimits *bptree.BPTree, inputToken string, outputToken string) *pdca.PairPriceLimit {
	value := pairPriceLimits.Get(pdca.PairKey(inputToken, outputToken))
	if value == nil {
		return nil
	}

	return value.(*pdca.PairPriceLimit)
}

// calculateSqrtPriceLimitX96 converts minOutputPerInputX128 into the sqrt
// price limit of a swap on a pool of fee tier fee in the given direction,
// clamped to the range the pool accepts.
//
// The pool takes its fee from the input, so the marginal rate of a unit of
// input is P*(1-fee) selling token0 (P = token1 per token0) and (1-fee)/P
// selling token1. Requiring that rate to stay at or above L gives:
//
//	zeroForOne: P >= L/(1-fee), a lower bound, rounded up
//	oneForZero: P <= (1-fee)/L, an upper bound, rounded down
//
// so the rounding never loosens the limit.
func calculateSqrtPriceLimitX96(minOutputPerInputX128 *u256.Uint, fee uint32, zeroForOne bool) *u256.Uint {
	minSqrtPrice := u256.MustFromDecimal(minSqrtRatioPlusOne)
	maxSqrtPrice := u256.MustFromDecimal(maxSqrtRatioMinusOne)

	if minOutputPerInputX128.IsZero() {
		// No output floor: the bound the pool never reaches.
		if zeroForOne {
			return minSqrtPrice
		}

		return maxSqrtPrice
	}

	feeDenominator := u256.NewUint(poolFeeDenominator)
	feeComplement := u256.NewUint(poolFeeDenominator - uint64(fee))

	var priceX128 *u256.Uint

	if zeroForOne {
		// priceX128 = L_X128 / (1-fee), rounded up.
		if minOutputPerInputX128.BitLen() > 250 {
			return maxSqrtPrice
		}

		priceX128 = u256.MulDivRoundingUp(minOutputPerInputX128, feeDenominator, feeComplement)
	} else {
		// priceX128 = (2^256 / L_X128) * (1-fee), rounded down.
		if minOutputPerInputX128.Lt(u256.NewUint(2)) {
			return maxSqrtPrice
		}

		q128 := u256.One().Lsh(u256.One(), 128)
		inverseX128 := u256.MulDiv(q128, q128, minOutputPerInputX128)
		priceX128 = u256.MulDiv(inverseX128, feeComplement, feeDenominator)
	}

	sqrtPriceX96 := sqrtX128ToSqrtX96(priceX128, zeroForOne)

	if sqrtPriceX96.Lt(minSqrtPrice) {
		return minSqrtPrice
	}

	if sqrtPriceX96.Gt(maxSqrtPrice) {
		return maxSqrtPrice
	}

	return sqrtPriceX96
}

// sqrtX128ToSqrtX96 returns sqrt(priceX128 / 2^128) * 2^96,
// that is sqrt(priceX128 * 2^64), rounded up when roundUp is set.
// A priceX128 too large to shift by 64 bits is shifted by 64-2k bits and the
// root by k bits instead, which keeps the result within one part in 2^96.
func sqrtX128ToSqrtX96(priceX128 *u256.Uint, roundUp bool) *u256.Uint {
	k := uint(0)
	if bitLen := priceX128.BitLen() + 64; bitLen > 255 {
		k = uint(bitLen-255+1) / 2
	}

	var value *u256.Uint
	if 2*k <= 64 {
		value = u256.Zero().Lsh(priceX128, 64-2*k)
	} else {
		value = u256.Zero().Rsh(priceX128, 2*k-64)
	}

	root := sqrtUint256(value)

	if roundUp && !u256.Zero().Mul(root, root).Eq(value) {
		root = u256.Zero().Add(root, u256.One())
	}

	return u256.Zero().Lsh(root, k)
}

// sqrtUint256 returns floor(sqrt(x)) by Newton's method.
func sqrtUint256(x *u256.Uint) *u256.Uint {
	if x.IsZero() {
		return u256.Zero()
	}

	// Start above the root: 2^ceil(bitLen/2).
	z := u256.Zero().Lsh(u256.One(), uint((x.BitLen()+1)/2))

	for {
		// next = (z + x/z) / 2
		next := u256.Zero().Add(z, u256.Zero().Div(x, z))
		next = next.Rsh(next, 1)

		if next.Gte(z) {
			return z
		}

		z = next
	}
}

// poolSqrtPriceLimit returns the sqrt price limit of selling on poolPath under
// limit, or why the pool cannot trade under it. maxDeviationRate, in basis
// points of price, bounds how far the pool's price may sit on the favorable
// side of the limit (see isDisplacedPool); 0 disables that check.
// maxLimitAge, in seconds, is how old the limit may be (see isStalePriceLimit).
//
// It returns the limit, or the ineligibility code and reason.
func poolSqrtPriceLimit(poolPath string, fee uint32, zeroForOne bool, limit *pdca.PairPriceLimit, maxDeviationRate int64, maxLimitAge int64) (string, string, string) {
	if limit == nil {
		return "", codeNoPriceLimit, reasonNoPriceLimit
	}

	stale, err := isStalePriceLimit(limit, maxLimitAge, time.Now().Unix())
	if err != nil {
		// The age is validated when set; an invalid one excludes the pool.
		return "", codePriceLimitStale, reasonInvalidLimitAge
	}

	if stale {
		return "", codePriceLimitStale, reasonPriceLimitStale
	}

	currentSqrtPrice, err := pool.GetSlot0SqrtPriceX96(poolPath)
	if err != nil {
		return "", codePriceUnavailable, reasonPoolPriceAbsent
	}

	current, err := u256.FromDecimal(currentSqrtPrice)
	if err != nil {
		return "", codePriceUnavailable, reasonPoolPriceAbsent
	}

	sqrtPriceLimit := calculateSqrtPriceLimitX96(limit.MinOutputPerInputX128(), fee, zeroForOne)

	// The pool requires the limit strictly on the side the price moves to.
	if zeroForOne && !sqrtPriceLimit.Lt(current) {
		return "", codePricePastLimit, reasonPricePastLimit
	}

	if !zeroForOne && !sqrtPriceLimit.Gt(current) {
		return "", codePricePastLimit, reasonPricePastLimit
	}

	displaced, err := isDisplacedPool(current, sqrtPriceLimit, zeroForOne, maxDeviationRate)
	if err != nil {
		// The rate is validated when set; an invalid one excludes the pool.
		return "", codePriceDisplaced, reasonInvalidDeviation
	}

	if displaced {
		return "", codePriceDisplaced, reasonPriceDisplaced
	}

	return sqrtPriceLimit.ToString(), "", ""
}

// isStalePriceLimit reports whether limit was set more than maxLimitAge
// seconds before currentTimestamp. A non-positive maxLimitAge is invalid:
// a stored config without the age fails closed instead of disabling the check.
func isStalePriceLimit(limit *pdca.PairPriceLimit, maxLimitAge int64, currentTimestamp int64) (bool, error) {
	if maxLimitAge <= 0 {
		return false, makeErrorWithDetails(errInvalidConfig, ufmt.Sprintf("maxPairPriceLimitAge(%d)", maxLimitAge))
	}

	return currentTimestamp-limit.UpdatedAt() > maxLimitAge, nil
}

// isDisplacedPool reports whether the pool price sits more than
// maxDeviationRate, in basis points of price, on the favorable side of the
// swap price limit; 0 disables the check.
//
// Prices are compared through their square roots:
// P_current / P_limit > 1 + rate  <=>  sqrtCurrent > sqrtLimit * sqrt(1 + rate)
// when selling token0, and the reciprocal when selling token1.
func isDisplacedPool(currentSqrtPriceX96 *u256.Uint, sqrtPriceLimitX96 *u256.Uint, zeroForOne bool, maxDeviationRate int64) (bool, error) {
	if maxDeviationRate == 0 {
		return false, nil
	}

	if maxDeviationRate < 0 || maxDeviationRate > pdca.BasisPointDenominator {
		return false, makeErrorWithDetails(errInvalidConfig, ufmt.Sprintf("maxPoolPriceDeviationRate(%d)", maxDeviationRate))
	}

	// factorX96 = sqrt(1 + rate) * 2^96, rounded down.
	ratioX192 := u256.MulDiv(
		u256.NewUint(uint64(pdca.BasisPointDenominator+maxDeviationRate)),
		u256.Zero().Lsh(u256.One(), 2*q96Shift),
		u256.NewUint(uint64(pdca.BasisPointDenominator)),
	)
	factorX96 := sqrtUint256(ratioX192)
	q96 := u256.Zero().Lsh(u256.One(), q96Shift)

	if zeroForOne {
		// The price falls toward the limit: displaced when the pool price is
		// above limit * (1 + rate).
		threshold := u256.MulDiv(sqrtPriceLimitX96, factorX96, q96)
		return currentSqrtPriceX96.Gt(threshold), nil
	}

	// The price rises toward the limit: displaced when the pool price is
	// below limit / (1 + rate).
	scaledCurrent := u256.MulDiv(currentSqrtPriceX96, factorX96, q96)

	return scaledCurrent.Lt(sqrtPriceLimitX96), nil
}

// parseMinOutputPerInputX128 parses a decimal Q128 price limit.
func parseMinOutputPerInputX128(value string) (*u256.Uint, error) {
	parsed, err := u256.FromDecimal(value)
	if err != nil {
		return nil, makeErrorWithDetails(errInvalidPriceLimit, ufmt.Sprintf("minOutputPerInputX128(%s): %s", value, err.Error()))
	}

	return parsed, nil
}

swap.gno

package impl

import (
	"strconv"

	pdca "gno.land/p/gnoswap/order/dca/v0"
	ufmt "gno.land/p/nt/ufmt/v0"

	"gno.land/r/gnoswap/common"
	dca "gno.land/r/gnoswap/order/dca"
	"gno.land/r/gnoswap/pool"
)

// swapDirection returns the pool direction of selling inputToken for
// outputToken and the pool's token order.
func swapDirection(inputToken string, outputToken string) (zeroForOne bool, token0 string, token1 string) {
	if inputToken < outputToken {
		return true, inputToken, outputToken
	}

	return false, outputToken, inputToken
}

// swapExactIn sells amountIn on the pair's pool of fee tier fee, down to
// sqrtPriceLimitX96 (see calculateSqrtPriceLimitX96), and returns the output
// received by the escrow. A pool that reaches the limit before selling the
// whole input fails the round.
//
// The pool sends the output first, then calls the escrow's swap callback,
// which pays the input from the escrow without any allowance (see
// dca.NewSwapCallback). The pool result is checked against the escrow's
// balance changes: the whole input must be sold, and the output must reach
// amountOutMin (0 disables it).
func swapExactIn(_ int, rlm realm, group *pdca.Group, fee uint32, sqrtPriceLimitX96 string, amountIn int64, amountOutMin int64) (int64, error) {
	escrowAddress := rlm.Address()
	inputToken := group.InputToken()
	outputToken := group.OutputToken()
	zeroForOne, token0, token1 := swapDirection(inputToken, outputToken)

	inputBalanceBefore := common.BalanceOf(inputToken, escrowAddress)
	outputBalanceBefore := common.BalanceOf(outputToken, escrowAddress)

	amount0, amount1 := pool.Swap(
		cross(rlm),
		token0,
		token1,
		fee,
		escrowAddress,
		zeroForOne,
		strconv.FormatInt(amountIn, 10),
		sqrtPriceLimitX96,
		dca.NewSwapCallback(0, rlm, inputToken, zeroForOne, amountIn),
	)

	// Pool deltas: positive is owed to the pool, negative is sent out.
	poolAmountIn, poolAmountOut := amount0, amount1
	if !zeroForOne {
		poolAmountIn, poolAmountOut = amount1, amount0
	}

	spentAmount := inputBalanceBefore - common.BalanceOf(inputToken, escrowAddress)
	receivedAmount := common.BalanceOf(outputToken, escrowAddress) - outputBalanceBefore

	poolInDelta, err := strconv.ParseInt(poolAmountIn, 10, 64)
	if err != nil || spentAmount != amountIn || poolInDelta != amountIn {
		return 0, makeErrorWithDetails(
			errSwapMismatch,
			ufmt.Sprintf("input spent(%d) pool(%s) expected(%d)", spentAmount, poolAmountIn, amountIn),
		)
	}

	poolOutDelta, err := strconv.ParseInt(poolAmountOut, 10, 64)
	if err != nil || receivedAmount < 0 || poolOutDelta != -receivedAmount {
		return 0, makeErrorWithDetails(
			errSwapMismatch,
			ufmt.Sprintf("output received(%d) pool(%s)", receivedAmount, poolAmountOut),
		)
	}

	if receivedAmount < amountOutMin {
		return 0, makeErrorWithDetails(
			errInsufficientSwapOutput,
			ufmt.Sprintf("output(%d) amountOutMin(%d)", receivedAmount, amountOutMin),
		)
	}

	return receivedAmount, nil
}

utils.gno

package impl

import (
	"gno.land/p/gnoswap/gnsmath/v1"
	pdca "gno.land/p/gnoswap/order/dca/v0"
	u256 "gno.land/p/gnoswap/uint256/v1"
	ufmt "gno.land/p/nt/ufmt/v0"
)

// calculatePayout wraps pdca.CalculatePayout,
// reporting a backwards accumulator as invalid state.
func calculatePayout(amountPerExecution int64, endAccumulatedX128 *u256.Uint, debtX128 *u256.Uint) (int64, error) {
	payoutAmount, err := pdca.CalculatePayout(amountPerExecution, endAccumulatedX128, debtX128)
	if err != nil {
		return 0, makeErrorWithDetails(errInvalidState, err.Error())
	}

	return payoutAmount, nil
}

// orderPayout is one payout of an order's accrued output.
type orderPayout struct {
	grossAmount        int64 // accrued output paid out
	executionFeeAmount int64 // the order's execution fee on grossAmount
	claimedAmount      int64 // grossAmount - executionFeeAmount, sent to the owner
}

// calculateOrderPayout returns the payout of the output the order accrued up
// to endAccumulatedX128, with the order's execution fee deducted on its
// cumulative gross output (see pdca.CalculatePayoutExecutionFeeAmount).
func calculateOrderPayout(order *pdca.Order, endAccumulatedX128 *u256.Uint) (orderPayout, error) {
	grossAmount, err := calculatePayout(order.AmountPerExecution(), endAccumulatedX128, order.DebtX128())
	if err != nil {
		return orderPayout{}, err
	}

	executionFeeAmount, err := pdca.CalculatePayoutExecutionFeeAmount(order.PaidGrossAmount(), grossAmount, order.ExecutionFeeRate())
	if err != nil {
		return orderPayout{}, makeErrorWithDetails(errInvalidState, err.Error())
	}

	return orderPayout{
		grossAmount:        grossAmount,
		executionFeeAmount: executionFeeAmount,
		claimedAmount:      gnsmath.SafeSubInt64(grossAmount, executionFeeAmount),
	}, nil
}

// recordOrderPayout adds a payout to the order's lifetime
// claimed amount and execution fee.
func recordOrderPayout(order *pdca.Order, payout orderPayout) {
	order.SetClaimedAmount(u256.Zero().Add(order.ClaimedAmount(), u256.NewUint(uint64(payout.claimedAmount))))
	order.SetExecutionFeeAmount(u256.Zero().Add(order.ExecutionFeeAmount(), u256.NewUint(uint64(payout.executionFeeAmount))))
}

// calculateDebtX128AfterPayout wraps pdca.CalculateDebtX128AfterPayout,
// reporting an invalid payout as invalid state.
func calculateDebtX128AfterPayout(amountPerExecution int64, debtX128 *u256.Uint, payoutAmount int64) (*u256.Uint, error) {
	nextDebtX128, err := pdca.CalculateDebtX128AfterPayout(amountPerExecution, debtX128, payoutAmount)
	if err != nil {
		return nil, makeErrorWithDetails(errInvalidState, err.Error())
	}

	return nextDebtX128, nil
}

// getOrderEndAccumulatedOutputPerAmountX128 returns the accumulator an order
// is paid against, and whether all of its rounds have executed.
func getOrderEndAccumulatedOutputPerAmountX128(order *pdca.Order, group *pdca.Group) (*u256.Uint, bool, error) {
	if group.Round() < order.EndRound() {
		return group.AccumulatedOutputPerAmountX128(), false, nil
	}

	roundMark := group.GetRoundMark(order.EndRound())
	if roundMark == nil {
		return nil, false, makeErrorWithDetails(errInvalidState, ufmt.Sprintf("missing snapshot for round %d", order.EndRound()))
	}

	return roundMark.AccumulatedOutputPerAmountX128(), true, nil
}

// releaseRoundMark drops one order reference from its end-round mark,
// removing the mark once no order references it.
func releaseRoundMark(group *pdca.Group, round uint64) error {
	roundMark := group.GetRoundMark(round)
	if roundMark == nil {
		return makeErrorWithDetails(errInvalidState, ufmt.Sprintf("missing mark for round %d", round))
	}

	orderCount := roundMark.OrderCount() - 1
	if orderCount < 0 {
		return makeErrorWithDetails(errInvalidState, ufmt.Sprintf("negative order count for round %d", round))
	}

	if orderCount > 0 {
		roundMark.SetOrderCount(orderCount)
		return nil
	}

	if round > group.Round() && roundMark.OrderAmount() != 0 {
		return makeErrorWithDetails(errInvalidState, ufmt.Sprintf("unexecuted mark %d still has order amount", round))
	}

	group.RemoveRoundMark(round)

	return nil
}

// feeRateMinAmount is the smallest amountPerExecution of the orders with
// one execution fee rate that sell in a round.
type feeRateMinAmount struct {
	executionFeeRate      int64
	minAmountPerExecution int64
}

// getFeeRateMinAmounts returns, by ascending execution fee rate, the
// smallest amountPerExecution of the group's orders of each fee rate that
// sell in round; it is empty when no order does.
// The amount index sorts a group's orders by fee rate, then amount,
// so each rate costs one seek past the finished orders before its first
// selling one, and the number of seeks is the number of fee rates indexed.
// The amount index keeps finished orders until they are paid out;
// with prune, the entries of orders whose last round is before round
// are removed on the way, as no later round sells them.
func (d *dcaOrderImpl) getFeeRateMinAmounts(group *pdca.Group, round uint64, prune bool) []feeRateMinAmount {
	orderAmountsByGroup := d.store.GetOrderAmountsByGroup()
	prefix := pdca.GroupOrderPrefix(group.ID())
	end := pdca.PrefixEnd(prefix)

	minAmounts := []feeRateMinAmount{}
	finishedKeys := []string{}
	start := prefix

	for {
		found := false
		executionFeeRate := int64(0)
		minAmountPerExecution := int64(0)

		orderAmountsByGroup.Iterate(start, end, func(key string, value any) bool {
			if value.(uint64) < round {
				if prune {
					finishedKeys = append(finishedKeys, key)
				}

				return false
			}

			executionFeeRate = pdca.GroupOrderAmountKeyFeeRate(group.ID(), key)
			minAmountPerExecution = pdca.GroupOrderAmountKeyAmount(group.ID(), key)
			found = true

			return true
		})

		if !found {
			break
		}

		minAmounts = append(minAmounts, feeRateMinAmount{
			executionFeeRate:      executionFeeRate,
			minAmountPerExecution: minAmountPerExecution,
		})

		// Skip the larger orders of this rate.
		start = pdca.PrefixEnd(pdca.GroupOrderFeeRatePrefix(group.ID(), executionFeeRate))
	}

	for _, key := range finishedKeys {
		orderAmountsByGroup.Remove(key)
	}

	return minAmounts
}

// minAmountPerExecutionOf returns the smallest amountPerExecution of
// minAmounts, or 0 when it is empty.
func minAmountPerExecutionOf(minAmounts []feeRateMinAmount) int64 {
	minAmountPerExecution := int64(0)

	for i, minAmount := range minAmounts {
		if i == 0 || minAmount.minAmountPerExecution < minAmountPerExecution {
			minAmountPerExecution = minAmount.minAmountPerExecution
		}
	}

	return minAmountPerExecution
}

// maxExecutionFeeRateOf returns the highest execution fee rate of
// minAmounts, or 0 when it is empty.
func maxExecutionFeeRateOf(minAmounts []feeRateMinAmount) int64 {
	maxExecutionFeeRate := int64(0)

	for _, minAmount := range minAmounts {
		if minAmount.executionFeeRate > maxExecutionFeeRate {
			maxExecutionFeeRate = minAmount.executionFeeRate
		}
	}

	return maxExecutionFeeRate
}

// calculateMinOrderAmountOut returns the output, net of its own execution
// fee rate, the order of minAmount is credited at outputPerAmountX128.
func calculateMinOrderAmountOut(minAmount feeRateMinAmount, outputPerAmountX128 *u256.Uint) (int64, error) {
	grossAmountOut, err := pdca.CalculatePayout(minAmount.minAmountPerExecution, outputPerAmountX128, u256.Zero())
	if err != nil {
		return 0, err
	}

	return pdca.CalculateMinNetAmountOut(grossAmountOut, minAmount.executionFeeRate)
}

func getScheduleKey(group *pdca.Group) string {
	return pdca.ScheduleKey(group.NextExecutionTimestamp(), group.ID())
}

// rescheduleGroup sets a group's order amount and next execution timestamp,
// keeping the schedule index in sync.
// Only groups with a positive order amount are indexed.
func (d *dcaOrderImpl) rescheduleGroup(group *pdca.Group, orderAmount int64, nextExecutionTimestamp int64) error {
	if orderAmount < 0 {
		return makeErrorWithDetails(errInvalidState, ufmt.Sprintf("negative order amount for group %s", group.ID()))
	}

	scheduledGroups := d.store.GetScheduledGroups()
	if group.OrderAmount() > 0 {
		scheduledGroups.Remove(getScheduleKey(group))
	}

	group.SetOrderAmount(orderAmount)
	group.SetNextExecutionTimestamp(nextExecutionTimestamp)

	if orderAmount > 0 {
		scheduledGroups.Set(getScheduleKey(group), group.ID())
	}

	return nil
}

func (d *dcaOrderImpl) getOrder(orderID uint64) (*pdca.Order, error) {
	value := d.store.GetOrders().Get(pdca.OrderKey(orderID))
	if value == nil {
		return nil, makeErrorWithDetails(errOrderNotFound, ufmt.Sprintf("orderId(%d)", orderID))
	}

	return value.(*pdca.Order), nil
}

func (d *dcaOrderImpl) getGroup(groupID string) (*pdca.Group, error) {
	value := d.store.GetGroups().Get(groupID)
	if value == nil {
		return nil, makeErrorWithDetails(errGroupNotFound, ufmt.Sprintf("groupId(%s)", groupID))
	}

	return value.(*pdca.Group), nil
}

// getOrderWithGroup returns an order and the group it belongs to.
func (d *dcaOrderImpl) getOrderWithGroup(orderID uint64) (*pdca.Order, *pdca.Group, error) {
	order, err := d.getOrder(orderID)
	if err != nil {
		return nil, nil, err
	}

	group, err := d.getGroup(order.GroupID())
	if err != nil {
		return nil, nil, err
	}

	return order, group, nil
}

// validateOrderOutput checks that the round credits the smallest order of
// each execution fee rate at least minOrderAmountOut of output net of that
// rate, computed as its payout is. Within one rate an order's net payout
// only grows with amountPerExecution, so every order of the round then
// receives at least that much net of its own fee.
func validateOrderOutput(
	group *pdca.Group,
	minAmounts []feeRateMinAmount,
	minOrderAmountOut int64,
	outputPerAmountX128 *u256.Uint,
	executedAmountOut int64,
	orderAmount int64,
) error {
	for _, minAmount := range minAmounts {
		orderAmountOut, err := calculateMinOrderAmountOut(minAmount, outputPerAmountX128)
		if err != nil {
			return makeErrorWithDetails(errInvalidState, err.Error())
		}

		if orderAmountOut < minOrderAmountOut {
			return makeErrorWithDetails(
				errInsufficientOrderOutput,
				ufmt.Sprintf(
					"groupId(%s) amountPerExecution(%d) receives %d after executionFeeRate(%d), below minOrderAmountOut(%d), of executedAmountOut(%d) for orderAmount(%d)",
					group.ID(), minAmount.minAmountPerExecution, orderAmountOut, minAmount.executionFeeRate, minOrderAmountOut, executedAmountOut, orderAmount,
				),
			)
		}
	}

	return nil
}