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 (
	plimit "gno.land/p/gnoswap/order/limit/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"
)

func (l *limitOrderImpl) assertIsCall(_ int, rlm realm) realm {
	access.AssertIsRlmCurrent(0, rlm)
	common.AssertIsNotHandleNativeCoin()

	return rlm.Previous()
}

func (l *limitOrderImpl) assertIsAdminCall(_ int, rlm realm) realm {
	prev := l.assertIsCall(0, rlm)
	access.AssertIsAdminOrGovernance(prev.Address())

	return prev
}

func assertIsOrderOwner(order *plimit.Order, caller address) {
	if order.Owner() != caller {
		panic(makeErrorWithDetails(errNotOrderOwner, "order belongs to another caller").Error())
	}
}

// Authorization belongs to the proxy target and its immediate caller, not to
// the implementation or the transaction's origin signer.
func assertIsAuthorizedKeeper(target string, caller address) {
	if !keeper.IsAuthorized(target, keeper.SelectorExecuteOrder, caller) {
		panic(makeErrorWithDetails(errNotKeeper, ufmt.Sprintf("caller(%s)", caller.String())).Error())
	}
}

// validateNotHalted reports the first operation halted for Limit orders.
func validateNotHalted(operations ...string) error {
	for _, operation := range operations {
		if halt.IsHalted(halt.TargetLimit, operation) {
			return makeErrorWithDetails(errHalted, ufmt.Sprintf("operation(%s)", operation))
		}
	}

	return nil
}

func assertIsNotHalted(operations ...string) {
	if err := validateNotHalted(operations...); err != nil {
		panic(err.Error())
	}
}

config.gno

package impl

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

// SetMinMakingAmount sets the minimum input amount accepted for new orders.
func (l *limitOrderImpl) SetMinMakingAmount(_ int, rlm realm, minMakingAmount int64) {
	prev := l.assertIsAdminCall(0, rlm)

	if minMakingAmount <= 0 {
		panic(makeErrorWithDetails(errInvalidConfig, "minMakingAmount must be positive").Error())
	}

	config := l.store.GetConfig()
	old := config.MinMakingAmount()
	config.SetMinMakingAmount(minMakingAmount)

	emitConfigUpdated(prev.Address(), prev.PkgPath(), "minMakingAmount", utils.FormatInt(old), utils.FormatInt(minMakingAmount))
}

// SetOrderDeadlines sets the positive duration range accepted for new orders.
func (l *limitOrderImpl) SetOrderDeadlines(_ int, rlm realm, minDuration, maxDuration int64) {
	prev := l.assertIsAdminCall(0, rlm)

	if minDuration <= 0 || maxDuration < minDuration {
		panic(makeErrorWithDetails(errInvalidConfig, "invalid order duration range").Error())
	}

	config := l.store.GetConfig()
	oldMin, oldMax := config.MinOrderDuration(), config.MaxOrderDuration()
	config.SetMinOrderDuration(minDuration)
	config.SetMaxOrderDuration(maxDuration)

	emitConfigUpdated(prev.Address(), prev.PkgPath(), "minOrderDuration", utils.FormatInt(oldMin), utils.FormatInt(minDuration))
	emitConfigUpdated(prev.Address(), prev.PkgPath(), "maxOrderDuration", utils.FormatInt(oldMax), utils.FormatInt(maxDuration))
}

// SetMaxCleanupBatchSize bounds examined records, not just successful refunds.
func (l *limitOrderImpl) SetMaxCleanupBatchSize(_ int, rlm realm, maxCleanupBatchSize int64) {
	prev := l.assertIsAdminCall(0, rlm)

	if maxCleanupBatchSize < 1 || maxCleanupBatchSize > maxCleanupBatchSizeLimit {
		panic(makeErrorWithDetails(errInvalidConfig, "maxCleanupBatchSize must be in [1, "+utils.FormatInt(maxCleanupBatchSizeLimit)+"]").Error())
	}

	config := l.store.GetConfig()
	old := config.MaxCleanupBatchSize()
	config.SetMaxCleanupBatchSize(maxCleanupBatchSize)

	emitConfigUpdated(prev.Address(), prev.PkgPath(), "maxCleanupBatchSize", utils.FormatInt(old), utils.FormatInt(maxCleanupBatchSize))
}

// SetMaxSlippageBps sets the slippage cap for new orders.
func (l *limitOrderImpl) SetMaxSlippageBps(_ int, rlm realm, maxSlippageBps int64) {
	prev := l.assertIsAdminCall(0, rlm)

	config := l.store.GetConfig()

	old := config.MaxSlippageBps()
	if err := config.SetMaxSlippageBps(maxSlippageBps); err != nil {
		panic(makeErrorWithDetails(errInvalidConfig, "maxSlippageBps must be in [0, 10000]").Error())
	}

	emitConfigUpdated(prev.Address(), prev.PkgPath(), "maxSlippageBps", utils.FormatInt(old), utils.FormatInt(maxSlippageBps))
}

consts.gno

package impl

const (
	defaultExecutionFeeRate    int64 = 15
	defaultMinMakingAmount     int64 = 100
	defaultMinOrderDuration    int64 = 300
	defaultMaxOrderDuration    int64 = 31 * 24 * 60 * 60
	defaultMaxCleanupBatchSize int64 = 100

	maxCleanupBatchSizeLimit    int64 = 500
	maxCleanupOrderIDsCSVLength       = int(maxCleanupBatchSizeLimit)*20 + int(maxCleanupBatchSizeLimit) - 1
)

