const BpsDenominator
BpsDenominator is 100% in basis points.
Package limit holds the immutable building blocks of the GnoSwap limit order realm:
Package limit holds the immutable building blocks of the GnoSwap limit order realm:
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
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.
BpsDenominator is 100% in basis points.
DefaultBPTreeFanout is the fanout of every limit-order B+tree.
DefaultMaxSlippageBps is the default maximum slippage for new orders (10%).
MaxExecutionFeeRate is the largest execution fee rate, in basis points (10%).
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) 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)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.
OrderKey encodes an order ID so B+tree order matches numeric order.
OwnerOrderKey sorts an owner's orders by ID under OwnerOrderPrefix.
OwnerOrderPrefix is the common prefix of an owner's index keys.
PrefixEnd is an exclusive upper bound for prefix + 8-byte encoded ID keys. Nine 0xff bytes sort after every 8-byte suffix.
NewConfig returns a config with the given parameters. Bounds are enforced by the implementation that stores it.
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.
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}Config holds governance-controlled limit-order parameters.
Clone returns a copy of the config that shares no state with c. Callers outside the storing realm read the config through it.
SetExecutionFeeRate sets the execution fee rate in basis points. It returns ErrInvalidExecutionFeeRate outside [0, MaxExecutionFeeRate].
SetMaxSlippageBps sets the maximum slippage accepted for new orders. It returns ErrInvalidSlippage outside [0, BpsDenominator].
ILimitOrder is the implementation interface behind the limit proxy.
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}ILimitOrderAdmin covers admin/governance configuration. Changes apply to later operations, except where a method states otherwise.
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}ILimitOrderExecutor covers keeper-authorized execution and public cleanup.
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}ILimitOrderGetter exposes detached pending orders and read-only indexes.
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}ILimitOrderManager covers owner-facing order operations.
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}ILimitOrderStore is the persistent storage shared by all versions.
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}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.
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.
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.
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.
IsActive reports whether unfilled input can accept a fill at now.
IsExpired reports whether the deadline has been reached at now.
MinimumUserOutput returns the owner-net output a fill of fillInput must deliver: the slippage-adjusted original ratio, rounded up.
RefundInput consumes the remaining escrow exactly once and returns it, without pretending that refunded input was traded. Later calls return 0.
RemainingInput returns escrowed input not yet filled or refunded.
Status derives the order lifecycle state at the supplied Unix timestamp.
OrderStatus is the time-derived lifecycle state of a pending limit order.