Transaction
DEFD0309B69055…568E87EF2FC6
Block 1,651,933 · index 0 · indexed
Summary
- Hash
- DEFD0309B690553F7AD9859EE545C8A850264A6E035014315A3F568E87EF2FC6
- Block
- 1,651,933
- Size
- 21402 bytes
- Gas used
- 32,817,436 / 39,380,888
- Fee
- 39381 ugnot
- Status
- success
Messages
Arguments · 21
- #1limit
- #2doc.gno
- #3// Package limit is the GnoSwap limit order realm. // // Users escrow makingAmount of tokenIn for takingAmount of tokenOut before // expiresAt. Authorized keepers fill orders on a whitelisted direct pool, // without the router, choosing the pool fee tier and swap price limit for // each fill. Partial fills leave unsold input in escrow; each fill pays the // owner immediately after deducting the order's snapshotted execution fee, // while enforcing the order's slippage-adjusted owner-net exchange ratio. // Owners can cancel for the remaining input, and anyone can refund expired // orders through bounded cleanup. Settled orders are removed from the indexes. // // This package is the permanent entry point. It owns the escrow address, the // KV store shared by every version, and the upgrade switch; the business // logic lives in a registered implementation (impl/v0). // // Files: // - proxy.gno: state-changing entry points // - getter.gno: read-only queries // - store.gno: KV store and store keys // - state.gno: realm state and the active implementation // - upgrade.gno: implementation registration and upgrades // - swap_callback.gno: authenticated pool callback paying escrowed input package limit
- #4errors.gno
- #5package limit // Proxy errors carry no error code; codes belong to the implementation. // ErrSpoofedRealm is returned when a store write gets a non-current realm. const ErrSpoofedRealm = "spoofed realm" // ErrNilInitializer is raised by RegisterInitializer for a nil factory. const ErrNilInitializer = "nil initializer" const ( errImplNotInitialized = "implementation is not initialized" errInvalidImpl = "impl is not an ILimitOrder" errInvalidDomainStore = "domainStore is not an ILimitOrderStore" errNilConfig = "config is nil" errImplDoesNotSupportTargetedCleanup = "implementation does not support targeted expired-order cleanup" errImplDoesNotSupportFeeCollection = "implementation does not support pending execution fee collection" // errInvalidSwapCallback is returned by an order's swap callback for a // call it must not pay. errInvalidSwapCallback = "invalid swap callback" // Format strings: the store key name, the config value. errNilValue = "%s is nil" errInvalidConfigType = "failed to cast config: %T" )
- #6getter.gno
- #7package limit import ( plimit "gno.land/p/gnoswap/order/limit/v1" rotree "gno.land/p/nt/bptree/rotree/v0" ) // Getters return detached copies of stored values. Store trees are returned // as read-only views keyed as in the store layout (see store.gno); views whose // entries are pointers copy every entry they return. Callers page a view // themselves through Iterate, IterateByOffset, or their reverse forms. // ================================== // Config Getters // ================================== // GetConfig returns a detached copy of the current global configuration. // // Returns: // - *plimit.Config: copy of the stored configuration func GetConfig() *plimit.Config { return getImplementation().GetConfig() } // GetExecutionFeeRate returns the execution fee rate snapshotted into new orders. // // Returns: // - int64: execution fee rate, in basis points of gross output func GetExecutionFeeRate() int64 { return GetConfig().ExecutionFeeRate() } // GetMaxSlippageBps returns the slippage cap for new orders. // // Returns: // - int64: maximum slippage, in basis points func GetMaxSlippageBps() int64 { return GetConfig().MaxSlippageBps() } // GetMinMakingAmount returns the minimum input amount for new orders. // // Returns: // - int64: minimum makingAmount, in raw token units func GetMinMakingAmount() int64 { return GetConfig().MinMakingAmount() } // GetOrderDeadlines returns the allowed order duration range for new orders. // // Returns: // - int64: shortest allowed expiresAt - createdAt, in seconds // - int64: longest allowed expiresAt - createdAt, in seconds func GetOrderDeadlines() (int64, int64) { config := GetConfig() return config.MinOrderDuration(), config.MaxOrderDuration() } // GetMaxCleanupBatchSize returns the most orders one CleanupExpiredOrders call examines. // // Returns: // - int64: maximum cleanup batch size func GetMaxCleanupBatchSize() int64 { return GetConfig().MaxCleanupBatchSize() } // ================================== // Order Getters // ================================== // GetNextOrderID returns the ID the next created order receives. // // Returns: // - uint64: next order ID func GetNextOrderID() uint64 { return getImplementation().GetNextOrderID() } // ExistsOrder reports whether an order is pending. // Settled orders are deleted. // // Parameters: // - orderID: order to look up // // Returns: // - bool: true while the order is pending func ExistsOrder(orderID uint64) bool { return getImplementation().ExistsOrder(orderID) } // GetOrder returns a detached pending order, or nil after it is settled. // // Parameters: // - orderID: order to look up // // Returns: // - *plimit.Order: copy of the order; nil when it is not pending func GetOrder(orderID uint64) *plimit.Order { return getImplementation().GetOrder(orderID) } // GetOrders returns a live read-only view of pending orders. // // Returns: // - *rotree.ReadOnlyTree: plimit.OrderKey(orderID) -> *plimit.Order; // each order read from the view is detached from stored state func GetOrders() *rotree.ReadOnlyTree { return getImplementation().GetOrders() } // GetOrdersByOwner returns the read-only owner index of pending orders. // Iterate the [plimit.OwnerOrderPrefix(owner), plimit.PrefixEnd(prefix)) // range for one owner's orders in ID order, choosing the page size. // // Returns: // - *rotree.ReadOnlyTree: plimit.OwnerOrderKey(owner, orderID) -> uint64 orderID func GetOrdersByOwner() *rotree.ReadOnlyTree { return getImplementation().GetOrdersByOwner() } // ================================== // Execution Fee Getters // ================================== // GetPendingExecutionFeeAmount returns execution fees held for tokenPath until the // protocol fee realm accepts them. A later fill with the same output token retries collection. // // Parameters: // - tokenPath: fee token path // // Returns: // - int64: pending execution fee, in raw token units func GetPendingExecutionFeeAmount(tokenPath string) int64 { return getImplementation().GetPendingExecutionFeeAmount(tokenPath) } // GetPendingExecutionFees returns the read-only index of pending execution fees. // // Returns: // - *rotree.ReadOnlyTree: tokenPath -> int64 pending amount func GetPendingExecutionFees() *rotree.ReadOnlyTree { return getImplementation().GetPendingExecutionFees() }
- #8gnomod.toml
- #9module = "gno.land/r/gnoswap/order/limit" gno = "0.9"
- #10proxy.gno
- #11package limit type expiredOrderCleanup interface { CleanupExpiredOrdersByIDs(_ int, rlm realm, orderIDs string) (expired int, retryOrderIDs string) } type pendingExecutionFeeCollector interface { CollectPendingExecutionFee(_ int, rlm realm, tokenPath string) (int64, int64) } // CreateOrder escrows makingAmount of tokenIn for takingAmount of tokenOut. // Each fill supplies its pool fee tier and price limit. // 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 into each new order. // baseToken must be tokenIn (Sell) or tokenOut (Buy); it is emitted only as // creation metadata and does not affect the order's execution terms. // The caller must first approve Address() for makingAmount. // Reverts while execution is halted for Limit orders. func CreateOrder( cur realm, tokenIn string, tokenOut string, makingAmount int64, takingAmount int64, slippageBps int64, expiresAt int64, baseToken string, ) uint64 { return getImplementation().CreateOrder(0, cur, tokenIn, tokenOut, makingAmount, takingAmount, slippageBps, expiresAt, baseToken) } // CancelOrder refunds the remaining input and removes the order from the indexes. // A past-deadline refund uses the expired event. // It returns the refunded input. // // Owner only. Reverts while withdrawals are halted for limit orders. func CancelOrder(cur realm, orderID uint64) int64 { return getImplementation().CancelOrder(0, cur, orderID) } // ExecuteOrder fills up to maxAmountIn through the order's token pair at poolFee. // A nonzero sqrtPriceLimitX96 stops at that pool price and may leave input // unspent in escrow. Zero requires maxAmountIn to be consumed in full. // The order's minimum owner-net output is enforced on the actual input. // Returns actual input and pool output before the order's execution fee; // the owner is paid immediately after that fee is deducted. // The immediate caller must be authorized for ExecuteOrder by the shared // keeper policy. Reverts while execution or withdrawals are halted for limit orders. func ExecuteOrder(cur realm, orderID uint64, maxAmountIn int64, poolFee uint32, sqrtPriceLimitX96 string) (int64, int64) { return getImplementation().ExecuteOrder(0, cur, orderID, maxAmountIn, poolFee, sqrtPriceLimitX96) } // CollectPendingExecutionFee forwards fees pending for tokenPath to the protocol // fee realm without another fill. Anyone may call it; the caller receives nothing. // Returns the amount forwarded and the amount left pending. // Reverts while withdrawals are halted for Limit orders. func CollectPendingExecutionFee(cur realm, tokenPath string) (int64, int64) { collector, ok := getImplementation().(pendingExecutionFeeCollector) if !ok { panic(errImplDoesNotSupportFeeCollection) } return collector.CollectPendingExecutionFee(0, cur, tokenPath) } // CleanupExpiredOrders refunds pending orders after their deadline. // Anyone may call it. // // One call examines at most min(maxOrders, maxCleanupBatchSize) orders after // startAfterOrderID, in ID order. It returns the number of orders expired and // the cursor for the next call; repeat until the cursor is 0. // Reverts while withdrawals are halted for limit orders. func CleanupExpiredOrders(cur realm, startAfterOrderID uint64, maxOrders int) (int, uint64) { return getImplementation().CleanupExpiredOrders(0, cur, startAfterOrderID, maxOrders) } // CleanupExpiredOrdersByIDs refunds only the named expired orders. // orderIDs is a strictly increasing comma-separated list of positive decimal // order IDs. Existing unexpired or underfunded orders are returned for retry. // Reverts while withdrawals are halted for limit orders. func CleanupExpiredOrdersByIDs(cur realm, orderIDs string) (int, string) { cleanup, ok := getImplementation().(expiredOrderCleanup) if !ok { panic(errImplDoesNotSupportTargetedCleanup) } return cleanup.CleanupExpiredOrdersByIDs(0, cur, orderIDs) } // SetExecutionFeeRate sets the execution fee rate snapshotted into new orders, // in basis points of gross output. // Admin or governance only. func SetExecutionFeeRate(cur realm, executionFeeRate int64) { getImplementation().SetExecutionFeeRate(0, cur, executionFeeRate) } // SetMinMakingAmount sets the minimum input amount for new orders, in raw token units. // Existing orders are unaffected. Admin or governance only. func SetMinMakingAmount(cur realm, minMakingAmount int64) { getImplementation().SetMinMakingAmount(0, cur, minMakingAmount) } // SetOrderDeadlines sets the allowed order duration range for new orders, // in seconds. Admin or governance only. func SetOrderDeadlines(cur realm, minDuration int64, maxDuration int64) { getImplementation().SetOrderDeadlines(0, cur, minDuration, maxDuration) } // SetMaxCleanupBatchSize caps the orders one CleanupExpiredOrders call examines, // bounding its gas. Admin or governance only. func SetMaxCleanupBatchSize(cur realm, maxCleanupBatchSize int64) { getImplementation().SetMaxCleanupBatchSize(0, cur, maxCleanupBatchSize) } // SetMaxSlippageBps sets the slippage cap for new orders in [0, 10000] bps. // Existing orders keep their slippage. Admin or governance only. func SetMaxSlippageBps(cur realm, maxSlippageBps int64) { getImplementation().SetMaxSlippageBps(0, cur, maxSlippageBps) }
- #12state.gno
- #13package limit import ( _ "gno.land/r/gnoswap/rbac/v1" // registers the roles read through access "errors" plimit "gno.land/p/gnoswap/order/limit/v1" "gno.land/p/gnoswap/store/v1" "gno.land/p/gnoswap/version_manager/v1" ) var ( currentAddress address kvStore store.KVStore versionManager version_manager.VersionManager implementation plimit.ILimitOrder ) func init(cur realm) { currentAddress = cur.Address() kvStore = store.NewKVStore(currentAddress) versionManager = version_manager.NewVersionManager( cur.PkgPath(), kvStore, initializeDomainStore, ) implementation = nil } func initializeDomainStore(_ int, _ realm, kvStore store.KVStore) any { return NewLimitOrderStore(kvStore) } // Address returns the realm address that escrows order funds. // Users approve it before CreateOrder. func Address() address { return currentAddress } func getImplementation() plimit.ILimitOrder { if implementation == nil { panic(errImplNotInitialized) } return implementation } func updateImplementation() error { result := versionManager.GetCurrentImplementation() if result == nil { return errors.New(errImplNotInitialized) } impl, ok := result.(plimit.ILimitOrder) if !ok { return errors.New(errInvalidImpl) } implementation = impl return nil }
- #14store.gno
- #15package limit import ( "errors" plimit "gno.land/p/gnoswap/order/limit/v1" "gno.land/p/gnoswap/store/v1" bptree "gno.land/p/nt/bptree/v0" ufmt "gno.land/p/nt/ufmt/v0" ) // NewBPTreeN allocates an empty B+tree in the order/limit realm. // Implementations create the store trees through it, // so the trees are owned by the realm that stores them. func NewBPTreeN(fanout int) *bptree.BPTree { return bptree.NewBPTreeN(fanout) } // StoreKey is a key of the limit order KV store. type StoreKey string func (s StoreKey) String() string { return string(s) } // Store layout. Tree keys are built by the plimit key helpers. // // orders OrderKey -> *Order, pending orders only // ordersByOwner OwnerOrderKey -> orderID, pending orders only // pendingExecutionFees tokenPath -> int64, held until the protocol fee collector accepts them // nextOrderID uint64 // config *Config const ( StoreKeyOrders StoreKey = "orders" StoreKeyOrdersByOwner StoreKey = "ordersByOwner" StoreKeyPendingExecutionFees StoreKey = "pendingExecutionFees" StoreKeyNextOrderID StoreKey = "nextOrderID" StoreKeyConfig StoreKey = "config" ) type limitOrderStore struct { kvStore store.KVStore } // NewLimitOrderStore wraps the domain KV store. func NewLimitOrderStore(kvStore store.KVStore) plimit.ILimitOrderStore { return &limitOrderStore{kvStore: kvStore} } // set writes key after checking that rlm is the current realm. // The KV store additionally enforces its write ACL for code realms. func (s *limitOrderStore) set(_ int, rlm realm, key string, value any) error { if !rlm.IsCurrent() { return errors.New(ErrSpoofedRealm) } return s.kvStore.Set(0, rlm, key, value) } func (s *limitOrderStore) getTree(key StoreKey) *bptree.BPTree { tree, err := s.kvStore.GetBPTree(key.String()) if err != nil { panic(err.Error()) } if tree == nil { panic(ufmt.Sprintf(errNilValue, key.String())) } return tree } func (s *limitOrderStore) setTree(_ int, rlm realm, key StoreKey, tree *bptree.BPTree) error { if !rlm.IsCurrent() { return errors.New(ErrSpoofedRealm) } if tree == nil { return ufmt.Errorf(errNilValue, key.String()) } return s.kvStore.Set(0, rlm, key.String(), tree) } func (s *limitOrderStore) HasOrders() bool { return s.kvStore.Has(StoreKeyOrders.String()) } func (s *limitOrderStore) GetOrders() *bptree.BPTree { return s.getTree(StoreKeyOrders) } func (s *limitOrderStore) SetOrders(_ int, rlm realm, orders *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyOrders, orders) } func (s *limitOrderStore) HasOrdersByOwner() bool { return s.kvStore.Has(StoreKeyOrdersByOwner.String()) } func (s *limitOrderStore) GetOrdersByOwner() *bptree.BPTree { return s.getTree(StoreKeyOrdersByOwner) } func (s *limitOrderStore) SetOrdersByOwner(_ int, rlm realm, ordersByOwner *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyOrdersByOwner, ordersByOwner) } func (s *limitOrderStore) HasPendingExecutionFees() bool { return s.kvStore.Has(StoreKeyPendingExecutionFees.String()) } func (s *limitOrderStore) GetPendingExecutionFees() *bptree.BPTree { return s.getTree(StoreKeyPendingExecutionFees) } func (s *limitOrderStore) SetPendingExecutionFees(_ int, rlm realm, pendingExecutionFees *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyPendingExecutionFees, pendingExecutionFees) } func (s *limitOrderStore) HasNextOrderID() bool { return s.kvStore.Has(StoreKeyNextOrderID.String()) } func (s *limitOrderStore) GetNextOrderID() uint64 { id, err := s.kvStore.GetUint64(StoreKeyNextOrderID.String()) if err != nil { panic(err.Error()) } return id } func (s *limitOrderStore) SetNextOrderID(_ int, rlm realm, id uint64) error { return s.set(0, rlm, StoreKeyNextOrderID.String(), id) } func (s *limitOrderStore) HasConfig() bool { return s.kvStore.Has(StoreKeyConfig.String()) } func (s *limitOrderStore) GetConfig() *plimit.Config { result, err := s.kvStore.Get(StoreKeyConfig.String()) if err != nil { panic(err.Error()) } config, ok := result.(*plimit.Config) if !ok || config == nil { panic(ufmt.Sprintf(errInvalidConfigType, result)) } return config } func (s *limitOrderStore) SetConfig(_ int, rlm realm, config *plimit.Config) error { if !rlm.IsCurrent() { return errors.New(ErrSpoofedRealm) } if config == nil { return errors.New(errNilConfig) } return s.kvStore.Set(0, rlm, StoreKeyConfig.String(), config) }
- #16swap_callback.gno
- #17package limit import ( "errors" prbac "gno.land/p/gnoswap/rbac/v1" "gno.land/r/gnoswap/access/v1" "gno.land/r/gnoswap/common" "gno.land/r/gnoswap/pool" ) // NewSwapCallback binds payment to this proxy's custody, the order's input // token and its input budget. Only code already executing in the proxy's current // realm context can create it. The closure is declared here so pool callbacks // retain proxy custody rather than paying from an implementation realm. func NewSwapCallback(_ int, rlm realm, tokenIn string, zeroForOne bool, maxAmountIn int64) func(cur realm, amount0Delta, amount1Delta int64, marker *pool.CallbackMarker) error { if !rlm.IsCurrent() || rlm.Address() != Address() || tokenIn == "" || maxAmountIn <= 0 { panic(errInvalidSwapCallback) } poolAddress := access.MustGetAddress(prbac.ROLE_POOL.String()) remaining := maxAmountIn return func(cur realm, amount0Delta, amount1Delta int64, marker *pool.CallbackMarker) error { if !cur.IsCurrent() || cur.Address() != Address() || cur.Previous().Address() != poolAddress || marker == nil { return errors.New(errInvalidSwapCallback) } input, output := amount0Delta, amount1Delta if !zeroForOne { input, output = amount1Delta, amount0Delta } if input <= 0 || output > 0 || input > remaining { return errors.New(errInvalidSwapCallback) } remaining -= input return common.Transfer(0, cur, tokenIn, poolAddress, input) } }
- #18upgrade.gno
- #19package limit import ( plimit "gno.land/p/gnoswap/order/limit/v1" "gno.land/r/gnoswap/access/v1" ) // RegisterInitializer registers an implementation version. // Each version calls it from init with a factory that receives the shared store. // Only packages under this realm's path may register, // and the first registration becomes active. // A nil initializer is rejected before its version path is registered. func RegisterInitializer(cur realm, initializer func(_ int, rlm realm, orderStore plimit.ILimitOrderStore) plimit.ILimitOrder) { if initializer == nil { panic(ErrNilInitializer) } initializerFunc := func(_ int, rlm realm, domainStore any) any { access.AssertIsRlmCurrent(0, rlm) orderStore, ok := domainStore.(plimit.ILimitOrderStore) if !ok { panic(errInvalidDomainStore) } return initializer(0, rlm, orderStore) } err := versionManager.RegisterInitializer(0, cur, initializerFunc) if err != nil { panic(err.Error()) } err = updateImplementation() if err != nil { panic(err.Error()) } } // UpgradeImpl activates a previously registered version by package path. // Admin or governance only. func UpgradeImpl(cur realm, packagePath string) { caller := cur.Previous().Address() access.AssertIsAdminOrGovernance(caller) err := versionManager.ChangeImplementation(0, cur, packagePath) if err != nil { panic(err.Error()) } err = updateImplementation() if err != nil { panic(err.Error()) } } // GetImplementationPackagePath returns the active implementation path. func GetImplementationPackagePath() string { return versionManager.GetCurrentPackagePath() }
- #20/gno.MemPackageType
- #21 MPUserAll
Result log
msg:0,success:true,log:,events:[]