doc.gno

// Package impl is the v0 implementation of the GnoSwap limit order realm.
// It registers itself with gno.land/r/gnoswap/order/limit at init.
//
// Files:
//   - order.gno: CreateOrder, CancelOrder, CleanupExpiredOrders, CleanupExpiredOrdersByIDs
//   - execute.gno: ExecuteOrder, pool swaps, balance checks, and fill settlement
//   - execution_fee.gno: SetExecutionFeeRate, pending fees, and protocol fee collection
//   - swap.gno: swap price limits and pool amount decoding
//   - config.gno: admin configuration of order limits and cleanup batches
//   - getter.gno: read-only queries
//   - assert.gno, utils.gno: shared checks and helpers
//
// Each fill uses the keeper's pool fee tier on the order's token pair; the
// pool must be whitelisted for Limit orders. A zero sqrtPriceLimitX96 requires
// the entire maxAmountIn to be consumed; a nonzero limit permits partial
// consumption. Actual balance deltas must match the pool result, and the
// owner-net output must satisfy the order's slippage-adjusted ratio on the
// actual input, after the incremental cumulative execution fee.
//
// Filled orders are removed before paying the owner. Execution fees are
// forwarded to the protocol fee realm, or kept pending if collection is
// halted or rejected; later fills or CollectPendingExecutionFee retry them.
// Expired orders cannot be filled. Owner cancellation and public bounded
// cleanup refund unsold input and remove orders from both indexes.
// Roles: gno.land/r/gnoswap/order/keeper restricts ExecuteOrder to
// LimitKeeperRole at deployment. Admin or governance configures order limits
// and fees; PoolManagerRole manages the separate Limit pool whitelist through
// gno.land/r/gnoswap/order/whitelist.
package impl

emits.gno

package impl

import (
	"chain"

	plimit "gno.land/p/gnoswap/order/limit/v0"
	"gno.land/p/gnoswap/utils/v1"
)

func emitOrderCreated(prevAddr address, prevRealm string, order *plimit.Order, baseToken string) {
	chain.Emit(
		"LimitOrderCreated",
		"prevAddr", prevAddr.String(), "prevRealm", prevRealm,
		"owner", order.Owner().String(), "orderId", utils.FormatUint(order.ID()),
		"tokenIn", order.TokenIn(), "tokenOut", order.TokenOut(),
		"baseToken", baseToken,
		"makingAmount", utils.FormatInt(order.MakingAmount()), "takingAmount", utils.FormatInt(order.TakingAmount()),
		"slippageBps", utils.FormatInt(order.SlippageBps()),
		"createdAt", utils.FormatInt(order.CreatedAt()), "expiresAt", utils.FormatInt(order.ExpiresAt()),
		"executionFeeRate", utils.FormatInt(order.ExecutionFeeRate()),
	)
}

func emitOrderFilled(prevAddr address, prevRealm string, order *plimit.Order, route string, amountIn, poolOutput, executionFee int64) {
	chain.Emit(
		"LimitOrderFilled",
		"prevAddr", prevAddr.String(), "prevRealm", prevRealm,
		"owner", order.Owner().String(), "orderId", utils.FormatUint(order.ID()),
		"route", route,
		"tokenIn", order.TokenIn(), "tokenOut", order.TokenOut(),
		"amountIn", utils.FormatInt(amountIn), "poolOutput", utils.FormatInt(poolOutput),
		"userOutput", utils.FormatInt(poolOutput-executionFee), "executionFee", utils.FormatInt(executionFee),
		"filledInput", utils.FormatInt(order.FilledInput()), "remainingInput", utils.FormatInt(order.RemainingInput()),
		"refundedInput", utils.FormatInt(order.RefundedInput()),
		"grossOutput", utils.FormatInt(order.GrossOutput()), "cumulativeExecutionFee", utils.FormatInt(order.ExecutionFee()),
	)
}

func emitExecutionFeeCollected(
	prevAddr address,
	prevRealm string,
	orderID uint64,
	tokenPath string,
	executionFeeAmount int64,
	forwardedAmount int64,
	pendingAmount int64,
) {
	chain.Emit(
		"LimitExecutionFeeCollected",
		"prevAddr", prevAddr.String(),
		"prevRealm", prevRealm,
		"orderId", utils.FormatUint(orderID),
		"tokenPath", tokenPath,
		"executionFeeAmount", utils.FormatInt(executionFeeAmount),
		"forwardedAmount", utils.FormatInt(forwardedAmount),
		"pendingAmount", utils.FormatInt(pendingAmount),
	)
}

func emitOrderCompleted(prevAddr address, prevRealm string, order *plimit.Order) {
	chain.Emit(
		"LimitOrderCompleted",
		"prevAddr", prevAddr.String(), "prevRealm", prevRealm,
		"owner", order.Owner().String(), "orderId", utils.FormatUint(order.ID()),
		"filledInput", utils.FormatInt(order.FilledInput()), "refundedInput", utils.FormatInt(order.RefundedInput()),
		"grossOutput", utils.FormatInt(order.GrossOutput()), "cumulativeExecutionFee", utils.FormatInt(order.ExecutionFee()),
		"userOutput", utils.FormatInt(order.GrossOutput()-order.ExecutionFee()),
	)
}

