Transaction
406783613A2984…324D58A4B0D2
Block 1,651,932 · index 0 · indexed
Summary
- Hash
- 406783613A2984E6A9EFE85AE7664F6F693F3F6AB4C47CE4DC34324D58A4B0D2
- Block
- 1,651,932
- Size
- 46493 bytes
- Gas used
- 64,863,643 / 77,836,336
- Fee
- 77837 ugnot
- Status
- success
Messages
- Package
- gno.land/r/gnoswap/order/dca
Arguments · 21
- #1dca
- #2doc.gno
- #3// Package dca is the GnoSwap DCA (dollar-cost averaging) order realm. // // Users escrow inputToken and sell amountPerExecution of it for outputToken // every interval, executionCount times, at a chosen slot of the interval // (e.g. 09:00 UTC daily). Orders of the same pair, interval, and slot // form a group that keepers execute in one pool swap per round, on the // pair's best whitelisted pool, without the router. Each round's swap output // accrues to the orders and is paid by Claim, or by keepers through // ClaimGroupOrders; each payout deducts the execution fee at the rate the // order snapshotted when it was created. // // 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 package dca
- #4errors.gno
- #5package dca import ( ufmt "gno.land/p/nt/ufmt/v0" ) // 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" // ErrUpgradeWhileExecuting is raised by UpgradeImpl during a group swap. const ErrUpgradeWhileExecuting = "cannot upgrade while a group execution is in progress" // ErrInvalidSwapCallback is returned by a round's swap callback for a call it // must not pay: not from the pool, outside a round, a second payment, or a // delta that is not the round's exact input (e.g. a pool without liquidity // owes nothing). const ErrInvalidSwapCallback = "invalid swap callback" const ( errImplNotInitialized = "implementation is not initialized" errInvalidImpl = "impl is not an IDCAOrder" errInvalidDomainStore = "domainStore is not an IDCAOrderStore" errNilConfig = "config is nil" // Format strings: the store key name, the config value. errNilValue = "%s is nil" errInvalidConfigType = "failed to cast config: %T" ) func makeErrorWithDetails(message string, details string) error { return ufmt.Errorf("%s || %s", message, details) }
- #6getter.gno
- #7package dca import ( pdca "gno.land/p/gnoswap/order/dca/v1" rotree "gno.land/p/nt/bptree/rotree/v0" ) // Getters return 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 copy of the configuration. // // Returns: // - *pdca.Config: copy of the stored configuration func GetConfig() *pdca.Config { return getImplementation().GetConfig() } // GetExecutionFeeRate returns the execution fee rate new orders snapshot: // the share of an order's output sent to the protocol fee realm. // An existing order's rate is pdca.Order.ExecutionFeeRate (see GetOrder). // // Returns: // - int64: execution fee rate, in basis points func GetExecutionFeeRate() int64 { return GetConfig().ExecutionFeeRate() } // GetMaxPoolPriceDeviationRate returns how far, in basis points of price, a // pool's price may sit on the favorable side of its swap price limit and still // be quoted (see SetMaxPoolPriceDeviationRate); 0 means the check is off. // // Returns: // - int64: rate in basis points func GetMaxPoolPriceDeviationRate() int64 { return GetConfig().MaxPoolPriceDeviationRate() } // GetMaxPairPriceLimitAge returns how long, in seconds, a pair price limit // stays usable after it was set (see SetMaxPairPriceLimitAge). // // Returns: // - int64: maximum age in seconds func GetMaxPairPriceLimitAge() int64 { return GetConfig().MaxPairPriceLimitAge() } // GetMaxExecutionCount returns the maximum executions of a new order. // // Returns: // - int64: maximum executionCount func GetMaxExecutionCount() int64 { return GetConfig().MaxExecutionCount() } // GetAllowedIntervals returns the intervals new orders may use. // // Returns: // - []int64: allowed intervals in seconds, ascending func GetAllowedIntervals() []int64 { return GetConfig().AllowedIntervals() } // IsAllowedInterval reports whether new orders may use interval. // // Parameters: // - interval: round interval, in seconds // // Returns: // - bool: true when interval is allowed func IsAllowedInterval(interval int64) bool { return GetConfig().IsAllowedInterval(interval) } // GetSlotStep returns the spacing of the slot offsets new orders may use at interval. // // Parameters: // - interval: round interval, in seconds // // Returns: // - int64: slot step in seconds; 0 when interval is not allowed func GetSlotStep(interval int64) int64 { return GetConfig().SlotStep(interval) } // GetMinExecutionGapRate returns the minimum gap between a group's executions. // // Returns: // - int64: minimum gap, in basis points of the group interval func GetMinExecutionGapRate() int64 { return GetConfig().MinExecutionGapRate() } // GetMaxClaimBatchSize returns the most orders one ClaimGroupOrders call examines. // // Returns: // - int64: maximum claim batch size func GetMaxClaimBatchSize() int64 { return GetConfig().MaxClaimBatchSize() } // ================================== // 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 active. // Finished orders are deleted. // // Parameters: // - orderID: order to look up // // Returns: // - bool: true while the order is active func ExistsOrder(orderID uint64) bool { return getImplementation().ExistsOrder(orderID) } // GetOrder returns a copy of an active order. // Finished orders are deleted and return an error. // // Parameters: // - orderID: order to look up // // Returns: // - *pdca.Order: copy of the order // - error: non-nil when the order is not active func GetOrder(orderID uint64) (*pdca.Order, error) { return getImplementation().GetOrder(orderID) } // GetOrders returns a read-only view of active orders. // // Returns: // - *rotree.ReadOnlyTree: pdca.OrderKey(orderID) -> *pdca.Order; // each order read from the view is a copy func GetOrders() *rotree.ReadOnlyTree { return getImplementation().GetOrders() } // GetOrdersByOwner returns the read-only owner index of active orders. // Iterate the [pdca.OwnerOrderPrefix(owner), pdca.PrefixEnd(prefix)) range // for one owner's orders in ID order. // // Returns: // - *rotree.ReadOnlyTree: pdca.OwnerOrderKey(owner, orderID) -> uint64 orderID func GetOrdersByOwner() *rotree.ReadOnlyTree { return getImplementation().GetOrdersByOwner() } // GetOrderIDsByOwner returns up to count active order IDs of owner, // ascending and greater than startAfterID (0 starts from the first). // Page by passing the last returned ID. // // Parameters: // - owner: order owner // - startAfterID: exclusive lower bound of the returned IDs // - count: maximum number of IDs returned // // Returns: // - []uint64: active order IDs, ascending func GetOrderIDsByOwner(owner address, startAfterID uint64, count int) []uint64 { return getImplementation().GetOrderIDsByOwner(owner, startAfterID, count) } // GetClaimableAmount returns the output an order can claim now, // net of the order's execution fee. // // Parameters: // - orderID: order to look up // // Returns: // - int64: output the next Claim pays the owner; 0 when the order is not active func GetClaimableAmount(orderID uint64) int64 { return getImplementation().GetClaimableAmount(orderID) } // GetOrderExecutionLogs returns copies of up to count of an active order's // unreleased execution logs, oldest first: each covers up to three rounds, // [FirstRound, LastRound], and the input the order sells in each. A log is // released once all of its rounds executed and the order is claimed; // the rounds' swap results are in the DCAGroupExecuted events. // // Parameters: // - orderID: order to look up // - count: maximum number of logs returned // // Returns: // - []*pdca.ExecutionLog: copies of the order's unreleased logs // - error: non-nil when the order is not active func GetOrderExecutionLogs(orderID uint64, count int) ([]*pdca.ExecutionLog, error) { return getImplementation().GetOrderExecutionLogs(orderID, count) } // GetExecutionLogs returns the read-only index of unreleased execution logs. // Iterate the [pdca.ExecutionLogPrefix(orderID), pdca.PrefixEnd(prefix)) // range for one order's logs; the key suffix decodes to the first round. // // Returns: // - *rotree.ReadOnlyTree: pdca.ExecutionLogKey(orderID, firstRound) -> uint64 lastRound func GetExecutionLogs() *rotree.ReadOnlyTree { return getImplementation().GetExecutionLogs() } // ================================== // Group Getters // ================================== // ExistsGroup reports whether a group is stored. // // Parameters: // - groupID: pdca.MakeGroupID(inputToken, outputToken, interval, slotOffset) // // Returns: // - bool: true when the group exists func ExistsGroup(groupID string) bool { return getImplementation().ExistsGroup(groupID) } // GetGroup returns a copy of a group without its round marks. // The copy's round mark tree is empty; read the marks through GetGroupRoundMarks. // // Parameters: // - groupID: group to look up // // Returns: // - *pdca.Group: copy of the group's fields // - error: non-nil when the group does not exist func GetGroup(groupID string) (*pdca.Group, error) { return getImplementation().GetGroup(groupID) } // GetGroups returns a read-only view of every group. // // Returns: // - *rotree.ReadOnlyTree: groupID -> *pdca.Group; each group read from // the view is a copy without its round marks, as GetGroup returns func GetGroups() *rotree.ReadOnlyTree { return getImplementation().GetGroups() } // GetGroupRoundMarks returns a read-only view of a group's round marks: // one per round at which an unfinalized order ends. // // Parameters: // - groupID: group to look up // // Returns: // - *rotree.ReadOnlyTree: pdca.RoundKey(round) -> *pdca.RoundMark; each // mark read from the view is a copy. nil when the group does not exist func GetGroupRoundMarks(groupID string) *rotree.ReadOnlyTree { return getImplementation().GetGroupRoundMarks(groupID) } // GetOrdersByGroup returns the read-only group index of active orders. // Iterate the [pdca.GroupOrderPrefix(groupID), pdca.PrefixEnd(prefix)) // range for one group's orders in ID order. // // Returns: // - *rotree.ReadOnlyTree: pdca.GroupOrderKey(groupID, orderID) -> uint64 orderID func GetOrdersByGroup() *rotree.ReadOnlyTree { return getImplementation().GetOrdersByGroup() } // GetOrderAmountsByGroup returns the read-only group index of orders by // executionFeeRate, then amountPerExecution, which a round reads for the // smallest order of each fee rate. // Iterate the [pdca.GroupOrderPrefix(groupID), pdca.PrefixEnd(prefix)) // range for one group's orders by ascending executionFeeRate, // amountPerExecution, then ID, or the // [pdca.GroupOrderFeeRatePrefix(groupID, rate), pdca.PrefixEnd(prefix)) // range for the orders of one fee rate. // A finished order's entry stays until the order is paid out // or a later round of its group removes it. // // Returns: // - *rotree.ReadOnlyTree: pdca.GroupOrderAmountKey(groupID, executionFeeRate, amountPerExecution, orderID) -> uint64 endRound func GetOrderAmountsByGroup() *rotree.ReadOnlyTree { return getImplementation().GetOrderAmountsByGroup() } // GetOrderIDsByGroup returns up to count active order IDs of a group, // ascending and greater than startAfterID. Page as GetOrderIDsByOwner. // // Parameters: // - groupID: group to look up // - startAfterID: exclusive lower bound of the returned IDs // - count: maximum number of IDs returned // // Returns: // - []uint64: active order IDs, ascending func GetOrderIDsByGroup(groupID string, startAfterID uint64, count int) []uint64 { return getImplementation().GetOrderIDsByGroup(groupID, startAfterID, count) } // GetScheduledGroups returns the read-only schedule of groups with input to // sell, ordered by next execution timestamp, then group ID. // pdca.ScheduleKeyTimestamp decodes a key's timestamp. // // Returns: // - *rotree.ReadOnlyTree: pdca.ScheduleKey(nextExecutionTimestamp, groupID) -> string groupID func GetScheduledGroups() *rotree.ReadOnlyTree { return getImplementation().GetScheduledGroups() } // GetExecutableGroups returns copies of up to count groups due now, // oldest first. // // Paging: start with cursor "", // then pass pdca.FormatScheduleCursor of the last group back // until fewer than count groups return. // The cursor is a fixed schedule position, // so groups executed between pages do not shift it. // // Parameters: // - cursor: "" or "<nextExecutionTimestamp>|<groupID>" of the last group seen // - count: maximum number of groups returned // // Returns: // - []*pdca.Group: copies of due groups without their round marks; // empty while execution is halted // - error: non-nil when cursor is malformed func GetExecutableGroups(cursor string, count int) ([]*pdca.Group, error) { return getImplementation().GetExecutableGroups(cursor, count) } // GetExecutionQuote returns, as JSON, how the group's next round would trade // now: its input, the selected pool, the expected pool output, an estimate // of the orders' execution fees on that output and of what is left for the // orders, and every candidate pool's quote or ineligibility reason. // Orders pay their own snapshotted fee rates when paid out, each rounding // its own cumulative fee. The fee and order output totals instead charge // executionFeeRate, the highest rate of the orders the round sells (0 when // none does), once on the whole output, so they are estimates, not bounds: // the fees the orders pay can exceed expectedExecutionFeeAmount by rounding. // minAmountsByExecutionFeeRate lists, by ascending fee rate, the smallest // order of each rate the round sells. The round reverts unless every listed // order is credited at least max(1, minOrderAmountOut) net of its rate; // expectedMinOrderAmountOut is the least such output at expectedAmountOut, // and minAmountPerExecution the smallest order overall. // Keepers set amountOutMin from expectedAmountOut // and pass amountIn as expectedAmountIn. // // Parameters: // - groupID: group to quote // // Returns: // - string: JSON quote; "" when the group does not exist func GetExecutionQuote(groupID string) string { return getImplementation().GetExecutionQuote(groupID) } // ================================== // Manager Setting Getters // ================================== // GetTokenMinAmountPerExecution returns the minimum input per execution the // manager set for tokenPath (see SetTokenMinAmountPerExecution). // // Parameters: // - tokenPath: input token path // // Returns: // - int64: minimum in raw token units; 0 when none is set func GetTokenMinAmountPerExecution(tokenPath string) int64 { return getImplementation().GetTokenMinAmountPerExecution(tokenPath) } // GetMinAmountPerExecution returns the minimum input per execution a new // order selling tokenPath needs: the larger of GetConfig().MinAmountPerExecution() // and GetTokenMinAmountPerExecution(tokenPath). // // Parameters: // - tokenPath: input token path // // Returns: // - int64: effective minimum, in raw token units func GetMinAmountPerExecution(tokenPath string) int64 { return getImplementation().GetMinAmountPerExecution(tokenPath) } // GetTokenMinAmountsPerExecution returns the read-only index of per-token // minimums, in key order. // // Returns: // - *rotree.ReadOnlyTree: tokenPath -> int64 func GetTokenMinAmountsPerExecution() *rotree.ReadOnlyTree { return getImplementation().GetTokenMinAmountsPerExecution() } // GetPairPriceLimit returns the price limit of selling inputToken for // outputToken (see SetPairPriceLimit). // // Parameters: // - inputToken, outputToken: the pair direction // // Returns: // - string: minOutputPerInputX128, decimal Q128; "0" when none is set // - int64: unix time the limit was set; 0 when none is set func GetPairPriceLimit(inputToken string, outputToken string) (string, int64) { limit, found := getImplementation().GetPairPriceLimit(inputToken, outputToken) if !found { return "0", 0 } return limit.MinOutputPerInputX128().ToString(), limit.UpdatedAt() } // GetPairPriceLimits returns a read-only view of the pair price limits, // in key order. Entries are copies. // // Returns: // - *rotree.ReadOnlyTree: "inputToken:outputToken" -> *pdca.PairPriceLimit func GetPairPriceLimits() *rotree.ReadOnlyTree { return getImplementation().GetPairPriceLimits() } // ================================== // Execution Fee Getters // ================================== // GetPendingExecutionFeeAmount returns the execution fee of tokenPath held // by this realm: fees payouts charged, and fees the protocol fee realm could // not accept yet. It is forwarded by the next round whose output token is // tokenPath, or by CollectPendingExecutionFee. // // 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. // A token whose pending fee was forwarded keeps its entry at 0. // // Returns: // - *rotree.ReadOnlyTree: tokenPath -> int64 pending amount func GetPendingExecutionFees() *rotree.ReadOnlyTree { return getImplementation().GetPendingExecutionFees() }
- #8gnomod.toml
- #9module = "gno.land/r/gnoswap/order/dca" gno = "0.9"
- #10proxy.gno
- #11package dca // CreateOrder creates an order that sells amountPerExecution of inputToken // for outputToken every interval seconds, executionCount times, // and returns its ID. // // The caller must first approve Address() // for amountPerExecution*executionCount. // amountPerExecution must be at least GetMinAmountPerExecution(inputToken), // and the pair direction needs a price limit (see SetPairPriceLimit). // The order snapshots the execution fee rate in effect (see // GetExecutionFeeRate) for its lifetime: the fee is that share of the order's // output, deducted when the output is paid out. Later rate changes apply only // to orders created afterwards. // Orders with the same inputToken, outputToken, interval, and slotOffset // share one group and execute together. Each round trades on the pair's // best whitelisted pool, chosen at execution time (see GetExecutionQuote). // // The caller also pays the storage deposit of the order's execution logs, // one per three rounds; each is refunded to whoever releases it after all of // its rounds execute (see ClaimGroupOrders). // // Parameters: // - inputToken, outputToken: at least one whitelisted direct pool must // connect them (see gno.land/r/gnoswap/order/whitelist.AddWhitelistedPool). // - interval: one of GetConfig().AllowedIntervals(). // - slotOffset: seconds after each interval boundary of the unix epoch at // which rounds run, a multiple of GetConfig().SlotStep(interval) // in [0, interval). Boundaries are UTC midnights for daily intervals; // weekly boundaries fall on Thursdays 00:00 UTC (1970-01-01 was one), // so a Monday slot is 4 days. // The first round waits for the next slot, or runs now if it is due. // // Reverts while the execute operation is halted for DCA // in gno.land/r/gnoswap/order/halt. func CreateOrder( cur realm, inputToken string, outputToken string, interval int64, slotOffset int64, amountPerExecution int64, executionCount int64, ) uint64 { return getImplementation().CreateOrder(0, cur, inputToken, outputToken, interval, slotOffset, amountPerExecution, executionCount) } // CancelOrder pays accrued output, refunds unsold input, and closes the order. // It returns the refunded input and the output paid by this call. // // Owner only. Reverts while the withdraw operation is halted. func CancelOrder(cur realm, orderID uint64) (int64, int64) { return getImplementation().CancelOrder(0, cur, orderID) } // Claim pays accrued output to the order owner and returns the amount. // Anyone may call it, e.g. a keeper delivering output; // proceeds always go to the owner. // The order's execution logs whose rounds all executed are released, // and their storage deposit is refunded to the caller. // // Reverts while the withdraw operation is halted. func Claim(cur realm, orderID uint64) int64 { return getImplementation().Claim(0, cur, orderID) } // ExecuteGroup runs the next round of a group once it is due. // Only accounts holding the DCA keeper role in gno.land/r/gnoswap/order/keeper // may call it: the ExecuteGroup selector is assigned to DCAKeeperRole at // deployment, and admin or governance grants the role or reassigns it. // It returns the round input and the output credited to the orders, // before their execution fees, which each order pays when paid out. // // Parameters: // - groupID: see GetExecutableGroups. // - amountOutMin: minimum pool output, before the execution fee; // 0 disables it. // - expectedAmountIn: the group orderAmount amountOutMin was quoted for. // The round reverts if the orderAmount differs; // 0 is accepted only with amountOutMin 0. // - minOrderAmountOut: the least output every order of the round must be // credited after its own execution fee rate // (see GetExecutionQuote), in the output token's smallest unit; 0 means 1. // The round reverts when its smallest order would receive less. // // Pool selection: among the pair's whitelisted pools (one per fee tier), // the pool with the best quote for the full round is used. // The round swaps on that pool directly through gno.land/r/gnoswap/pool, // without the router, so no router fee is charged. // The swap's price limit comes from the pair price limit // (see SetPairPriceLimit), so no unit of input is sold below it, // whatever amountOutMin is. // The round reverts when no whitelisted pool can fill it within the limit. // // Reverts while the execute or withdraw operation is halted. func ExecuteGroup(cur realm, groupID string, expectedAmountIn int64, amountOutMin int64, minOrderAmountOut int64) (int64, int64) { return getImplementation().ExecuteGroup(0, cur, groupID, expectedAmountIn, amountOutMin, minOrderAmountOut) } // ClaimGroupOrders pays accrued output to the owners of a group's active // orders, as Claim does, so owners receive output without claiming. // Anyone may call it; output always goes to the order owner. // // One call examines at most min(maxOrderCount, maxClaimBatchSize) orders // after startAfterOrderID, in ID order. It returns the number of orders paid // or completed and the cursor for the next call; repeat until the cursor is 0. // // Each order's execution logs whose rounds all executed are released and finished // orders are deleted; the freed storage deposit is refunded to the caller, // so the reward grows with the orders and rounds claimed. // // Reverts while the withdraw operation is halted. func ClaimGroupOrders(cur realm, groupID string, startAfterOrderID uint64, maxOrderCount int) (int, uint64) { return getImplementation().ClaimGroupOrders(0, cur, groupID, startAfterOrderID, maxOrderCount) } // ForceCancelOrder closes an order that blocks its group's rounds. As with // CancelOrder, accrued output and unsold input go to the order owner; the // caller receives nothing but the freed storage deposit of the order's // execution logs. It returns the refunded input and the output paid. // // The order must have rounds left and be, as checked on-chain: // - below the minimum per execution a new order of its token needs now // (reason below_min_amount), or // - in a due round that, as quoted now, credits it less than one output // unit after its execution fee (no_order_output), or // - the largest order (by amountPerExecution, ties included) of a due round // that no pool can fill as quoted now while a pool fills part of it, // with some output, within the price limit (exceeds_pool_capacity). A round that needs // several orders gone is shrunk one largest order per call. // // Any other order reverts with "order does not block its group". // DCAOrderForceCancelled reports the reason. // // Only accounts holding the role assigned to the ForceCancelOrder selector in // gno.land/r/gnoswap/order/keeper (DCAKeeperRole at deployment). // Reverts while the withdraw operation is halted. func ForceCancelOrder(cur realm, orderID uint64) (int64, int64) { return getImplementation().ForceCancelOrder(0, cur, orderID) } // CollectPendingExecutionFee forwards the execution fee pending for // tokenPath (see GetPendingExecutionFeeAmount) to the protocol fee realm and // returns the amount forwarded and the amount left pending. // Payouts keep each order's execution fee as pending, and every round // forwards the pending fee of its output token; this forwards it when no // round of that output token runs. If the protocol fee realm rejects it, // for example while its collection is halted, the fee stays pending. // Anyone may call it: the fee only moves to the protocol fee realm. // // Reverts while the withdraw operation is halted. func CollectPendingExecutionFee(cur realm, tokenPath string) (int64, int64) { return getImplementation().CollectPendingExecutionFee(0, cur, tokenPath) } // SetExecutionFeeRate sets the share of an order's output, // in basis points (0 to 1000, at most 10%), // sent to the protocol fee realm. // Orders created afterwards snapshot it; existing orders keep their rate. // // Admin or governance only. func SetExecutionFeeRate(cur realm, executionFeeRate int64) { getImplementation().SetExecutionFeeRate(0, cur, executionFeeRate) } // SetOrderLimits sets the minimum input per execution // and the maximum executions per order. Admin or governance only. func SetOrderLimits(cur realm, minAmountPerExecution int64, maxExecutionCount int64) { getImplementation().SetOrderLimits(0, cur, minAmountPerExecution, maxExecutionCount) } // AddAllowedInterval allows new orders to use interval, in seconds // (one minute to one year). The interval starts with a single slot, // offset 0 (see SetSlotStep). Admin or governance only. func AddAllowedInterval(cur realm, interval int64) { getImplementation().AddAllowedInterval(0, cur, interval) } // RemoveAllowedInterval stops new orders from using interval. // Existing orders and groups of that interval keep running until they finish; // its slot step is dropped, and re-adding it starts from a single slot. // At least one interval must stay allowed. Admin or governance only. func RemoveAllowedInterval(cur realm, interval int64) { getImplementation().RemoveAllowedInterval(0, cur, interval) } // SetMinExecutionGapRate sets the minimum gap between two executions of a // group, in basis points of its interval (0 to 10000), so a late execution is // not followed right away by the next one. Admin or governance only. func SetMinExecutionGapRate(cur realm, minExecutionGapRate int64) { getImplementation().SetMinExecutionGapRate(0, cur, minExecutionGapRate) } // SetMaxClaimBatchSize caps the orders one ClaimGroupOrders call examines, // bounding its gas. Admin or governance only. func SetMaxClaimBatchSize(cur realm, maxClaimBatchSize int64) { getImplementation().SetMaxClaimBatchSize(0, cur, maxClaimBatchSize) } // SetMaxPoolPriceDeviationRate sets how far, in basis points of price, a // pool's price may sit on the favorable side of its swap price limit (see // SetPairPriceLimit) and still be quoted, 0 to 10000; 0 disables the check. // A pool further away is ineligible without a quote: its quote or swap would // walk every tick between its price and the limit, which an empty or // manipulated pool far from the oracle price makes unbounded. // v0 starts at 2000 (20%). Admin or governance only. func SetMaxPoolPriceDeviationRate(cur realm, maxPoolPriceDeviationRate int64) { getImplementation().SetMaxPoolPriceDeviationRate(0, cur, maxPoolPriceDeviationRate) } // SetMaxPairPriceLimitAge sets how long, in seconds, a pair price limit stays // usable after the pool manager set it (see SetPairPriceLimit), 60 to 604800. // Under an older limit every pool is ineligible (code price_limit_stale), so // rounds stop until the limit is refreshed instead of trading at a stale price. // v0 starts at 3600 (one hour). Admin or governance only. func SetMaxPairPriceLimitAge(cur realm, maxPairPriceLimitAge int64) { getImplementation().SetMaxPairPriceLimitAge(0, cur, maxPairPriceLimitAge) } // SetSlotStep sets the spacing, in seconds, of the slot offsets new orders // may use at interval: slotStep must divide the interval, and the interval // then has interval/slotStep slots. slotStep == interval allows offset 0 only. // // Existing groups keep their slot, even one the new step no longer allows; // only new orders are checked. Finer steps split each pair's orders into // more groups, so each round sells less in more swaps. // // Admin or governance only. func SetSlotStep(cur realm, interval int64, slotStep int64) { getImplementation().SetSlotStep(0, cur, interval, slotStep) } // SetTokenMinAmountPerExecution sets the minimum input per execution of new // orders selling tokenPath, in raw token units, applied on top of the global // minimum (see SetOrderLimits); 0 removes it. // The pool manager derives it from an oracle price, so every order is worth a // set value per round whatever the token's decimals. // Existing orders are unaffected. // // Admin, governance, or accounts holding the role assigned to the // SetTokenMinAmountPerExecution selector in gno.land/r/gnoswap/order/keeper // (PoolManagerRole at deployment). func SetTokenMinAmountPerExecution(cur realm, tokenPath string, minAmountPerExecution int64) { getImplementation().SetTokenMinAmountPerExecution(0, cur, tokenPath, minAmountPerExecution) } // SetPairPriceLimit sets the least pool output, before the execution fee, // that rounds selling inputToken for outputToken accept per unit of input: // minOutputPerInputX128 is raw outputToken units per raw inputToken unit, // in Q128 fixed point, as a decimal string. "0" removes the limit. // // Every quote and round of the pair direction passes the limit to the pool // as its swap price limit, adjusted for the pool's fee tier, so each unit of // input fills at a rate of at least the limit and a swap crosses only the // ticks up to it. A pool whose price is past the limit is skipped, and a // round that cannot be filled within it reverts. // A pair direction without a limit cannot be quoted, executed, // or receive new orders. // The limit applies from the next quote or round, to existing orders too. // Its update time is recorded but not checked on-chain. // // Admin, governance, or accounts holding the role assigned to the // SetPairPriceLimit selector in gno.land/r/gnoswap/order/keeper // (PoolManagerRole at deployment). func SetPairPriceLimit(cur realm, inputToken string, outputToken string, minOutputPerInputX128 string) { getImplementation().SetPairPriceLimit(0, cur, inputToken, outputToken, minOutputPerInputX128) }
- #12state.gno
- #13package dca import ( _ "gno.land/r/gnoswap/rbac/v1" // registers the roles read through access "errors" pdca "gno.land/p/gnoswap/order/dca/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 pdca.IDCAOrder ) func init(cur realm) { currentAddress = cur.Address() kvStore = store.NewKVStore(currentAddress) versionManager = version_manager.NewVersionManager( cur.PkgPath(), kvStore, initializeDomainStore, ) implementation = nil } func initializeDomainStore(_ int, rlm realm, kvStore store.KVStore) any { return NewDCAOrderStore(kvStore) } // Address returns the realm address that escrows order funds. // Users approve it before CreateOrder. func Address() address { return currentAddress } func getImplementation() pdca.IDCAOrder { if implementation == nil { panic(errImplNotInitialized) } return implementation } func updateImplementation() error { result := versionManager.GetCurrentImplementation() if result == nil { return errors.New(errImplNotInitialized) } impl, ok := result.(pdca.IDCAOrder) if !ok { return errors.New(errInvalidImpl) } implementation = impl return nil }
- #14store.gno
- #15package dca import ( "errors" pdca "gno.land/p/gnoswap/order/dca/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/dca 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 DCA KV store. type StoreKey string func (s StoreKey) String() string { return string(s) } // Store layout. Tree keys are built by the pdca key helpers. // // orders OrderKey -> *Order // ordersByOwner OwnerOrderKey -> orderID // groups groupID -> *Group // scheduledGroups ScheduleKey -> groupID, groups with orderAmount > 0 only // nextOrderID uint64 // config *Config // executing true while ExecuteGroup is inside its pool swap // ordersByGroup GroupOrderKey -> orderID, active orders only // pendingExecutionFees tokenPath -> int64, fees not yet sent to protocol_fee // executionLogs ExecutionLogKey -> lastRound uint64, unreleased logs of active orders // orderAmountsByGroup GroupOrderAmountKey -> endRound, orders by executionFeeRate, then amountPerExecution // tokenMinAmountsPerExecution tokenPath -> int64, per-token minimum input per execution // pairPriceLimits PairKey -> *PairPriceLimit, minimum pool output per input of a pair direction const ( StoreKeyOrders StoreKey = "orders" StoreKeyOrdersByOwner StoreKey = "ordersByOwner" StoreKeyGroups StoreKey = "groups" StoreKeyScheduledGroups StoreKey = "scheduledGroups" StoreKeyNextOrderID StoreKey = "nextOrderID" StoreKeyConfig StoreKey = "config" StoreKeyExecuting StoreKey = "executing" StoreKeyOrdersByGroup StoreKey = "ordersByGroup" StoreKeyPendingExecutionFees StoreKey = "pendingExecutionFees" StoreKeyExecutionLogs StoreKey = "executionLogs" StoreKeyOrderAmountsByGroup StoreKey = "orderAmountsByGroup" StoreKeyTokenMinAmountsPerExecution StoreKey = "tokenMinAmountsPerExecution" StoreKeyPairPriceLimits StoreKey = "pairPriceLimits" ) type dcaOrderStore struct { kvStore store.KVStore } // NewDCAOrderStore wraps the domain KV store. func NewDCAOrderStore(kvStore store.KVStore) pdca.IDCAOrderStore { return &dcaOrderStore{kvStore: kvStore} } func (s *dcaOrderStore) 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 *dcaOrderStore) 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 *dcaOrderStore) HasOrders() bool { return s.kvStore.Has(StoreKeyOrders.String()) } func (s *dcaOrderStore) GetOrders() *bptree.BPTree { return s.getTree(StoreKeyOrders) } func (s *dcaOrderStore) SetOrders(_ int, rlm realm, orders *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyOrders, orders) } func (s *dcaOrderStore) HasOrdersByOwner() bool { return s.kvStore.Has(StoreKeyOrdersByOwner.String()) } func (s *dcaOrderStore) GetOrdersByOwner() *bptree.BPTree { return s.getTree(StoreKeyOrdersByOwner) } func (s *dcaOrderStore) SetOrdersByOwner(_ int, rlm realm, ordersByOwner *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyOrdersByOwner, ordersByOwner) } func (s *dcaOrderStore) HasOrdersByGroup() bool { return s.kvStore.Has(StoreKeyOrdersByGroup.String()) } func (s *dcaOrderStore) GetOrdersByGroup() *bptree.BPTree { return s.getTree(StoreKeyOrdersByGroup) } func (s *dcaOrderStore) SetOrdersByGroup(_ int, rlm realm, ordersByGroup *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyOrdersByGroup, ordersByGroup) } func (s *dcaOrderStore) HasGroups() bool { return s.kvStore.Has(StoreKeyGroups.String()) } func (s *dcaOrderStore) GetGroups() *bptree.BPTree { return s.getTree(StoreKeyGroups) } func (s *dcaOrderStore) SetGroups(_ int, rlm realm, groups *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyGroups, groups) } func (s *dcaOrderStore) HasScheduledGroups() bool { return s.kvStore.Has(StoreKeyScheduledGroups.String()) } func (s *dcaOrderStore) GetScheduledGroups() *bptree.BPTree { return s.getTree(StoreKeyScheduledGroups) } func (s *dcaOrderStore) SetScheduledGroups(_ int, rlm realm, groups *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyScheduledGroups, groups) } func (s *dcaOrderStore) HasNextOrderID() bool { return s.kvStore.Has(StoreKeyNextOrderID.String()) } func (s *dcaOrderStore) GetNextOrderID() uint64 { id, err := s.kvStore.GetUint64(StoreKeyNextOrderID.String()) if err != nil { panic(err.Error()) } return id } func (s *dcaOrderStore) SetNextOrderID(_ int, rlm realm, id uint64) error { if !rlm.IsCurrent() { return errors.New(ErrSpoofedRealm) } return s.kvStore.Set(0, rlm, StoreKeyNextOrderID.String(), id) } func (s *dcaOrderStore) HasConfig() bool { return s.kvStore.Has(StoreKeyConfig.String()) } func (s *dcaOrderStore) GetConfig() *pdca.Config { result, err := s.kvStore.Get(StoreKeyConfig.String()) if err != nil { panic(err.Error()) } config, ok := result.(*pdca.Config) if !ok || config == nil { panic(ufmt.Sprintf(errInvalidConfigType, result)) } return config } func (s *dcaOrderStore) SetConfig(_ int, rlm realm, config *pdca.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) } // IsExecuting reports whether a group execution is inside its swap. // The flag is in the proxy store, // so every version and UpgradeImpl share the same re-entrancy guard. func (s *dcaOrderStore) IsExecuting() bool { if !s.kvStore.Has(StoreKeyExecuting.String()) { return false } executing, err := s.kvStore.GetBool(StoreKeyExecuting.String()) if err != nil { panic(err.Error()) } return executing } func (s *dcaOrderStore) SetExecuting(_ int, rlm realm, executing bool) error { if !rlm.IsCurrent() { return errors.New(ErrSpoofedRealm) } return s.kvStore.Set(0, rlm, StoreKeyExecuting.String(), executing) } func (s *dcaOrderStore) HasPendingExecutionFees() bool { return s.kvStore.Has(StoreKeyPendingExecutionFees.String()) } func (s *dcaOrderStore) GetPendingExecutionFees() *bptree.BPTree { return s.getTree(StoreKeyPendingExecutionFees) } func (s *dcaOrderStore) SetPendingExecutionFees(_ int, rlm realm, pendingExecutionFees *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyPendingExecutionFees, pendingExecutionFees) } func (s *dcaOrderStore) HasExecutionLogs() bool { return s.kvStore.Has(StoreKeyExecutionLogs.String()) } func (s *dcaOrderStore) GetExecutionLogs() *bptree.BPTree { return s.getTree(StoreKeyExecutionLogs) } func (s *dcaOrderStore) SetExecutionLogs(_ int, rlm realm, executionLogs *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyExecutionLogs, executionLogs) } func (s *dcaOrderStore) HasOrderAmountsByGroup() bool { return s.kvStore.Has(StoreKeyOrderAmountsByGroup.String()) } func (s *dcaOrderStore) GetOrderAmountsByGroup() *bptree.BPTree { return s.getTree(StoreKeyOrderAmountsByGroup) } func (s *dcaOrderStore) SetOrderAmountsByGroup(_ int, rlm realm, orderAmountsByGroup *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyOrderAmountsByGroup, orderAmountsByGroup) } func (s *dcaOrderStore) HasTokenMinAmountsPerExecution() bool { return s.kvStore.Has(StoreKeyTokenMinAmountsPerExecution.String()) } func (s *dcaOrderStore) GetTokenMinAmountsPerExecution() *bptree.BPTree { return s.getTree(StoreKeyTokenMinAmountsPerExecution) } func (s *dcaOrderStore) SetTokenMinAmountsPerExecution(_ int, rlm realm, tokenMinAmounts *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyTokenMinAmountsPerExecution, tokenMinAmounts) } func (s *dcaOrderStore) HasPairPriceLimits() bool { return s.kvStore.Has(StoreKeyPairPriceLimits.String()) } func (s *dcaOrderStore) GetPairPriceLimits() *bptree.BPTree { return s.getTree(StoreKeyPairPriceLimits) } func (s *dcaOrderStore) SetPairPriceLimits(_ int, rlm realm, pairPriceLimits *bptree.BPTree) error { return s.setTree(0, rlm, StoreKeyPairPriceLimits, pairPriceLimits) }
- #16swap_callback.gno
- #17package dca import ( prbac "gno.land/p/gnoswap/rbac/v1" ufmt "gno.land/p/nt/ufmt/v0" "gno.land/r/gnoswap/access/v1" "gno.land/r/gnoswap/common" "gno.land/r/gnoswap/pool" ) // NewSwapCallback returns the callback of one round's pool.Swap. It pays the // pool the round input, at most maxAmountIn of tokenIn, from the escrow. // // The callback is declared in this realm, so it transfers as the escrow // itself: the escrow never grants an allowance for a swap. That makes the // callback a payment capability, so it is guarded on creation and on use: // // - only the escrow's own current realm can create one, so only code the // proxy hands its realm to (the active implementation) can; // - only the pool can invoke it (cur.Previous()); the pool's swap lock // admits no other swap while a round's swap runs; // - it pays only while a round is executing, once, and only an exact-input // delta of the sold token: positive input, no positive output, at most // maxAmountIn. // // zeroForOne is the swap direction: it selects which pool delta is tokenIn. func NewSwapCallback(_ int, rlm realm, tokenIn string, zeroForOne bool, maxAmountIn int64) func(cur realm, amount0Delta, amount1Delta int64, _ *pool.CallbackMarker) error { if !rlm.IsCurrent() || rlm.Address() != Address() { panic(ErrSpoofedRealm) } if maxAmountIn <= 0 { panic(makeErrorWithDetails(ErrInvalidSwapCallback, ufmt.Sprintf("maxAmountIn(%d)", maxAmountIn)).Error()) } poolAddress := access.MustGetAddress(prbac.ROLE_POOL.String()) paid := false // The marker is not checked: pool.NewCallbackMarker is public, so it // proves nothing about the caller. The caller check below does. return func(cur realm, amount0Delta, amount1Delta int64, _ *pool.CallbackMarker) error { if cur.Previous().Address() != poolAddress { return makeErrorWithDetails(ErrInvalidSwapCallback, "caller is not the pool") } if paid || !NewDCAOrderStore(kvStore).IsExecuting() { return makeErrorWithDetails(ErrInvalidSwapCallback, "no round swap awaits payment") } input, output := amount0Delta, amount1Delta if !zeroForOne { input, output = amount1Delta, amount0Delta } if input <= 0 || output > 0 || input > maxAmountIn { return makeErrorWithDetails( ErrInvalidSwapCallback, ufmt.Sprintf("input(%d) output(%d) maxAmountIn(%d)", input, output, maxAmountIn), ) } paid = true return common.Transfer(0, cur, tokenIn, poolAddress, input) } }
- #18upgrade.gno
- #19package dca import ( pdca "gno.land/p/gnoswap/order/dca/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 here, // instead of panicking later when the version is activated. func RegisterInitializer(cur realm, initializer func(_ int, rlm realm, dcaStore pdca.IDCAOrderStore) pdca.IDCAOrder) { if initializer == nil { panic(ErrNilInitializer) } initializerFunc := func(_ int, rlm realm, domainStore any) any { access.AssertIsRlmCurrent(0, rlm) currentStore, ok := domainStore.(pdca.IDCAOrderStore) if !ok { panic(errInvalidDomainStore) } return initializer(0, rlm, currentStore) } 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) // The running version still writes the accumulator after its swap, // so never switch during a round. if NewDCAOrderStore(kvStore).IsExecuting() { panic(ErrUpgradeWhileExecuting) } 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:[]