Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Playground

config.gno

package limit

// Config holds governance-controlled limit-order parameters.
type Config struct {
	executionFeeRate    int64 // snapshotted into each new order, bps of gross output
	maxSlippageBps      int64 // maximum slippage accepted for new orders
	minMakingAmount     int64 // minimum input amount accepted for new orders
	minOrderDuration    int64 // shortest allowed expiresAt - createdAt, in seconds
	maxOrderDuration    int64 // longest allowed expiresAt - createdAt, in seconds
	maxCleanupBatchSize int64 // most orders one CleanupExpiredOrders call examines
}

// NewConfig returns a config with the given parameters.
// Bounds are enforced by the implementation that stores it.
func NewConfig(
	executionFeeRate int64,
	minMakingAmount int64,
	minOrderDuration int64,
	maxOrderDuration int64,
	maxCleanupBatchSize int64,
) *Config {
	return &Config{
		executionFeeRate:    executionFeeRate,
		maxSlippageBps:      DefaultMaxSlippageBps,
		minMakingAmount:     minMakingAmount,
		minOrderDuration:    minOrderDuration,
		maxOrderDuration:    maxOrderDuration,
		maxCleanupBatchSize: maxCleanupBatchSize,
	}
}

// Clone returns a copy of the config that shares no state with c.
// Callers outside the storing realm read the config through it.
func (c *Config) Clone() *Config {
	return &Config{
		executionFeeRate:    c.executionFeeRate,
		maxSlippageBps:      c.maxSlippageBps,
		minMakingAmount:     c.minMakingAmount,
		minOrderDuration:    c.minOrderDuration,
		maxOrderDuration:    c.maxOrderDuration,
		maxCleanupBatchSize: c.maxCleanupBatchSize,
	}
}

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

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

	c.executionFeeRate = executionFeeRate

	return nil
}

func (c *Config) MaxSlippageBps() int64 { return c.maxSlippageBps }

// SetMaxSlippageBps sets the maximum slippage accepted for new orders.
// It returns ErrInvalidSlippage outside [0, BpsDenominator].
func (c *Config) SetMaxSlippageBps(maxSlippageBps int64) error {
	if maxSlippageBps < 0 || maxSlippageBps > BpsDenominator {
		return ErrInvalidSlippage
	}

	c.maxSlippageBps = maxSlippageBps

	return nil
}

func (c *Config) MinMakingAmount() int64     { return c.minMakingAmount }
func (c *Config) SetMinMakingAmount(v int64) { c.minMakingAmount = v }

func (c *Config) MinOrderDuration() int64     { return c.minOrderDuration }
func (c *Config) SetMinOrderDuration(v int64) { c.minOrderDuration = v }

func (c *Config) MaxOrderDuration() int64     { return c.maxOrderDuration }
func (c *Config) SetMaxOrderDuration(v int64) { c.maxOrderDuration = v }

func (c *Config) MaxCleanupBatchSize() int64 { return c.maxCleanupBatchSize }
func (c *Config) SetMaxCleanupBatchSize(maxCleanupBatchSize int64) {
	c.maxCleanupBatchSize = maxCleanupBatchSize
}

consts.gno

package limit

// BpsDenominator is 100% in basis points.
const BpsDenominator int64 = 10_000

// DefaultMaxSlippageBps is the default maximum slippage for new orders (10%).
const DefaultMaxSlippageBps int64 = 1_000

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

// DefaultBPTreeFanout is the fanout of every limit-order B+tree.
const DefaultBPTreeFanout = 16

doc.gno

// Package limit holds the immutable building blocks of the GnoSwap limit
// order realm:
//
//   - types.gno: interfaces between the proxy and its implementations
//   - order.gno, config.gno: domain types stored by the realm
//   - math.gno: owner-net minimum output and cumulative execution-fee math
//   - keys.gno: B+tree key encodings
//   - consts.gno: basis-point denominator and domain bounds
//
// Nothing here owns realm state. Storage, authorization, and token transfers
// live in gno.land/r/gnoswap/order/limit and its implementations under impl/.
//
// Accounting: an order escrows makingAmount of tokenIn for takingAmount of
// tokenOut. Each fill must pay its owner at least
//
//	ceil(takingAmount * fillInput * (10000 - slippageBps) / (makingAmount * 10000))
//
// after the execution fee. The fee rate is snapshotted at creation; the total
// fee is floor(cumulativeGrossOutput * executionFeeRate / 10000). Each fill
// pays only the increase in that total, so splitting fills cannot reduce fees.
// Filled and refunded input are tracked separately; only the remaining input
// can be filled before expiry or refunded.
package limit