func emitOrderRefunded(prevAddr address, prevRealm string, order *plimit.Order, refund int64, expired bool) {
	name := "LimitOrderCancelled"
	if expired {
		name = "LimitOrderExpired"
	}

	emitOrderInputRefunded(name, prevAddr, prevRealm, order, refund)
}

func emitOrderInputRefunded(name string, prevAddr address, prevRealm string, order *plimit.Order, refund int64) {
	chain.Emit(
		name,
		"prevAddr", prevAddr.String(), "prevRealm", prevRealm,
		"owner", order.Owner().String(), "orderId", utils.FormatUint(order.ID()),
		"tokenIn", order.TokenIn(), "tokenOut", order.TokenOut(),
		"refundIn", utils.FormatInt(refund), "refundedInput", utils.FormatInt(order.RefundedInput()),
		"filledInput", utils.FormatInt(order.FilledInput()), "remainingInput", utils.FormatInt(order.RemainingInput()),
		"grossOutput", utils.FormatInt(order.GrossOutput()), "cumulativeExecutionFee", utils.FormatInt(order.ExecutionFee()),
		"userOutput", utils.FormatInt(order.GrossOutput()-order.ExecutionFee()),
	)
}

func emitOrderCleanupInsufficientBalance(prevAddr address, prevRealm string, order *plimit.Order, refund, balance int64) {
	chain.Emit(
		"LimitOrderCleanupInsufficientBalance",
		"prevAddr", prevAddr.String(), "prevRealm", prevRealm,
		"owner", order.Owner().String(), "orderId", utils.FormatUint(order.ID()),
		"tokenIn", order.TokenIn(),
		"refundAmount", utils.FormatInt(refund), "balance", utils.FormatInt(balance),
	)
}

func emitConfigUpdated(prevAddr address, prevRealm, key, previous, next string) {
	chain.Emit(
		"LimitOrderConfigUpdated",
		"prevAddr", prevAddr.String(), "prevRealm", prevRealm,
		"key", key, "prevValue", previous, "newValue", next,
	)
}

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

errors.gno

package impl

import (
	plimit "gno.land/p/gnoswap/order/limit/v0"
	ufmt "gno.land/p/nt/ufmt/v0"
)

const (
	errInvalidTokenIn          = "[GNOSWAP-ORDER-LIMIT-001] invalid token in"
	errInvalidTokenOut         = "[GNOSWAP-ORDER-LIMIT-002] invalid token out"
	errSameToken               = "[GNOSWAP-ORDER-LIMIT-003] token in and token out must be different"
	errInvalidMakingAmount     = "[GNOSWAP-ORDER-LIMIT-004] invalid making amount (must be > 0)"
	errInvalidTakingAmount     = "[GNOSWAP-ORDER-LIMIT-005] invalid taking amount (must be > 0)"
	errInvalidSlippage         = "[GNOSWAP-ORDER-LIMIT-006] invalid slippage"
	errInvalidExpiresAt        = "[GNOSWAP-ORDER-LIMIT-007] invalid expiresAt (must be > 0)"
	errDeadlineTooShort        = "[GNOSWAP-ORDER-LIMIT-008] deadline too short"
	errDeadlineTooLong         = "[GNOSWAP-ORDER-LIMIT-009] deadline too long"
	errOrderNotFound           = "[GNOSWAP-ORDER-LIMIT-010] order not found"
	errOrderNotActive          = "[GNOSWAP-ORDER-LIMIT-011] order is not active"
	errOrderExpired            = "[GNOSWAP-ORDER-LIMIT-012] order has expired"
	errInsufficientOutput      = "[GNOSWAP-ORDER-LIMIT-013] insufficient output amount"
	errInvalidFillAmount       = "[GNOSWAP-ORDER-LIMIT-014] invalid fill amount"
	errAmountOverflow          = "[GNOSWAP-ORDER-LIMIT-015] amount exceeds int64"
	errSlippageExceeded        = "[GNOSWAP-ORDER-LIMIT-016] slippage exceeded, output less than minimum"
	errNotOrderOwner           = "[GNOSWAP-ORDER-LIMIT-017] unauthorized caller"
	errInvalidConfig           = "[GNOSWAP-ORDER-LIMIT-018] invalid config"
	errInvalidState            = "[GNOSWAP-ORDER-LIMIT-019] invalid accounting state"
	errInvalidExecutionFeeRate = "[GNOSWAP-ORDER-LIMIT-020] invalid execution fee rate"
	errNotKeeper               = "[GNOSWAP-ORDER-LIMIT-021] caller is not an authorized keeper"
	errHalted                  = "[GNOSWAP-ORDER-LIMIT-022] operation halted"
	errInvalidPriceLimit       = "[GNOSWAP-ORDER-LIMIT-023] invalid sqrt price limit"
	errInvalidCleanupOrderIDs  = "[GNOSWAP-ORDER-LIMIT-024] invalid cleanup order IDs"
	errPoolNotWhitelisted      = "[GNOSWAP-ORDER-LIMIT-025] pool is not whitelisted"
	errInvalidBaseToken        = "[GNOSWAP-ORDER-LIMIT-026] invalid base token"
)

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

