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

v0 source pure

Package limit holds the immutable building blocks of the GnoSwap limit order realm:

Overview

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

Example
1ceil(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.

Constants 5

const BpsDenominator

1const BpsDenominator int64 = 10_000
source

BpsDenominator is 100% in basis points.

const DefaultBPTreeFanout

1const DefaultBPTreeFanout = 16
source

DefaultBPTreeFanout is the fanout of every limit-order B+tree.

const DefaultMaxSlippageBps

1const DefaultMaxSlippageBps int64 = 1_000
source

DefaultMaxSlippageBps is the default maximum slippage for new orders (10%).

const MaxExecutionFeeRate

1const MaxExecutionFeeRate int64 = 1_000
source

MaxExecutionFeeRate is the largest execution fee rate, in basis points (10%).

const OrderStatusOpen, OrderStatusPartiallyFilled, OrderStatusExpired

1const (
2	// OrderStatusOpen: no input has been filled and the order has not expired.
3	OrderStatusOpen OrderStatus = "OPEN"
4	// OrderStatusPartiallyFilled: some input has been filled while unexpired.
5	OrderStatusPartiallyFilled OrderStatus = "PARTIALLY_FILLED"
6	// OrderStatusExpired: the deadline has been reached while input awaits refund.
7	OrderStatusExpired OrderStatus = "EXPIRED"
8)
source

Variables 1

var ErrInvalidMakingAmount, ErrInvalidTakingAmount, ErrInvalidSlippage, ErrInvalidExpiresAt, ErrOrderNotActive, ErrOrderExpired, ErrInsufficientOutput, ErrInvalidFillAmount, ErrAmountOverflow, ErrSlippageExceeded, ErrInvalidExecutionFeeRate

 1var (
 2	// ErrInvalidMakingAmount is returned when makingAmount is not positive.
 3	ErrInvalidMakingAmount = errors.New("invalid making amount (must be > 0)")
 4
 5	// ErrInvalidTakingAmount is returned when takingAmount is not positive.
 6	ErrInvalidTakingAmount = errors.New("invalid taking amount (must be > 0)")
 7
 8	// ErrInvalidSlippage is returned when slippageBps is outside [0, BpsDenominator].
 9	ErrInvalidSlippage = errors.New("invalid slippage")
10
11	// ErrInvalidExpiresAt is returned when expiresAt is not positive.
12	ErrInvalidExpiresAt = errors.New("invalid expiresAt (must be > 0)")
13
14	// ErrOrderNotActive is returned when no input remains to fill.
15	ErrOrderNotActive = errors.New("order is not active")
16
17	// ErrOrderExpired is returned when filling an order at or after its deadline.
18	ErrOrderExpired = errors.New("order has expired")
19
20	// ErrInsufficientOutput is returned when a fill reports no output.
21	ErrInsufficientOutput = errors.New("insufficient output amount")
22
23	// ErrInvalidFillAmount is returned when a fill input is not in (0, remaining input].
24	ErrInvalidFillAmount = errors.New("invalid fill amount")
25
26	// ErrAmountOverflow is returned when an amount, including cumulative
27	// gross output, would exceed MaxInt64.
28	ErrAmountOverflow = errors.New("amount exceeds int64")
29
30	// ErrSlippageExceeded is returned when a fill's owner-net output is below
31	// the order's proportional minimum.
32	ErrSlippageExceeded = errors.New("slippage exceeded, output less than minimum")
33
34	// ErrInvalidExecutionFeeRate is returned when an execution fee rate is outside
35	// [0, MaxExecutionFeeRate].
36	ErrInvalidExecutionFeeRate = errors.New("invalid execution fee rate")
37)
source

Functions 7

func CumulativeExecutionFee

1func CumulativeExecutionFee(grossOutput int64, executionFeeRate int64) (int64, error)
source

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 OrderKey

1func OrderKey(orderID uint64) string
source

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

func OwnerOrderKey

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

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

func OwnerOrderPrefix

1func OwnerOrderPrefix(owner address) string
source

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

func PrefixEnd

1func PrefixEnd(prefix string) string
source

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

func NewConfig

1func NewConfig(
2	executionFeeRate int64,
3	minMakingAmount int64,
4	minOrderDuration int64,
5	maxOrderDuration int64,
6	maxCleanupBatchSize int64,
7) *Config
source

NewConfig returns a config with the given parameters. Bounds are enforced by the implementation that stores it.

func NewOrder

 1func NewOrder(
 2	id uint64,
 3	owner address,
 4	tokenIn string,
 5	tokenOut string,
 6	makingAmount int64,
 7	takingAmount int64,
 8	slippageBps int64,
 9	executionFeeRate int64,
10	createdAt int64,
11	expiresAt int64,
12) (*Order, error)
source

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.

Types 9

type Config

struct
1type Config struct {
2	executionFeeRate    int64 // snapshotted into each new order, bps of gross output
3	maxSlippageBps      int64 // maximum slippage accepted for new orders
4	minMakingAmount     int64 // minimum input amount accepted for new orders
5	minOrderDuration    int64 // shortest allowed expiresAt - createdAt, in seconds
6	maxOrderDuration    int64 // longest allowed expiresAt - createdAt, in seconds
7	maxCleanupBatchSize int64 // most orders one CleanupExpiredOrders call examines
8}
source

Config holds governance-controlled limit-order parameters.

Methods on Config

func Clone

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

Clone returns a copy of the config that shares no state with c. Callers outside the storing realm read the config through it.

func SetExecutionFeeRate

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

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

func SetMaxSlippageBps

method on Config
1func (c *Config) SetMaxSlippageBps(maxSlippageBps int64) error
source

SetMaxSlippageBps sets the maximum slippage accepted for new orders. It returns ErrInvalidSlippage outside [0, BpsDenominator].

type ILimitOrder

interface
1type ILimitOrder interface {
2	ILimitOrderManager
3	ILimitOrderExecutor
4	ILimitOrderAdmin
5	ILimitOrderGetter
6}
source

ILimitOrder is the implementation interface behind the limit proxy.

type ILimitOrderAdmin

interface
 1type ILimitOrderAdmin interface {
 2	// SetExecutionFeeRate sets the execution fee rate snapshotted into new orders,
 3	// in basis points of gross output.
 4	SetExecutionFeeRate(_ int, rlm realm, executionFeeRate int64)
 5	// SetMaxSlippageBps sets the slippage cap for new orders, in [0, 10000] bps.
 6	SetMaxSlippageBps(_ int, rlm realm, maxSlippageBps int64)
 7	// SetMinMakingAmount sets the minimum input amount accepted for new orders.
 8	SetMinMakingAmount(_ int, rlm realm, minMakingAmount int64)
 9	// SetOrderDeadlines sets the allowed order duration range, in seconds.
10	SetOrderDeadlines(_ int, rlm realm, minDuration int64, maxDuration int64)
11	// SetMaxCleanupBatchSize caps the orders one CleanupExpiredOrders call examines.
12	SetMaxCleanupBatchSize(_ int, rlm realm, maxCleanupBatchSize int64)
13}
source

ILimitOrderAdmin covers admin/governance configuration. Changes apply to later operations, except where a method states otherwise.

type ILimitOrderExecutor

interface
 1type ILimitOrderExecutor interface {
 2	// ExecuteOrder swaps at most maxAmountIn through the order's token pair
 3	// at poolFee. A nonzero sqrtPriceLimitX96 permits partial consumption; each fill
 4	// must still satisfy the order's owner-net minimum on its actual input.
 5	// Returns actual input and pool output before the order fee.
 6	ExecuteOrder(_ int, rlm realm, orderID uint64, maxAmountIn int64, poolFee uint32, sqrtPriceLimitX96 string) (actualInput int64, poolOutput int64)
 7
 8	// CleanupExpiredOrders examines at most min(maxOrders, MaxCleanupBatchSize)
 9	// orders after startAfterOrderID in ID order and refunds expired ones.
10	// It returns the number expired and the last examined ID while more
11	// remain, or 0 when the scan is exhausted.
12	CleanupExpiredOrders(_ int, rlm realm, startAfterOrderID uint64, maxOrders int) (expired int, nextCursor uint64)
13}
source

ILimitOrderExecutor covers keeper-authorized execution and public cleanup.

type ILimitOrderGetter

interface
 1type ILimitOrderGetter interface {
 2	GetConfig() *Config
 3	GetNextOrderID() uint64
 4
 5	ExistsOrder(orderID uint64) bool
 6	// GetOrder returns a detached copy while pending, or nil after settlement.
 7	GetOrder(orderID uint64) *Order
 8	GetOrders() *rotree.ReadOnlyTree
 9	GetOrdersByOwner() *rotree.ReadOnlyTree
10
11	GetPendingExecutionFeeAmount(tokenPath string) int64
12	GetPendingExecutionFees() *rotree.ReadOnlyTree
13}
source

ILimitOrderGetter exposes detached pending orders and read-only indexes.

type ILimitOrderManager

interface
 1type ILimitOrderManager interface {
 2	// CreateOrder escrows makingAmount of tokenIn for takingAmount of tokenOut.
 3	// slippageBps=0 enforces the making/taking ratio or better.
 4	// expiresAt must be positive and within the configured duration bounds.
 5	// The execution fee rate is snapshotted from configuration.
 6	// baseToken must be tokenIn or tokenOut and is emitted as history metadata.
 7	CreateOrder(
 8		_ int,
 9		rlm realm,
10		tokenIn string,
11		tokenOut string,
12		makingAmount int64,
13		takingAmount int64,
14		slippageBps int64,
15		expiresAt int64,
16		baseToken string,
17	) uint64
18
19	// CancelOrder refunds the remaining input to the owner. Owner only.
20	// After the deadline, the refund is emitted as an expired refund.
21	CancelOrder(_ int, rlm realm, orderID uint64) (refundIn int64)
22}
source

ILimitOrderManager covers owner-facing order operations.

type ILimitOrderStore

interface
 1type ILimitOrderStore interface {
 2	HasOrders() bool
 3	GetOrders() *bptree.BPTree
 4	SetOrders(_ int, rlm realm, orders *bptree.BPTree) error
 5
 6	HasOrdersByOwner() bool
 7	GetOrdersByOwner() *bptree.BPTree
 8	SetOrdersByOwner(_ int, rlm realm, ordersByOwner *bptree.BPTree) error
 9
10	HasPendingExecutionFees() bool
11	GetPendingExecutionFees() *bptree.BPTree
12	SetPendingExecutionFees(_ int, rlm realm, pendingExecutionFees *bptree.BPTree) error
13
14	HasNextOrderID() bool
15	GetNextOrderID() uint64
16	SetNextOrderID(_ int, rlm realm, id uint64) error
17
18	HasConfig() bool
19	GetConfig() *Config
20	SetConfig(_ int, rlm realm, config *Config) error
21}
source

ILimitOrderStore is the persistent storage shared by all versions.

type Order

struct
 1type Order struct {
 2	id       uint64
 3	owner    address
 4	tokenIn  string
 5	tokenOut string
 6
 7	makingAmount     int64
 8	takingAmount     int64
 9	slippageBps      int64
10	executionFeeRate int64
11
12	createdAt int64
13	expiresAt int64
14
15	filledInput   int64
16	refundedInput int64
17	grossOutput   int64
18	executionFee  int64
19}
source

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.

Methods on Order

func ApplyFill

method on Order
1func (o *Order) ApplyFill(fillInput, poolOutput, now int64) error
source

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 Clone

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

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 GetMinimumOutput

method on Order
1func (o *Order) GetMinimumOutput(fillInput int64) (int64, error)
source

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 ID

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

func IsActive

method on Order
1func (o *Order) IsActive(now int64) bool
source

IsActive reports whether unfilled input can accept a fill at now.

func IsExpired

method on Order
1func (o *Order) IsExpired(now int64) bool
source

IsExpired reports whether the deadline has been reached at now.

func MinimumUserOutput

method on Order
1func (o *Order) MinimumUserOutput(fillInput int64) (int64, error)
source

MinimumUserOutput returns the owner-net output a fill of fillInput must deliver: the slippage-adjusted original ratio, rounded up.

func Owner

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

func RefundInput

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

RefundInput consumes the remaining escrow exactly once and returns it, without pretending that refunded input was traded. Later calls return 0.

func RemainingInput

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

RemainingInput returns escrowed input not yet filled or refunded.

func Status

method on Order
1func (o *Order) Status(now int64) OrderStatus
source

Status derives the order lifecycle state at the supplied Unix timestamp.

func TokenIn

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

func TokenOut

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

type OrderStatus

ident
1type OrderStatus string
source

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

Methods on OrderStatus

func String

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

Dependencies

Source Files 9