errors.gno

package limit

import (
	"errors"
)

var (
	// ErrInvalidMakingAmount is returned when makingAmount is not positive.
	ErrInvalidMakingAmount = errors.New("invalid making amount (must be > 0)")

	// ErrInvalidTakingAmount is returned when takingAmount is not positive.
	ErrInvalidTakingAmount = errors.New("invalid taking amount (must be > 0)")

	// ErrInvalidSlippage is returned when slippageBps is outside [0, BpsDenominator].
	ErrInvalidSlippage = errors.New("invalid slippage")

	// ErrInvalidExpiresAt is returned when expiresAt is not positive.
	ErrInvalidExpiresAt = errors.New("invalid expiresAt (must be > 0)")

	// ErrOrderNotActive is returned when no input remains to fill.
	ErrOrderNotActive = errors.New("order is not active")

	// ErrOrderExpired is returned when filling an order at or after its deadline.
	ErrOrderExpired = errors.New("order has expired")

	// ErrInsufficientOutput is returned when a fill reports no output.
	ErrInsufficientOutput = errors.New("insufficient output amount")

	// ErrInvalidFillAmount is returned when a fill input is not in (0, remaining input].
	ErrInvalidFillAmount = errors.New("invalid fill amount")

	// ErrAmountOverflow is returned when an amount, including cumulative
	// gross output, would exceed MaxInt64.
	ErrAmountOverflow = errors.New("amount exceeds int64")

	// ErrSlippageExceeded is returned when a fill's owner-net output is below
	// the order's proportional minimum.
	ErrSlippageExceeded = errors.New("slippage exceeded, output less than minimum")

	// ErrInvalidExecutionFeeRate is returned when an execution fee rate is outside
	// [0, MaxExecutionFeeRate].
	ErrInvalidExecutionFeeRate = errors.New("invalid execution fee rate")
)

gnomod.toml

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

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

keys.gno

package limit

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

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

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

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

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

math.gno

package limit