// Pure-package errors have no realm codes. Translate them at the public boundary.
func realmError(err error) error {
	message := ""

	switch err {
	case plimit.ErrInvalidMakingAmount:
		message = errInvalidMakingAmount
	case plimit.ErrInvalidTakingAmount:
		message = errInvalidTakingAmount
	case plimit.ErrInvalidSlippage:
		message = errInvalidSlippage
	case plimit.ErrInvalidExpiresAt:
		message = errInvalidExpiresAt
	case plimit.ErrOrderNotActive:
		message = errOrderNotActive
	case plimit.ErrOrderExpired:
		message = errOrderExpired
	case plimit.ErrInsufficientOutput:
		message = errInsufficientOutput
	case plimit.ErrInvalidFillAmount:
		message = errInvalidFillAmount
	case plimit.ErrAmountOverflow:
		message = errAmountOverflow
	case plimit.ErrSlippageExceeded:
		message = errSlippageExceeded
	case plimit.ErrInvalidExecutionFeeRate:
		message = errInvalidExecutionFeeRate
	default:
		return err
	}

	return makeErrorWithDetails(message, err.Error())
}

execute.gno

package impl

import (
	"strconv"
	"time"

	plimit "gno.land/p/gnoswap/order/limit/v0"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/order/halt"
	lo "gno.land/r/gnoswap/order/limit"
	"gno.land/r/gnoswap/order/whitelist"
	"gno.land/r/gnoswap/pool"
)

// ExecuteOrder returns actual input and pool output before the order fee,
// allowing the pool to stop before maxAmountIn at a nonzero price limit.
func (l *limitOrderImpl) ExecuteOrder(_ int, rlm realm, orderID uint64, maxAmountIn int64, poolFee uint32, sqrtPriceLimitX96 string) (int64, int64) {
	prev := l.assertIsCall(0, rlm)

	assertIsNotHalted(halt.OperationExecute, halt.OperationWithdraw)
	assertIsAuthorizedKeeper(rlm.PkgPath(), prev.Address())

	order, err := l.getOrder(orderID)
	if err != nil {
		panic(err.Error())
	}

	result, err := l.executeOrder(0, rlm, order, maxAmountIn, poolFee, sqrtPriceLimitX96)
	if err != nil {
		panic(realmError(err).Error())
	}

	emitOrderExecution(prev.Address(), prev.PkgPath(), order, poolFee, result)

	return result.actualInput, result.poolOutput
}

func emitOrderExecution(prevAddr address, prevRealm string, order *plimit.Order, poolFee uint32, result orderExecutionResult) {
	route := order.TokenIn() + ":" + order.TokenOut() + ":" + strconv.FormatUint(uint64(poolFee), 10)
	emitOrderFilled(prevAddr, prevRealm, order, route, result.actualInput, result.poolOutput, result.executionFeeAmount)

	if result.executionFeeAmount > 0 || result.forwardedExecutionFeeAmount > 0 || result.pendingExecutionFeeAmount > 0 {
		emitExecutionFeeCollected(
			prevAddr,
			prevRealm,
			order.ID(),
			order.TokenOut(),
			result.executionFeeAmount,
			result.forwardedExecutionFeeAmount,
			result.pendingExecutionFeeAmount,
		)
	}

	if order.RemainingInput() == 0 {
		emitOrderCompleted(prevAddr, prevRealm, order)
	}
}

type orderExecutionResult struct {
	actualInput                 int64
	poolOutput                  int64
	executionFeeAmount          int64
	forwardedExecutionFeeAmount int64
	pendingExecutionFeeAmount   int64
}

func (l *limitOrderImpl) executeOrder(_ int, rlm realm, order *plimit.Order, maxAmountIn int64, poolFee uint32, sqrtPriceLimitX96 string) (orderExecutionResult, error) {
	now := time.Now().Unix()
	if err := validateExecution(order, maxAmountIn, now); err != nil {
		return orderExecutionResult{}, err
	}

	poolPath := pool.GetPoolPath(order.TokenIn(), order.TokenOut(), poolFee)
	if !whitelist.IsWhitelistedPool(whitelist.TargetLimit, poolPath) {
		return orderExecutionResult{}, makeErrorWithDetails(errPoolNotWhitelisted, poolPath)
	}

	zeroForOne := order.TokenIn() < order.TokenOut()

	limit, fullInput, err := orderPriceLimit(sqrtPriceLimitX96, zeroForOne)
	if err != nil {
		return orderExecutionResult{}, err
	}

	token0, token1 := order.TokenIn(), order.TokenOut()
	if !zeroForOne {
		token0, token1 = token1, token0
	}

	custody := lo.Address()
	inputBefore := common.BalanceOf(order.TokenIn(), custody)
	outputBefore := common.BalanceOf(order.TokenOut(), custody)
	callback := lo.NewSwapCallback(0, rlm, order.TokenIn(), zeroForOne, maxAmountIn)
	amount0, amount1 := pool.Swap(
		cross(rlm), token0, token1, poolFee, custody, zeroForOne,
		strconv.FormatInt(maxAmountIn, 10), limit, callback,
	)

	actualInput, poolOutput, err := poolSwapAmounts(amount0, amount1, zeroForOne)
	if err != nil {
		return orderExecutionResult{}, err
	}

	if actualInput > maxAmountIn || (fullInput && actualInput != maxAmountIn) {
		return orderExecutionResult{}, plimit.ErrInvalidFillAmount
	}

	return l.settleOrderFill(0, rlm, order, actualInput, poolOutput, inputBefore, outputBefore, now)
}

func (l *limitOrderImpl) settleOrderFill(_ int, rlm realm, order *plimit.Order, actualInput, poolOutput, inputBefore, outputBefore, now int64) (orderExecutionResult, error) {
	custody := lo.Address()

	inputAfter := common.BalanceOf(order.TokenIn(), custody)
	outputAfter := common.BalanceOf(order.TokenOut(), custody)

	if inputBefore < 0 || inputAfter < 0 || inputAfter > inputBefore || inputBefore-inputAfter != actualInput {
		return orderExecutionResult{}, plimit.ErrInvalidFillAmount
	}

	if outputBefore < 0 || outputAfter < outputBefore || outputAfter-outputBefore != poolOutput {
		return orderExecutionResult{}, plimit.ErrInsufficientOutput
	}

	executionFeeBefore := order.ExecutionFee()
	if err := order.ApplyFill(actualInput, poolOutput, now); err != nil {
		return orderExecutionResult{}, err
	}

	executionFeeAmount := order.ExecutionFee() - executionFeeBefore
	userOutput := poolOutput - executionFeeAmount

	if order.RemainingInput() == 0 {
		l.removeOrder(order)
	}

	// Finalize order state before paying the owner or collecting the execution fee.
	if userOutput > 0 {
		common.SafeGRC20Transfer(0, rlm, order.TokenOut(), order.Owner(), userOutput)
	}

	forwardedExecutionFeeAmount, pendingExecutionFeeAmount := l.collectExecutionFee(0, rlm, order.TokenOut(), executionFeeAmount)

	return orderExecutionResult{
		actualInput:                 actualInput,
		poolOutput:                  poolOutput,
		executionFeeAmount:          executionFeeAmount,
		forwardedExecutionFeeAmount: forwardedExecutionFeeAmount,
		pendingExecutionFeeAmount:   pendingExecutionFeeAmount,
	}, nil
}

execution_fee.gno

package impl

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

	"gno.land/r/gnoswap/access/v1"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/halt/v1"
	orderhalt "gno.land/r/gnoswap/order/halt"
	pf "gno.land/r/gnoswap/protocol_fee"
	_ "gno.land/r/gnoswap/protocol_fee/v1"
)