import (
	"math"

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

// Read-only constants: never pass them to a mutating u256 method.
var (
	maxInt64U256 = u256.NewUint(uint64(math.MaxInt64))
)

// Every product below has int64 or bps operands, so it fits in 140 bits and
// never relies on truncating uint256 overflow.

// CumulativeExecutionFee returns floor(grossOutput * executionFeeRate / BpsDenominator):
// the total execution fee owed on an order's cumulative pool output.
// The execution fee of one fill is the increase of this value, so splitting a fill
// never lowers the total execution fee.
func CumulativeExecutionFee(grossOutput int64, executionFeeRate int64) (int64, error) {
	if grossOutput < 0 {
		return 0, ErrInsufficientOutput
	}

	if !isValidExecutionFeeRate(executionFeeRate) {
		return 0, ErrInvalidExecutionFeeRate
	}

	return toInt64(u256.MulDiv(
		u256.NewUint(uint64(grossOutput)),
		u256.NewUint(uint64(executionFeeRate)),
		u256.NewUint(uint64(BpsDenominator)),
	))
}

// proportionalMinimumOutput returns
// ceil(takingAmount * fillInput * (BpsDenominator-slippageBps) / (makingAmount * BpsDenominator)):
// the owner-net output a fill of fillInput must deliver, rounded up so the
// order's slippage-adjusted ratio is never undercut.
// Callers validate makingAmount > 0, takingAmount > 0, 0 <= fillInput <= makingAmount
// and 0 <= slippageBps <= BpsDenominator.
func proportionalMinimumOutput(makingAmount, takingAmount, slippageBps, fillInput int64) (int64, error) {
	numerator := u256.Zero().Mul(u256.NewUint(uint64(takingAmount)), u256.NewUint(uint64(fillInput)))
	numerator.Mul(numerator, u256.NewUint(uint64(BpsDenominator-slippageBps)))

	denominator := u256.Zero().Mul(u256.NewUint(uint64(makingAmount)), u256.NewUint(uint64(BpsDenominator)))

	return toInt64(u256.DivRoundingUp(numerator, denominator))
}

// requiredGrossOutput returns the least cumulative gross output whose
// owner-net share reaches requiredNet. With
// net(G) = G-floor(G*f/D) = ceil(G*(D-f)/D),
// it is floor((requiredNet-1)*D/(D-f))+1.
// requiredNet must be positive and executionFeeRate valid. The result may exceed
// MaxInt64, in which case it returns ErrAmountOverflow.
func requiredGrossOutput(requiredNet *u256.Uint, executionFeeRate int64) (int64, error) {
	numerator := u256.Zero().Sub(requiredNet, u256.One())
	required := u256.MulDiv(
		numerator,
		u256.NewUint(uint64(BpsDenominator)),
		u256.NewUint(uint64(BpsDenominator-executionFeeRate)),
	)
	required.Add(required, u256.One())

	return toInt64(required)
}

func isValidExecutionFeeRate(executionFeeRate int64) bool {
	return executionFeeRate >= 0 && executionFeeRate <= MaxExecutionFeeRate
}

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

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

order.gno

package limit

import (
	"math"

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

// OrderStatus is the time-derived lifecycle state of a pending limit order.
type OrderStatus string

const (
	// OrderStatusOpen: no input has been filled and the order has not expired.
	OrderStatusOpen OrderStatus = "OPEN"
	// OrderStatusPartiallyFilled: some input has been filled while unexpired.
	OrderStatusPartiallyFilled OrderStatus = "PARTIALLY_FILLED"
	// OrderStatusExpired: the deadline has been reached while input awaits refund.
	OrderStatusExpired OrderStatus = "EXPIRED"
)

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

// Order keeps the original net exchange ratio and execution fee rate
// snapshotted at creation. grossOutput is the output received from the pool.
// Execution fees are paid at each fill, but rounded on cumulative gross output
// so splitting cannot evade them. Every amount, including cumulative gross
// output, stays within MaxInt64.
type Order struct {
	id       uint64
	owner    address
	tokenIn  string
	tokenOut string

	makingAmount     int64
	takingAmount     int64
	slippageBps      int64
	executionFeeRate int64

	createdAt int64
	expiresAt int64

	filledInput   int64
	refundedInput int64
	grossOutput   int64
	executionFee  int64
}

// NewOrder creates an order with executionFeeRate snapshotted for its lifetime.
// Domain terms, including a positive expiry, are validated here;
// token registration and configured duration bounds belong to the implementation.
func NewOrder(
	id uint64,
	owner address,
	tokenIn string,
	tokenOut string,
	makingAmount int64,
	takingAmount int64,
	slippageBps int64,
	executionFeeRate int64,
	createdAt int64,
	expiresAt int64,
) (*Order, error) {
	if makingAmount <= 0 {
		return nil, ErrInvalidMakingAmount
	}

	if takingAmount <= 0 {
		return nil, ErrInvalidTakingAmount
	}

	if slippageBps < 0 || slippageBps > BpsDenominator {
		return nil, ErrInvalidSlippage
	}

	if !isValidExecutionFeeRate(executionFeeRate) {
		return nil, ErrInvalidExecutionFeeRate
	}

	if expiresAt <= 0 {
		return nil, ErrInvalidExpiresAt
	}

	return &Order{
		id:               id,
		owner:            owner,
		tokenIn:          tokenIn,
		tokenOut:         tokenOut,
		makingAmount:     makingAmount,
		takingAmount:     takingAmount,
		slippageBps:      slippageBps,
		executionFeeRate: executionFeeRate,
		createdAt:        createdAt,
		expiresAt:        expiresAt,
	}, nil
}

func (o *Order) ID() uint64              { return o.id }
func (o *Order) Owner() address          { return o.owner }
func (o *Order) TokenIn() string         { return o.tokenIn }
func (o *Order) TokenOut() string        { return o.tokenOut }
func (o *Order) MakingAmount() int64     { return o.makingAmount }
func (o *Order) TakingAmount() int64     { return o.takingAmount }
func (o *Order) SlippageBps() int64      { return o.slippageBps }
func (o *Order) ExecutionFeeRate() int64 { return o.executionFeeRate }

// Status derives the order lifecycle state at the supplied Unix timestamp.
func (o *Order) Status(now int64) OrderStatus {
	if o.IsExpired(now) {
		return OrderStatusExpired
	}

	if o.FilledInput() > 0 {
		return OrderStatusPartiallyFilled
	}

	return OrderStatusOpen
}
func (o *Order) CreatedAt() int64     { return o.createdAt }
func (o *Order) ExpiresAt() int64     { return o.expiresAt }
func (o *Order) FilledInput() int64   { return o.filledInput }
func (o *Order) RefundedInput() int64 { return o.refundedInput }
func (o *Order) GrossOutput() int64   { return o.grossOutput }
func (o *Order) ExecutionFee() int64  { return o.executionFee }

// Clone returns a detached copy that shares no mutable state with o.
// Fields are copied one by one, so a field added later must be added here.
func (o *Order) Clone() *Order {
	return &Order{
		id:       o.id,
		owner:    o.owner,
		tokenIn:  o.tokenIn,
		tokenOut: o.tokenOut,

		makingAmount:     o.makingAmount,
		takingAmount:     o.takingAmount,
		slippageBps:      o.slippageBps,
		executionFeeRate: o.executionFeeRate,

		createdAt: o.createdAt,
		expiresAt: o.expiresAt,

		filledInput:   o.filledInput,
		refundedInput: o.refundedInput,
		grossOutput:   o.grossOutput,
		executionFee:  o.executionFee,
	}
}

// RemainingInput returns escrowed input not yet filled or refunded.
func (o *Order) RemainingInput() int64 {
	return o.makingAmount - o.filledInput - o.refundedInput
}

// IsExpired reports whether the deadline has been reached at now.
func (o *Order) IsExpired(now int64) bool {
	return now >= o.expiresAt
}

// IsActive reports whether unfilled input can accept a fill at now.
func (o *Order) IsActive(now int64) bool {
	return !o.IsExpired(now) && o.RemainingInput() > 0
}

// MinimumUserOutput returns the owner-net output a fill of fillInput must
// deliver: the slippage-adjusted original ratio, rounded up.
func (o *Order) MinimumUserOutput(fillInput int64) (int64, error) {
	if fillInput <= 0 || fillInput > o.RemainingInput() {
		return 0, ErrInvalidFillAmount
	}

	return proportionalMinimumOutput(o.makingAmount, o.takingAmount, o.slippageBps, fillInput)
}

// GetMinimumOutput returns the exact minimum pool output needed by a
// fillInput, including the next cumulative execution-fee rounding
// boundary. It returns ErrAmountOverflow when no fill could satisfy the
// minimum without cumulative gross output exceeding MaxInt64.
func (o *Order) GetMinimumOutput(fillInput int64) (int64, error) {
	minimum, err := o.MinimumUserOutput(fillInput)
	if err != nil {
		return 0, err
	}

	// A zero owner minimum still requires a positive pool output.
	if minimum == 0 {
		if o.grossOutput == math.MaxInt64 {
			return 0, ErrAmountOverflow
		}

		return 1, nil
	}

	requiredNet := u256.NewUint(uint64(o.grossOutput - o.executionFee))
	requiredNet.Add(requiredNet, u256.NewUint(uint64(minimum)))

	requiredGross, err := requiredGrossOutput(requiredNet, o.executionFeeRate)
	if err != nil {
		return 0, err
	}

	return requiredGross - o.grossOutput, nil
}

// ApplyFill records a fill of fillInput that produced poolOutput at now.
// It validates every quantity before changing any accounting; on error the
// order is unchanged.
func (o *Order) ApplyFill(fillInput, poolOutput, now int64) error {
	if o.RemainingInput() <= 0 {
		return ErrOrderNotActive
	}

	if o.IsExpired(now) {
		return ErrOrderExpired
	}

	minimum, err := o.MinimumUserOutput(fillInput)
	if err != nil {
		return err
	}

	if poolOutput <= 0 {
		return ErrInsufficientOutput
	}

	if poolOutput > math.MaxInt64-o.grossOutput {
		return ErrAmountOverflow
	}

	gross := o.grossOutput + poolOutput

	executionFee, err := CumulativeExecutionFee(gross, o.executionFeeRate)
	if err != nil {
		return err
	}

	if poolOutput-(executionFee-o.executionFee) < minimum {
		return ErrSlippageExceeded
	}

	o.filledInput += fillInput
	o.grossOutput = gross
	o.executionFee = executionFee

	return nil
}

// RefundInput consumes the remaining escrow exactly once and returns it,
// without pretending that refunded input was traded. Later calls return 0.
func (o *Order) RefundInput() int64 {
	remaining := o.RemainingInput()
	o.refundedInput += remaining

	return remaining
}

types.gno

package limit

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

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

// ILimitOrder is the implementation interface behind the limit proxy.
type ILimitOrder interface {
	ILimitOrderManager
	ILimitOrderExecutor
	ILimitOrderAdmin
	ILimitOrderGetter
}

// ILimitOrderManager covers owner-facing order operations.
type ILimitOrderManager interface {
	// CreateOrder escrows makingAmount of tokenIn for takingAmount of tokenOut.
	// slippageBps=0 enforces the making/taking ratio or better.
	// expiresAt must be positive and within the configured duration bounds.
	// The execution fee rate is snapshotted from configuration.
	// baseToken must be tokenIn or tokenOut and is emitted as history metadata.
	CreateOrder(
		_ int,
		rlm realm,
		tokenIn string,
		tokenOut string,
		makingAmount int64,
		takingAmount int64,
		slippageBps int64,
		expiresAt int64,
		baseToken string,
	) uint64

	// CancelOrder refunds the remaining input to the owner. Owner only.
	// After the deadline, the refund is emitted as an expired refund.
	CancelOrder(_ int, rlm realm, orderID uint64) (refundIn int64)
}

// ILimitOrderExecutor covers keeper-authorized execution and public cleanup.
type ILimitOrderExecutor interface {
	// ExecuteOrder swaps at most maxAmountIn through the order's token pair
	// at poolFee. A nonzero sqrtPriceLimitX96 permits partial consumption; each fill
	// must still satisfy the order's owner-net minimum on its actual input.
	// Returns actual input and pool output before the order fee.
	ExecuteOrder(_ int, rlm realm, orderID uint64, maxAmountIn int64, poolFee uint32, sqrtPriceLimitX96 string) (actualInput int64, poolOutput int64)

	// CleanupExpiredOrders examines at most min(maxOrders, MaxCleanupBatchSize)
	// orders after startAfterOrderID in ID order and refunds expired ones.
	// It returns the number expired and the last examined ID while more
	// remain, or 0 when the scan is exhausted.
	CleanupExpiredOrders(_ int, rlm realm, startAfterOrderID uint64, maxOrders int) (expired int, nextCursor uint64)
}

// ILimitOrderAdmin covers admin/governance configuration.
// Changes apply to later operations, except where a method states otherwise.
type ILimitOrderAdmin interface {
	// SetExecutionFeeRate sets the execution fee rate snapshotted into new orders,
	// in basis points of gross output.
	SetExecutionFeeRate(_ int, rlm realm, executionFeeRate int64)
	// SetMaxSlippageBps sets the slippage cap for new orders, in [0, 10000] bps.
	SetMaxSlippageBps(_ int, rlm realm, maxSlippageBps int64)
	// SetMinMakingAmount sets the minimum input amount accepted for new orders.
	SetMinMakingAmount(_ int, rlm realm, minMakingAmount int64)
	// SetOrderDeadlines sets the allowed order duration range, in seconds.
	SetOrderDeadlines(_ int, rlm realm, minDuration int64, maxDuration int64)
	// SetMaxCleanupBatchSize caps the orders one CleanupExpiredOrders call examines.
	SetMaxCleanupBatchSize(_ int, rlm realm, maxCleanupBatchSize int64)
}

// ILimitOrderGetter exposes detached pending orders and read-only indexes.
type ILimitOrderGetter interface {
	GetConfig() *Config
	GetNextOrderID() uint64

	ExistsOrder(orderID uint64) bool
	// GetOrder returns a detached copy while pending, or nil after settlement.
	GetOrder(orderID uint64) *Order
	GetOrders() *rotree.ReadOnlyTree
	GetOrdersByOwner() *rotree.ReadOnlyTree

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

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

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

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

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

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