// SetExecutionFeeRate changes the rate snapshotted by future orders only.
// Admin or governance only.
func (l *limitOrderImpl) SetExecutionFeeRate(_ int, rlm realm, executionFeeRate int64) {
	prev := l.assertIsAdminCall(0, rlm)

	config := l.store.GetConfig()

	previousExecutionFeeRate := config.ExecutionFeeRate()
	if err := config.SetExecutionFeeRate(executionFeeRate); err != nil {
		panic(makeErrorWithDetails(errInvalidExecutionFeeRate, err.Error()).Error())
	}

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

// CollectPendingExecutionFee forwards pending fees without executing an order.
// Anyone may call it; funds only move to the protocol fee realm.
func (l *limitOrderImpl) CollectPendingExecutionFee(_ int, rlm realm, tokenPath string) (int64, int64) {
	prev := l.assertIsCall(0, rlm)

	assertIsNotHalted(orderhalt.OperationWithdraw)

	forwardedAmount, pendingAmount := l.collectExecutionFee(0, rlm, tokenPath, 0)
	if forwardedAmount > 0 {
		emitExecutionFeeCollected(prev.Address(), prev.PkgPath(), 0, tokenPath, 0, forwardedAmount, pendingAmount)
	}

	return forwardedAmount, pendingAmount
}

// collectExecutionFee keeps execution fees pending while collection is halted
// or rejected, and retries on the next fill or explicit collection.
// It also runs for zero execution-fee fills so they can forward earlier pending fees.
// It returns the amount forwarded and the amount left pending.
func (l *limitOrderImpl) collectExecutionFee(_ int, rlm realm, tokenPath string, executionFeeAmount int64) (int64, int64) {
	pendingExecutionFees := l.store.GetPendingExecutionFees()
	pendingAmount := getPendingExecutionFeeAmount(pendingExecutionFees, tokenPath)

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

	if halt.IsHaltedProtocolFee() {
		pendingExecutionFees.Set(tokenPath, totalAmount)
		return 0, totalAmount
	}

	// Remove the pending debit before external calls so re-entry cannot collect
	// it twice. A rejected collection restores it; an abort rolls back the call.
	if pendingAmount > 0 {
		pendingExecutionFees.Remove(tokenPath)
	}

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

	if err != nil {
		pendingExecutionFees.Set(tokenPath, totalAmount)
		return 0, totalAmount
	}

	return totalAmount, 0
}

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 (
	plimit "gno.land/p/gnoswap/order/limit/v0"
	rotree "gno.land/p/nt/bptree/rotree/v0"
)

func (l *limitOrderImpl) GetConfig() *plimit.Config {
	return l.store.GetConfig().Clone()
}

func (l *limitOrderImpl) GetNextOrderID() uint64 {
	return l.store.GetNextOrderID()
}

func (l *limitOrderImpl) ExistsOrder(orderID uint64) bool {
	return l.store.GetOrders().Has(plimit.OrderKey(orderID))
}

func (l *limitOrderImpl) GetOrder(orderID uint64) *plimit.Order {
	value := l.store.GetOrders().Get(plimit.OrderKey(orderID))
	if value == nil {
		return nil
	}

	return value.(*plimit.Order).Clone()
}

func (l *limitOrderImpl) GetOrders() *rotree.ReadOnlyTree {
	return rotree.Wrap(l.store.GetOrders(), cloneOrderEntry)
}

func (l *limitOrderImpl) GetOrdersByOwner() *rotree.ReadOnlyTree {
	return rotree.Wrap(l.store.GetOrdersByOwner(), nil)
}

func (l *limitOrderImpl) GetPendingExecutionFeeAmount(tokenPath string) int64 {
	return getPendingExecutionFeeAmount(l.store.GetPendingExecutionFees(), tokenPath)
}

func (l *limitOrderImpl) GetPendingExecutionFees() *rotree.ReadOnlyTree {
	return rotree.Wrap(l.store.GetPendingExecutionFees(), nil)
}

func cloneOrderEntry(value any) any {
	if value == nil {
		return nil
	}

	return value.(*plimit.Order).Clone()
}

gnomod.toml

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

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

init.gno

package impl

import (
	plimit "gno.land/p/gnoswap/order/limit/v0"

	lo "gno.land/r/gnoswap/order/limit"
)

func init(cur realm) {
	lo.RegisterInitializer(cross(cur), func(_ int, rlm realm, orderStore plimit.ILimitOrderStore) plimit.ILimitOrder {
		if err := initStoreData(0, rlm, orderStore); err != nil {
			panic(err.Error())
		}

		return NewLimitOrderImpl(orderStore)
	})
}

func initStoreData(_ int, rlm realm, s plimit.ILimitOrderStore) error {
	if !s.HasOrders() {
		if err := s.SetOrders(0, rlm, lo.NewBPTreeN(plimit.DefaultBPTreeFanout)); err != nil {
			return err
		}
	}

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

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

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

	if !s.HasConfig() {
		config := plimit.NewConfig(
			defaultExecutionFeeRate,
			defaultMinMakingAmount,
			defaultMinOrderDuration,
			defaultMaxOrderDuration,
			defaultMaxCleanupBatchSize,
		)
		if err := s.SetConfig(0, rlm, config); err != nil {
			return err
		}
	}

	return nil
}

instance.gno

package impl

import plimit "gno.land/p/gnoswap/order/limit/v0"

type limitOrderImpl struct {
	store plimit.ILimitOrderStore
}

// NewLimitOrderImpl binds the implementation to the proxy-owned store.
func NewLimitOrderImpl(orderStore plimit.ILimitOrderStore) plimit.ILimitOrder {
	return &limitOrderImpl{store: orderStore}
}

order.gno

package impl

import (
	"strconv"
	"strings"
	"time"

	plimit "gno.land/p/gnoswap/order/limit/v0"
	ufmt "gno.land/p/nt/ufmt/v0"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/order/halt"
	lo "gno.land/r/gnoswap/order/limit"
)

func (l *limitOrderImpl) CreateOrder(_ int, rlm realm, tokenIn, tokenOut string, makingAmount, takingAmount, slippageBps, expiresAt int64, baseToken string) uint64 {
	prev := l.assertIsCall(0, rlm)

	assertIsNotHalted(halt.OperationExecute)

	if baseToken == "" || (baseToken != tokenIn && baseToken != tokenOut) {
		panic(errInvalidBaseToken)
	}

	order, err := l.createOrder(0, rlm, prev.Address(), tokenIn, tokenOut, makingAmount, takingAmount, slippageBps, expiresAt)
	if err != nil {
		panic(realmError(err).Error())
	}

	emitOrderCreated(prev.Address(), prev.PkgPath(), order, baseToken)

	return order.ID()
}

func (l *limitOrderImpl) createOrder(_ int, rlm realm, owner address, tokenIn, tokenOut string, makingAmount, takingAmount, slippageBps, expiresAt int64) (*plimit.Order, error) {
	now := time.Now().Unix()

	orderID := l.store.GetNextOrderID()
	if orderID == ^uint64(0) {
		return nil, plimit.ErrAmountOverflow
	}

	config := l.store.GetConfig()

	max := config.MaxSlippageBps()
	if slippageBps < 0 || slippageBps > max {
		return nil, makeErrorWithDetails(errInvalidSlippage, ufmt.Sprintf("max %d bps, got %d bps", max, slippageBps))
	}

	order, err := plimit.NewOrder(orderID, owner, tokenIn, tokenOut, makingAmount, takingAmount, slippageBps, config.ExecutionFeeRate(), now, expiresAt)
	if err != nil {
		return nil, err
	}

	if err := l.validateCreateOrder(tokenIn, tokenOut, makingAmount, expiresAt, now); err != nil {
		return nil, err
	}

	if err := l.store.SetNextOrderID(0, rlm, orderID+1); err != nil {
		return nil, err
	}

	l.store.GetOrders().Set(plimit.OrderKey(orderID), order)
	l.store.GetOrdersByOwner().Set(plimit.OwnerOrderKey(owner, orderID), orderID)

	common.SafeGRC20TransferFrom(0, rlm, tokenIn, owner, lo.Address(), makingAmount)

	return order, nil
}

func (l *limitOrderImpl) removeOrder(order *plimit.Order) {
	l.store.GetOrders().Remove(plimit.OrderKey(order.ID()))
	l.store.GetOrdersByOwner().Remove(plimit.OwnerOrderKey(order.Owner(), order.ID()))
}

// CancelOrder returns the unsold input in the same transaction.
func (l *limitOrderImpl) CancelOrder(_ int, rlm realm, orderID uint64) int64 {
	prev := l.assertIsCall(0, rlm)

	assertIsNotHalted(halt.OperationWithdraw)

	order, err := l.getOrder(orderID)
	if err != nil {
		panic(err.Error())
	}

	assertIsOrderOwner(order, prev.Address())

	if order.RemainingInput() <= 0 {
		panic(makeErrorWithDetails(errOrderNotActive, "order has no remaining input").Error())
	}

	expired := order.IsExpired(time.Now().Unix())
	refund := order.RefundInput()
	l.removeOrder(order)

	if refund > 0 {
		common.SafeGRC20Transfer(0, rlm, order.TokenIn(), order.Owner(), refund)
	}

	emitOrderRefunded(prev.Address(), prev.PkgPath(), order, refund, expired)

	return refund
}

// CleanupExpiredOrders bounds the number of pending records examined per scan.
// The cursor is the last examined ID and remains usable after that order is removed.
func (l *limitOrderImpl) CleanupExpiredOrders(_ int, rlm realm, startAfterOrderID uint64, maxOrders int) (int, uint64) {
	prev := l.assertIsCall(0, rlm)

	assertIsNotHalted(halt.OperationWithdraw)

	if maxOrders <= 0 {
		return 0, 0
	}

	limit := int(l.store.GetConfig().MaxCleanupBatchSize())
	if maxOrders < limit {
		limit = maxOrders
	}

	ids := make([]uint64, 0, limit)
	more := false

	l.store.GetOrders().Iterate(plimit.OrderKey(startAfterOrderID), "", func(_ string, value any) bool {
		order := value.(*plimit.Order)
		if order.ID() <= startAfterOrderID {
			return false
		}

		if len(ids) == limit {
			more = true
			return true
		}

		ids = append(ids, order.ID())

		return false
	})

	now := time.Now().Unix()
	expired := 0

	for _, orderID := range ids {
		order, err := l.getOrder(orderID)
		if err != nil {
			panic(err.Error())
		}

		isExpired := order.IsExpired(now)
		if !isExpired {
			continue
		}

		remaining := order.RemainingInput()
		if remaining > 0 {
			balance := common.BalanceOf(order.TokenIn(), lo.Address())
			if balance < remaining {
				emitOrderCleanupInsufficientBalance(prev.Address(), prev.PkgPath(), order, remaining, balance)
				continue
			}
		}

		refund := order.RefundInput()
		l.removeOrder(order)

		if refund > 0 {
			common.SafeGRC20Transfer(0, rlm, order.TokenIn(), order.Owner(), refund)
		}

		emitOrderRefunded(prev.Address(), prev.PkgPath(), order, refund, isExpired)

		expired++
	}

	if more {
		return expired, ids[len(ids)-1]
	}

	return expired, 0
}

// CleanupExpiredOrdersByIDs examines only the validated IDs supplied by the caller.
func (l *limitOrderImpl) CleanupExpiredOrdersByIDs(_ int, rlm realm, orderIDs string) (int, string) {
	prev := l.assertIsCall(0, rlm)

	assertIsNotHalted(halt.OperationWithdraw)

	if orderIDs == "" {
		return 0, ""
	}

	ids := parseCleanupOrderIDsCSV(orderIDs, l.store.GetConfig().MaxCleanupBatchSize())
	now := time.Now().Unix()
	expired := 0
	retryOrderIDs := make([]string, 0, len(ids))

	for _, orderID := range ids {
		value := l.store.GetOrders().Get(plimit.OrderKey(orderID))
		if value == nil {
			continue
		}

		order, ok := value.(*plimit.Order)
		if !ok || order == nil {
			panic(makeErrorWithDetails(errInvalidState, "invalid stored order").Error())
		}

		isExpired := order.IsExpired(now)
		if !isExpired {
			retryOrderIDs = append(retryOrderIDs, strconv.FormatUint(orderID, 10))
			continue
		}

		remaining := order.RemainingInput()
		if remaining > 0 {
			balance := common.BalanceOf(order.TokenIn(), lo.Address())
			if balance < remaining {
				emitOrderCleanupInsufficientBalance(prev.Address(), prev.PkgPath(), order, remaining, balance)

				retryOrderIDs = append(retryOrderIDs, strconv.FormatUint(orderID, 10))

				continue
			}
		}

		refund := order.RefundInput()
		l.removeOrder(order)

		if refund > 0 {
			common.SafeGRC20Transfer(0, rlm, order.TokenIn(), order.Owner(), refund)
		}

		emitOrderRefunded(prev.Address(), prev.PkgPath(), order, refund, isExpired)

		expired++
	}

	return expired, strings.Join(retryOrderIDs, ",")
}

// parseCleanupOrderIDsCSV validates the complete bounded input before cleanup
// can change any order or refund any escrow.
func parseCleanupOrderIDsCSV(orderIDs string, maxBatchSize int64) []uint64 {
	if len(orderIDs) > maxCleanupOrderIDsCSVLength {
		panic(errInvalidCleanupOrderIDs)
	}

	itemCount := 1

	for i := 0; i < len(orderIDs); i++ {
		if orderIDs[i] == ',' {
			itemCount++
			if itemCount > int(maxCleanupBatchSizeLimit) || int64(itemCount) > maxBatchSize {
				panic(errInvalidCleanupOrderIDs)
			}
		}
	}

	if itemCount > int(maxCleanupBatchSizeLimit) || int64(itemCount) > maxBatchSize {
		panic(errInvalidCleanupOrderIDs)
	}

	values := strings.Split(orderIDs, ",")
	ids := make([]uint64, len(values))

	var previous uint64

	for i, value := range values {
		id, err := strconv.ParseUint(value, 10, 64)
		if err != nil || id == 0 || strconv.FormatUint(id, 10) != value || (i > 0 && id <= previous) {
			panic(errInvalidCleanupOrderIDs)
		}

		ids[i] = id
		previous = id
	}

	return ids
}

swap.gno

package impl

import (
	"math"
	"strconv"

	plimit "gno.land/p/gnoswap/order/limit/v0"
	u256 "gno.land/p/gnoswap/uint256/v1"
)

// The default bounds exclude the two TickMath endpoints.
const (
	minSwapSqrtPrice = "4295128740"
	maxSwapSqrtPrice = "1461446703485210103287273052203988822378723970341"
)

func orderPriceLimit(price string, zeroForOne bool) (string, bool, error) {
	value, err := u256.FromDecimal(price)
	if err != nil {
		return "", false, makeErrorWithDetails(errInvalidPriceLimit, price)
	}

	if !value.IsZero() {
		return price, false, nil
	}

	if zeroForOne {
		return minSwapSqrtPrice, true, nil
	}

	return maxSwapSqrtPrice, true, nil
}

func poolSwapAmounts(amount0, amount1 string, zeroForOne bool) (int64, int64, error) {
	input, output := amount0, amount1
	if !zeroForOne {
		input, output = amount1, amount0
	}

	actualInput, err := strconv.ParseInt(input, 10, 64)
	if err != nil || actualInput <= 0 {
		return 0, 0, plimit.ErrInvalidFillAmount
	}

	outputDelta, err := strconv.ParseInt(output, 10, 64)
	if err != nil || outputDelta == math.MinInt64 {
		return 0, 0, plimit.ErrAmountOverflow
	}

	if outputDelta >= 0 {
		return 0, 0, plimit.ErrInsufficientOutput
	}

	return actualInput, -outputDelta, nil
}

utils.gno

package impl

import (
	"strconv"

	plimit "gno.land/p/gnoswap/order/limit/v0"
	"gno.land/r/gnoswap/common"
	"gno.land/r/gnoswap/order/whitelist"
)

func (l *limitOrderImpl) getOrder(orderID uint64) (*plimit.Order, error) {
	value := l.store.GetOrders().Get(plimit.OrderKey(orderID))
	if value == nil {
		return nil, makeErrorWithDetails(errOrderNotFound, strconv.FormatUint(orderID, 10))
	}

	order, ok := value.(*plimit.Order)
	if !ok || order == nil {
		return nil, makeErrorWithDetails(errInvalidState, "invalid stored order")
	}

	return order, nil
}

// validateCreateOrder checks realm policy after NewOrder validates domain terms.
func (l *limitOrderImpl) validateCreateOrder(tokenIn, tokenOut string, makingAmount, expiresAt, now int64) error {
	if tokenIn == "" {
		return makeErrorWithDetails(errInvalidTokenIn, "empty registry key")
	}

	if tokenOut == "" {
		return makeErrorWithDetails(errInvalidTokenOut, "empty registry key")
	}

	if tokenIn == tokenOut {
		return makeErrorWithDetails(errSameToken, tokenIn)
	}

	if err := common.ValidateRegistered(tokenIn); err != nil {
		return makeErrorWithDetails(errInvalidTokenIn, err.Error())
	}

	if err := common.ValidateRegistered(tokenOut); err != nil {
		return makeErrorWithDetails(errInvalidTokenOut, err.Error())
	}

	if !whitelist.HasWhitelistedPool(whitelist.TargetLimit, tokenIn, tokenOut) {
		return makeErrorWithDetails(errPoolNotWhitelisted, tokenIn+":"+tokenOut)
	}

	config := l.store.GetConfig()
	if makingAmount < config.MinMakingAmount() {
		return makeErrorWithDetails(errInvalidMakingAmount, "makingAmount must be >= "+strconv.FormatInt(config.MinMakingAmount(), 10))
	}

	if expiresAt <= now || expiresAt-now < config.MinOrderDuration() {
		return makeErrorWithDetails(errDeadlineTooShort, "order expires before minimum duration")
	}

	if expiresAt-now > config.MaxOrderDuration() {
		return makeErrorWithDetails(errDeadlineTooLong, "order exceeds maximum duration")
	}

	return nil
}

func validateExecution(order *plimit.Order, amountIn, now int64) error {
	if order.RemainingInput() <= 0 {
		return plimit.ErrOrderNotActive
	}

	if order.IsExpired(now) {
		return plimit.ErrOrderExpired
	}

	if amountIn <= 0 || amountIn > order.RemainingInput() {
		return plimit.ErrInvalidFillAmount
	}

	return nil
}