Transaction
DC7952457C42CD…5E6A7EECA73F
Block 1,651,934 · index 0 · indexed
Summary
- Hash
- DC7952457C42CDF914E94503BF8B7EFF7D3A7EB366AC9C2438FA5E6A7EECA73F
- Block
- 1,651,934
- Size
- 129157 bytes
- Gas used
- 170,154,287 / 204,185,085
- Fee
- 204186 ugnot
- Status
- success
Messages
Arguments · 24
- #1impl
- #2assert.gno
- #3package impl import ( "gno.land/p/gnoswap/order/access/manager/v1" pdca "gno.land/p/gnoswap/order/dca/v1" prbac "gno.land/p/gnoswap/rbac/v1" bptree "gno.land/p/nt/bptree/v0" ufmt "gno.land/p/nt/ufmt/v0" "gno.land/r/gnoswap/access/v1" "gno.land/r/gnoswap/common" "gno.land/r/gnoswap/order/halt" "gno.land/r/gnoswap/order/keeper" "gno.land/r/gnoswap/order/whitelist" ) // assertIsAdminCall runs the checks shared by admin entry points // and returns the calling realm. func (d *dcaOrderImpl) assertIsAdminCall(_ int, rlm realm) realm { access.AssertIsRlmCurrent(0, rlm) common.AssertIsNotHandleNativeCoin() d.assertIsNotExecuting() prev := rlm.Previous() access.AssertIsAdminOrGovernance(prev.Address()) return prev } // assertIsNotExecuting rejects re-entry from the swap // into any state-changing entry point. func (d *dcaOrderImpl) assertIsNotExecuting() { if d.store.IsExecuting() { panic(makeErrorWithDetails(errReentrant, "group execution in progress").Error()) } } // assertIsNotHalted rejects the call while any of operations is halted // for DCA orders in gno.land/r/gnoswap/order/halt. func assertIsNotHalted(operations ...string) { if operation, halted := haltedOperation(operations...); halted { panic(makeErrorWithDetails(errHalted, ufmt.Sprintf("operation(%s)", operation)).Error()) } } // haltedOperation returns the first of operations halted for DCA orders. func haltedOperation(operations ...string) (string, bool) { for _, operation := range operations { if halt.IsHalted(halt.TargetDCA, operation) { return operation, true } } return "", false } // assertIsAuthorizedKeeper rejects callers that gno.land/r/gnoswap/order/keeper // does not allow to run rounds on target, the DCA proxy package path. // ExecuteGroup is assigned to DCAKeeperRole at deployment; admin or // governance grants it to keepers or reassigns the selector. func assertIsAuthorizedKeeper(target string, caller address) { if !keeper.IsAuthorized(target, keeper.SelectorExecuteGroup, caller) { panic(makeErrorWithDetails(errNotKeeper, ufmt.Sprintf("caller(%s)", caller.String())).Error()) } } // assertIsManagerCall runs the checks shared by the manager entry points // (token minimums and pair price limits) and returns the calling realm. // Admin and governance may always call them; other callers need the // PoolManagerRole that gno.land/r/gnoswap/order/keeper assigns on the DCA // proxy package path. func (d *dcaOrderImpl) assertIsManagerCall(_ int, rlm realm, selector manager.Selector) realm { access.AssertIsRlmCurrent(0, rlm) common.AssertIsNotHandleNativeCoin() d.assertIsNotExecuting() prev := rlm.Previous() caller := prev.Address() if isAdminOrGovernance(caller) || keeper.IsAuthorized(rlm.PkgPath(), selector, caller) { return prev } panic(makeErrorWithDetails(errNotKeeper, ufmt.Sprintf("caller(%s) selector(%s)", caller.String(), string(selector))).Error()) } // isAdminOrGovernance reports whether caller is the GnoSwap admin or governance. func isAdminOrGovernance(caller address) bool { return access.IsAuthorized(prbac.ROLE_ADMIN.String(), caller) || access.IsAuthorized(prbac.ROLE_GOVERNANCE.String(), caller) } // assertIsValidPair checks that inputToken and outputToken differ // and that at least one whitelisted direct pool connects them. func assertIsValidPair(inputToken string, outputToken string) { if inputToken == outputToken { panic(makeErrorWithDetails(errInvalidToken, ufmt.Sprintf("inputToken and outputToken are both %s", inputToken)).Error()) } if !whitelist.HasWhitelistedPool(whitelist.TargetDCA, inputToken, outputToken) { panic(makeErrorWithDetails(errInvalidPool, ufmt.Sprintf("no whitelisted pool for %s -> %s", inputToken, outputToken)).Error()) } } // assertHasPairPriceLimit checks that the pair direction has a price limit, // without which its rounds cannot trade. func assertHasPairPriceLimit(pairPriceLimits *bptree.BPTree, inputToken string, outputToken string) { if getPairPriceLimit(pairPriceLimits, inputToken, outputToken) == nil { panic(makeErrorWithDetails(errMissingPriceLimit, ufmt.Sprintf("no price limit for %s -> %s", inputToken, outputToken)).Error()) } } // assertIsAllowedInterval checks that new orders may use interval. func assertIsAllowedInterval(config *pdca.Config, interval int64) { if !config.IsAllowedInterval(interval) { panic(makeErrorWithDetails(errInvalidInterval, ufmt.Sprintf("interval(%d)", interval)).Error()) } } // assertIsAllowedSlot checks that new orders may use slotOffset at interval. func assertIsAllowedSlot(config *pdca.Config, interval int64, slotOffset int64) { if !config.IsAllowedSlot(interval, slotOffset) { panic(makeErrorWithDetails( errInvalidSlotOffset, ufmt.Sprintf("slotOffset(%d) must be a multiple of %d in [0, %d)", slotOffset, config.SlotStep(interval), interval), ).Error()) } } // assertIsValidOrderSize checks the order against the configured limits; // minAmountPerExecution is the effective minimum of the input token // (see minAmountPerExecution). func assertIsValidOrderSize(config *pdca.Config, minAmountPerExecution int64, amountPerExecution int64, executionCount int64) { if amountPerExecution < minAmountPerExecution { panic(makeErrorWithDetails( errInvalidAmount, ufmt.Sprintf("amountPerExecution(%d) must be >= %d", amountPerExecution, minAmountPerExecution), ).Error()) } if executionCount <= 0 || executionCount > config.MaxExecutionCount() { panic(makeErrorWithDetails( errInvalidExecutionCount, ufmt.Sprintf("executionCount(%d) must be in [1, %d]", executionCount, config.MaxExecutionCount()), ).Error()) } } // assertIsOrderOwner checks that caller owns the order. func assertIsOrderOwner(order *pdca.Order, caller address) { if order.Owner() != caller { panic(makeErrorWithDetails(errNotOrderOwner, ufmt.Sprintf("orderId(%d)", order.ID())).Error()) } } // assertIsQuotedAmountIn checks that the round sells the input // amountOutMin was quoted for. // A floor quoted for a larger input would keep that trade's price impact, // which is looser than the smaller round needs, so a changed orderAmount // needs a new quote instead of a rescaled floor. // Passing 0 for both skips the check. func assertIsQuotedAmountIn(group *pdca.Group, expectedAmountIn int64, amountOutMin int64) { if expectedAmountIn == 0 && amountOutMin == 0 { return } if expectedAmountIn != group.OrderAmount() { panic(makeErrorWithDetails( errAmountInMismatch, ufmt.Sprintf("groupId(%s) expectedAmountIn(%d) orderAmount(%d)", group.ID(), expectedAmountIn, group.OrderAmount()), ).Error()) } }
- #4claim_group_orders.gno
- #5package impl import ( "gno.land/p/gnoswap/gnsmath/v1" pdca "gno.land/p/gnoswap/order/dca/v1" ufmt "gno.land/p/nt/ufmt/v0" "gno.land/r/gnoswap/access/v1" "gno.land/r/gnoswap/common" "gno.land/r/gnoswap/order/halt" ) // ClaimGroupOrders pays accrued output to the owners of a group's active // orders, like Claim, so owners receive output without claiming. // Anyone may call it; output always goes to the order owner. // // The call releases each examined order's execution logs whose rounds all executed // and deletes finished orders. The freed storage deposit is refunded to the // caller, a fixed reward per log of three executed rounds. // // One call examines at most min(maxOrderCount, maxClaimBatchSize) orders // after startAfterOrderID, in ID order, so its gas stays bounded. // The returned cursor is the last examined order ID; pass it back until it // is 0. New orders get higher IDs and finished orders leave the index, // so changes between calls neither skip nor repeat an order. func (d *dcaOrderImpl) ClaimGroupOrders(_ int, rlm realm, groupID string, startAfterOrderID uint64, maxOrderCount int) (int, uint64) { access.AssertIsRlmCurrent(0, rlm) common.AssertIsNotHandleNativeCoin() assertIsNotHalted(halt.OperationWithdraw) d.assertIsNotExecuting() if maxOrderCount <= 0 { panic(makeErrorWithDetails(errInvalidAmount, ufmt.Sprintf("maxOrderCount(%d) must be positive", maxOrderCount)).Error()) } group, err := d.getGroup(groupID) if err != nil { panic(err.Error()) } prev := rlm.Previous() result, err := d.claimGroupOrders(0, rlm, prev.Address(), prev.PkgPath(), group, startAfterOrderID, maxOrderCount) if err != nil { panic(err.Error()) } emitGroupOrdersClaimed( prev.Address(), prev.PkgPath(), groupID, result.examinedOrderCount, result.claimedOrderCount, result.releasedExecutionLogCount, result.nextCursor, ) emitPayoutExecutionFee(prev.Address(), prev.PkgPath(), group, result.executionFeeAmount, d.pendingExecutionFeeAmount(group.OutputToken())) return result.claimedOrderCount, result.nextCursor } // groupOrdersClaimResult describes one page of claimGroupOrders. type groupOrdersClaimResult struct { examinedOrderCount int claimedOrderCount int // orders paid or completed releasedExecutionLogCount int64 // order logs freed for the caller executionFeeAmount int64 // execution fee the payouts kept as pending nextCursor uint64 // last examined order ID, 0 when the group is done } // claimGroupOrders claims one page of the group's orders. func (d *dcaOrderImpl) claimGroupOrders( _ int, rlm realm, prevAddr address, prevRealm string, group *pdca.Group, startAfterOrderID uint64, maxOrderCount int, ) (groupOrdersClaimResult, error) { limit := int64(maxOrderCount) if maxClaimBatchSize := d.store.GetConfig().MaxClaimBatchSize(); limit > maxClaimBatchSize { limit = maxClaimBatchSize } orderIDs, hasMore := d.getGroupOrderIDs(group.ID(), startAfterOrderID, int(limit)) result := groupOrdersClaimResult{examinedOrderCount: len(orderIDs)} for _, orderID := range orderIDs { order, err := d.getOrder(orderID) if err != nil { return groupOrdersClaimResult{}, err } payout, releasedCount, isUpdated, err := d.claimOrder(0, rlm, prevAddr, prevRealm, order, group) if err != nil { return groupOrdersClaimResult{}, err } result.executionFeeAmount = gnsmath.SafeAddInt64(result.executionFeeAmount, payout.executionFeeAmount) result.releasedExecutionLogCount = gnsmath.SafeAddInt64(result.releasedExecutionLogCount, releasedCount) if isUpdated { result.claimedOrderCount++ } } if hasMore { result.nextCursor = orderIDs[len(orderIDs)-1] } return result, nil } // getGroupOrderIDs returns up to count active order IDs of a group after // startAfterID, and whether more remain. IDs are collected before any // order is claimed, since a claim may remove entries from the index. func (d *dcaOrderImpl) getGroupOrderIDs(groupID string, startAfterID uint64, count int) ([]uint64, bool) { if startAfterID == ^uint64(0) { return nil, false } prefix := pdca.GroupOrderPrefix(groupID) start := pdca.GroupOrderKey(groupID, gnsmath.SafeAddUint64(startAfterID, 1)) orderIDs := []uint64{} hasMore := false d.store.GetOrdersByGroup().Iterate(start, pdca.PrefixEnd(prefix), func(_ string, value any) bool { if len(orderIDs) == count { hasMore = true return true } orderIDs = append(orderIDs, value.(uint64)) return false }) return orderIDs, hasMore }
- #6config.gno
- #7package impl import ( pdca "gno.land/p/gnoswap/order/dca/v1" ufmt "gno.land/p/nt/ufmt/v0" ) // SetOrderLimits sets the minimum input per execution // and the maximum executions per order. // Existing orders are unaffected. Admin or governance only. func (d *dcaOrderImpl) SetOrderLimits(_ int, rlm realm, minAmountPerExecution int64, maxExecutionCount int64) { prev := d.assertIsAdminCall(0, rlm) if minAmountPerExecution <= 0 { panic(makeErrorWithDetails( errInvalidConfig, ufmt.Sprintf("minAmountPerExecution(%d) must be positive", minAmountPerExecution), ).Error()) } if maxExecutionCount <= 0 || maxExecutionCount > maxExecutionCountLimit { panic(makeErrorWithDetails( errInvalidConfig, ufmt.Sprintf("maxExecutionCount(%d) must be in [1, %d]", maxExecutionCount, maxExecutionCountLimit), ).Error()) } config := d.store.GetConfig() previousMinAmountPerExecution := config.MinAmountPerExecution() previousMaxExecutionCount := config.MaxExecutionCount() config.SetMinAmountPerExecution(minAmountPerExecution) config.SetMaxExecutionCount(maxExecutionCount) emitConfigUpdated(prev.Address(), prev.PkgPath(), "minAmountPerExecution", previousMinAmountPerExecution, minAmountPerExecution) emitConfigUpdated(prev.Address(), prev.PkgPath(), "maxExecutionCount", previousMaxExecutionCount, maxExecutionCount) } // AddAllowedInterval allows new orders to use interval. // Admin or governance only. func (d *dcaOrderImpl) AddAllowedInterval(_ int, rlm realm, interval int64) { prev := d.assertIsAdminCall(0, rlm) if interval < minAllowedInterval || interval > maxAllowedInterval { panic(makeErrorWithDetails( errInvalidInterval, ufmt.Sprintf("interval(%d) must be in [%d, %d]", interval, minAllowedInterval, maxAllowedInterval), ).Error()) } if err := d.store.GetConfig().AddAllowedInterval(interval); err != nil { panic(makeErrorWithDetails(errInvalidInterval, ufmt.Sprintf("interval(%d): %s", interval, err.Error())).Error()) } emitAllowedIntervalUpdated(prev.Address(), prev.PkgPath(), interval, true) } // RemoveAllowedInterval stops new orders from using interval. // Existing orders and groups of that interval keep running. // At least one interval must stay allowed. Admin or governance only. func (d *dcaOrderImpl) RemoveAllowedInterval(_ int, rlm realm, interval int64) { prev := d.assertIsAdminCall(0, rlm) config := d.store.GetConfig() if len(config.AllowedIntervals()) == 1 && config.IsAllowedInterval(interval) { panic(makeErrorWithDetails(errInvalidConfig, "at least one interval must stay allowed").Error()) } if err := config.RemoveAllowedInterval(interval); err != nil { panic(makeErrorWithDetails(errInvalidInterval, ufmt.Sprintf("interval(%d): %s", interval, err.Error())).Error()) } emitAllowedIntervalUpdated(prev.Address(), prev.PkgPath(), interval, false) } // SetMinExecutionGapRate sets the minimum gap between a group's executions, // in basis points of its interval. Admin or governance only. func (d *dcaOrderImpl) SetMinExecutionGapRate(_ int, rlm realm, minExecutionGapRate int64) { prev := d.assertIsAdminCall(0, rlm) if minExecutionGapRate < 0 || minExecutionGapRate > pdca.BasisPointDenominator { panic(makeErrorWithDetails( errInvalidConfig, ufmt.Sprintf("minExecutionGapRate(%d) must be in [0, %d]", minExecutionGapRate, pdca.BasisPointDenominator), ).Error()) } config := d.store.GetConfig() previousMinExecutionGapRate := config.MinExecutionGapRate() config.SetMinExecutionGapRate(minExecutionGapRate) emitConfigUpdated(prev.Address(), prev.PkgPath(), "minExecutionGapRate", previousMinExecutionGapRate, minExecutionGapRate) } // SetMaxPoolPriceDeviationRate sets 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 (0 to 10000; 0 disables the check). Admin or governance only. func (d *dcaOrderImpl) SetMaxPoolPriceDeviationRate(_ int, rlm realm, maxPoolPriceDeviationRate int64) { prev := d.assertIsAdminCall(0, rlm) if maxPoolPriceDeviationRate < 0 || maxPoolPriceDeviationRate > pdca.BasisPointDenominator { panic(makeErrorWithDetails( errInvalidConfig, ufmt.Sprintf("maxPoolPriceDeviationRate(%d) must be in [0, %d]", maxPoolPriceDeviationRate, pdca.BasisPointDenominator), ).Error()) } config := d.store.GetConfig() previousMaxPoolPriceDeviationRate := config.MaxPoolPriceDeviationRate() config.SetMaxPoolPriceDeviationRate(maxPoolPriceDeviationRate) emitConfigUpdated( prev.Address(), prev.PkgPath(), "maxPoolPriceDeviationRate", previousMaxPoolPriceDeviationRate, maxPoolPriceDeviationRate, ) } // SetMaxPairPriceLimitAge sets how long, in seconds, a pair price limit stays // usable after the pool manager set it (60 to 604800). A quote or round under // an older limit finds no eligible pool, so rounds stop when the manager stops // refreshing limits instead of trading at a stale price. Admin or governance only. func (d *dcaOrderImpl) SetMaxPairPriceLimitAge(_ int, rlm realm, maxPairPriceLimitAge int64) { prev := d.assertIsAdminCall(0, rlm) if maxPairPriceLimitAge < minMaxPairPriceLimitAge || maxPairPriceLimitAge > maxMaxPairPriceLimitAge { panic(makeErrorWithDetails( errInvalidConfig, ufmt.Sprintf("maxPairPriceLimitAge(%d) must be in [%d, %d]", maxPairPriceLimitAge, minMaxPairPriceLimitAge, maxMaxPairPriceLimitAge), ).Error()) } config := d.store.GetConfig() previousMaxPairPriceLimitAge := config.MaxPairPriceLimitAge() config.SetMaxPairPriceLimitAge(maxPairPriceLimitAge) emitConfigUpdated(prev.Address(), prev.PkgPath(), "maxPairPriceLimitAge", previousMaxPairPriceLimitAge, maxPairPriceLimitAge) } // SetMaxClaimBatchSize caps the orders one ClaimGroupOrders call examines. // Admin or governance only. func (d *dcaOrderImpl) SetMaxClaimBatchSize(_ int, rlm realm, maxClaimBatchSize int64) { prev := d.assertIsAdminCall(0, rlm) if maxClaimBatchSize <= 0 || maxClaimBatchSize > maxClaimBatchSizeLimit { panic(makeErrorWithDetails( errInvalidConfig, ufmt.Sprintf("maxClaimBatchSize(%d) must be in [1, %d]", maxClaimBatchSize, maxClaimBatchSizeLimit), ).Error()) } config := d.store.GetConfig() previousMaxClaimBatchSize := config.MaxClaimBatchSize() config.SetMaxClaimBatchSize(maxClaimBatchSize) emitConfigUpdated(prev.Address(), prev.PkgPath(), "maxClaimBatchSize", previousMaxClaimBatchSize, maxClaimBatchSize) } // SetSlotStep sets the spacing of the slot offsets new orders may use // at interval. Existing groups keep their slot. // Admin or governance only. func (d *dcaOrderImpl) SetSlotStep(_ int, rlm realm, interval int64, slotStep int64) { prev := d.assertIsAdminCall(0, rlm) config := d.store.GetConfig() assertIsAllowedInterval(config, interval) previousSlotStep := config.SlotStep(interval) if err := config.SetSlotStep(interval, slotStep); err != nil { panic(makeErrorWithDetails( errInvalidSlotStep, ufmt.Sprintf("slotStep(%d) must be a positive divisor of interval(%d)", slotStep, interval), ).Error()) } emitSlotStepChanged(prev.Address(), prev.PkgPath(), interval, previousSlotStep, slotStep) }
- #8consts.gno
- #9package impl const ( dcaBPTreeFanOut int = 16 // maxExecutionCountLimit bounds the configurable executions per order, // so cancelling an order releases its execution logs within one block. maxExecutionCountLimit int64 = 10_000 // Bounds of an allowed interval: one minute to one year. minAllowedInterval int64 = 60 maxAllowedInterval int64 = 365 * 24 * 60 * 60 // maxClaimBatchSizeLimit bounds the configurable ClaimGroupOrders batch. maxClaimBatchSizeLimit int64 = 500 // minOrderAmountOutFloor is the least output a round credits each of // its orders, whatever minOrderAmountOut ExecuteGroup is given. minOrderAmountOutFloor int64 = 1 defaultMinAmountPerExecution int64 = 1 defaultMaxExecutionCount int64 = 1_000 defaultMaxClaimBatchSize int64 = 50 defaultExecutionFeeRate int64 = 15 // basis points // Starting execution gap: half an interval; tune per deployment. defaultMinExecutionGapRate int64 = 5_000 // defaultMaxPoolPriceDeviationRate is the starting // Config.MaxPoolPriceDeviationRate: 20%, in basis points of price. defaultMaxPoolPriceDeviationRate int64 = 2_000 // defaultMaxPairPriceLimitAge is the starting Config.MaxPairPriceLimitAge: // one hour, in seconds. defaultMaxPairPriceLimitAge int64 = 60 * 60 // Bounds of Config.MaxPairPriceLimitAge: one minute to seven days. minMaxPairPriceLimitAge int64 = 60 maxMaxPairPriceLimitAge int64 = 7 * 24 * 60 * 60 ) // Intervals new orders may use after deployment, in seconds. // A month is a fixed 30 days, so every round in a group has the same length. const ( intervalMinute int64 = 60 intervalHour int64 = 60 * intervalMinute intervalDay int64 = 24 * intervalHour intervalWeek int64 = 7 * intervalDay intervalMonth int64 = 30 * intervalDay ) // defaultAllowedIntervals returns the initial allowed intervals, ascending. func defaultAllowedIntervals() []int64 { return []int64{intervalMinute, intervalHour, intervalDay, intervalWeek, intervalMonth} } // defaultSlotSteps returns the initial slot step of the intervals split // into several slots: daily orders pick an hour, weekly and 30-day orders // a day. A 30-day slot is a day of the 30-day cycle counted from the unix // epoch, not a calendar date. // Minute and hourly orders keep a single slot, offset 0: finer slots would // split liquidity for little gain. // Each slot is its own group, so the steps bound the groups per pair. func defaultSlotSteps() map[int64]int64 { return map[int64]int64{ intervalDay: intervalHour, intervalWeek: intervalDay, intervalMonth: intervalDay, } }
- #10doc.gno
- #11// Package impl is the v0 implementation of the GnoSwap DCA order realm. // It registers itself with gno.land/r/gnoswap/order/dca at init. // // Files: // - order.gno: CreateOrder, CancelOrder, Claim, ForceCancelOrder // - execute.gno: ExecuteGroup and the pool swap; rounds credit gross output // - execution_fee.gno: SetExecutionFeeRate, pending payout fees, and forwarding them to the protocol fee realm // - pool_selection.gno: choosing the pool of a round // - swap.gno: the pool swap of a round and its callback // - manager.gno: per-token minimum order sizes and pair price limits // - price_limit.gno: converting a pair price limit to a swap price limit // - claim_group_orders.gno: ClaimGroupOrders // - config.gno: admin configuration and slot steps // - getter.gno: read-only queries // - assert.gno, utils.gno: shared checks and helpers // // The executed amount is protected by the pair price limit the pool manager // sets from an oracle price, which every quote and swap passes to the pool as // its price limit, by the best-quote pool selection, and by the keeper's // amountOutMin, quoted for the round's input. The price limit also bounds the // ticks a quote or swap crosses, and so its gas. The execution gap keeps // a group's next execution at least minExecutionGapRate of its interval after // the previous one, even after a late execution. // A round reverts unless it credits each of its orders at least the keeper's // minOrderAmountOut, and never less than one unit, of output after its own // execution fee rate. The order amount index sorts orders by fee rate, then // amount, so the smallest order of each fee rate bounds every order of that rate. // Roles: gno.land/r/gnoswap/order/keeper restricts executions and force cancellations // to DCAKeeperRole, and the shared pool whitelist, token minimums, and price // limits to PoolManagerRole, at deployment. // // Keepers earn storage deposits: each order stores one execution log per // three rounds at creation, paid by its owner. Claim and ClaimGroupOrders // release the order's logs whose rounds all executed and delete finished // orders, which refunds the freed deposit to the transaction signer. package impl
- #12emits.gno
- #13package impl import ( "chain" pdca "gno.land/p/gnoswap/order/dca/v1" "gno.land/p/gnoswap/utils/v1" ) // Events carry the accumulator state // (accumulatedOutputPerAmountX128, round, orderAmount) and each order's // payout state, so indexers can compute claimable amounts without querying // state. The accumulator is gross of execution fees: // // gross = amountPerExecution * (acc(min(round, endRound)) - debtX128) / 2^128 // paid = totalClaimedAmount + totalExecutionFeeAmount // fee = floor((paid + gross) * executionFeeRate / 10000) - floor(paid * executionFeeRate / 10000) // claimable = gross - fee func emitGroupCreated(prevAddr address, prevRealm string, group *pdca.Group) { chain.Emit( "DCAGroupCreated", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "groupId", group.ID(), "inputToken", group.InputToken(), "outputToken", group.OutputToken(), "interval", utils.FormatInt(group.Interval()), "slotOffset", utils.FormatInt(group.SlotOffset()), "nextExecutionTimestamp", utils.FormatInt(group.NextExecutionTimestamp()), ) } // emitOrderCreated reports a new order. executionFeeRate is the rate the // order snapshotted. referenceAmountOut is the output of selling the whole // deposit at once when the order was placed, net of the order's execution // fee (see quoteReferenceAmountOut), 0 when no pool could absorb it. func emitOrderCreated( prevAddr address, prevRealm string, order *pdca.Order, group *pdca.Group, depositAmount int64, referenceAmountOut int64, ) { chain.Emit( "DCAOrderCreated", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "orderId", utils.FormatUint(order.ID()), "owner", order.Owner().String(), "groupId", order.GroupID(), "inputToken", group.InputToken(), "outputToken", group.OutputToken(), "interval", utils.FormatInt(group.Interval()), "slotOffset", utils.FormatInt(group.SlotOffset()), "amountPerExecution", utils.FormatInt(order.AmountPerExecution()), "executionCount", utils.FormatInt(order.ExecutionCount()), "executionFeeRate", utils.FormatInt(order.ExecutionFeeRate()), "depositAmount", utils.FormatInt(depositAmount), "startRound", utils.FormatUint(order.StartRound()), "endRound", utils.FormatUint(order.EndRound()), "debtX128", order.DebtX128().ToString(), "executionLogCount", utils.FormatInt(order.ExecutionLogCount()), "groupOrderAmount", utils.FormatInt(group.OrderAmount()), "groupNextExecutionTimestamp", utils.FormatInt(group.NextExecutionTimestamp()), "referenceAmountOut", utils.FormatInt(referenceAmountOut), ) } // emitGroupExecuted reports a round. executedAmountOut, the output credited // to the orders, equals swapAmountOut: orders pay their execution fees when // paid out. func emitGroupExecuted(prevAddr address, prevRealm string, group *pdca.Group, result groupRoundResult) { chain.Emit( "DCAGroupExecuted", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "groupId", group.ID(), "poolPath", result.poolPath, "inputToken", group.InputToken(), "outputToken", group.OutputToken(), "round", utils.FormatUint(group.Round()), "executedAmountIn", utils.FormatInt(result.executedAmountIn), "swapAmountOut", utils.FormatInt(result.swapAmountOut), "executedAmountOut", utils.FormatInt(result.executedAmountOut), "accumulatedOutputPerAmountX128", group.AccumulatedOutputPerAmountX128().ToString(), "endedOrderAmount", utils.FormatInt(result.endedOrderAmount), "nextOrderAmount", utils.FormatInt(group.OrderAmount()), "scheduledTimestamp", utils.FormatInt(result.scheduledTimestamp), "executionTimestamp", utils.FormatInt(result.executionTimestamp), "nextExecutionTimestamp", utils.FormatInt(group.NextExecutionTimestamp()), ) } func emitGroupOrdersClaimed( prevAddr address, prevRealm string, groupID string, examinedOrderCount int, claimedOrderCount int, releasedExecutionLogCount int64, nextCursor uint64, ) { chain.Emit( "DCAGroupOrdersClaimed", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "groupId", groupID, "examinedOrderCount", utils.FormatInt(int64(examinedOrderCount)), "claimedOrderCount", utils.FormatInt(int64(claimedOrderCount)), "releasedExecutionLogCount", utils.FormatInt(releasedExecutionLogCount), "nextCursor", utils.FormatUint(nextCursor), ) } // emitOrderClaimed reports a payout. grossAmount is the accrued output paid // out, executionFeeAmount the order's fee on it, and claimedAmount the rest, // sent to the owner; the totals are the order's lifetime values. func emitOrderClaimed( prevAddr address, prevRealm string, order *pdca.Order, group *pdca.Group, payout orderPayout, status pdca.OrderStatus, ) { chain.Emit( "DCAOrderClaimed", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "orderId", utils.FormatUint(order.ID()), "owner", order.Owner().String(), "groupId", order.GroupID(), "outputToken", group.OutputToken(), "grossAmount", utils.FormatInt(payout.grossAmount), "executionFeeRate", utils.FormatInt(order.ExecutionFeeRate()), "executionFeeAmount", utils.FormatInt(payout.executionFeeAmount), "claimedAmount", utils.FormatInt(payout.claimedAmount), "totalClaimedAmount", order.ClaimedAmount().ToString(), "totalExecutionFeeAmount", order.ExecutionFeeAmount().ToString(), "debtX128", order.DebtX128().ToString(), "status", status.String(), ) } func emitOrderCancelled( prevAddr address, prevRealm string, order *pdca.Order, group *pdca.Group, payout orderPayout, refundedAmount int64, ) { chain.Emit( "DCAOrderCancelled", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "orderId", utils.FormatUint(order.ID()), "owner", order.Owner().String(), "groupId", order.GroupID(), "inputToken", group.InputToken(), "outputToken", group.OutputToken(), "refundedAmount", utils.FormatInt(refundedAmount), "grossAmount", utils.FormatInt(payout.grossAmount), "executionFeeRate", utils.FormatInt(order.ExecutionFeeRate()), "executionFeeAmount", utils.FormatInt(payout.executionFeeAmount), "claimedAmount", utils.FormatInt(payout.claimedAmount), "totalClaimedAmount", order.ClaimedAmount().ToString(), "totalExecutionFeeAmount", order.ExecutionFeeAmount().ToString(), "debtX128", order.DebtX128().ToString(), "status", pdca.OrderStatusCancelled.String(), "cancelRound", utils.FormatUint(group.Round()), "groupOrderAmount", utils.FormatInt(group.OrderAmount()), ) } // emitPayoutExecutionFee reports the execution fee a payout of the group's // orders charged and kept as pending, if any. func emitPayoutExecutionFee(prevAddr address, prevRealm string, group *pdca.Group, executionFeeAmount int64, pendingAmount int64) { if executionFeeAmount <= 0 { return } emitExecutionFeeCollected(prevAddr, prevRealm, group.ID(), group.OutputToken(), group.Round(), executionFeeAmount, 0, pendingAmount) } // emitExecutionFeeCollected reports execution fees of tokenPath. // executionFeeAmount is the fee payouts charged (0 for a round or // CollectPendingExecutionFee), forwardedAmount what was sent to the protocol // fee realm, and pendingAmount what this realm still holds. // groupId is empty and round 0 for CollectPendingExecutionFee. func emitExecutionFeeCollected( prevAddr address, prevRealm string, groupID string, tokenPath string, round uint64, executionFeeAmount int64, forwardedAmount int64, pendingAmount int64, ) { chain.Emit( "DCAExecutionFeeCollected", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "groupId", groupID, "tokenPath", tokenPath, "round", utils.FormatUint(round), "executionFeeAmount", utils.FormatInt(executionFeeAmount), "forwardedAmount", utils.FormatInt(forwardedAmount), "pendingAmount", utils.FormatInt(pendingAmount), ) } func emitExecutionFeeRateChanged(prevAddr address, prevRealm string, previousExecutionFeeRate int64, executionFeeRate int64) { chain.Emit( "DCAExecutionFeeRateChanged", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "previousExecutionFeeRate", utils.FormatInt(previousExecutionFeeRate), "executionFeeRate", utils.FormatInt(executionFeeRate), ) } func emitSlotStepChanged(prevAddr address, prevRealm string, interval int64, previousSlotStep int64, slotStep int64) { chain.Emit( "DCASlotStepChanged", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "interval", utils.FormatInt(interval), "previousSlotStep", utils.FormatInt(previousSlotStep), "slotStep", utils.FormatInt(slotStep), ) } func emitExecutionLogsReleased(prevAddr address, prevRealm string, order *pdca.Order, group *pdca.Group, releasedExecutionLogCount int64) { chain.Emit( "DCAExecutionLogsReleased", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "orderId", utils.FormatUint(order.ID()), "groupId", group.ID(), "round", utils.FormatUint(group.Round()), "releasedExecutionLogCount", utils.FormatInt(releasedExecutionLogCount), "remainingExecutionLogCount", utils.FormatInt(order.ExecutionLogCount()), ) } func emitConfigUpdated(prevAddr address, prevRealm string, key string, previousValue int64, value int64) { chain.Emit( "DCAConfigUpdated", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "key", key, "previousValue", utils.FormatInt(previousValue), "value", utils.FormatInt(value), ) } func emitAllowedIntervalUpdated(prevAddr address, prevRealm string, interval int64, allowed bool) { chain.Emit( "DCAAllowedIntervalUpdated", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "interval", utils.FormatInt(interval), "allowed", utils.FormatBool(allowed), ) } // emitOrderForceCancelled reports an order closed by a keeper with ForceCancelOrder. // It carries the fields of DCAOrderCancelled and the reason the order blocked // its group (see ForceCancelOrder); the order's status is // cancelled, and its output and refund went to the owner. func emitOrderForceCancelled( prevAddr address, prevRealm string, order *pdca.Order, group *pdca.Group, payout orderPayout, refundedAmount int64, reason string, ) { chain.Emit( "DCAOrderForceCancelled", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "orderId", utils.FormatUint(order.ID()), "owner", order.Owner().String(), "groupId", order.GroupID(), "inputToken", group.InputToken(), "outputToken", group.OutputToken(), "refundedAmount", utils.FormatInt(refundedAmount), "grossAmount", utils.FormatInt(payout.grossAmount), "executionFeeRate", utils.FormatInt(order.ExecutionFeeRate()), "executionFeeAmount", utils.FormatInt(payout.executionFeeAmount), "claimedAmount", utils.FormatInt(payout.claimedAmount), "totalClaimedAmount", order.ClaimedAmount().ToString(), "totalExecutionFeeAmount", order.ExecutionFeeAmount().ToString(), "debtX128", order.DebtX128().ToString(), "status", pdca.OrderStatusCancelled.String(), "cancelRound", utils.FormatUint(group.Round()), "groupOrderAmount", utils.FormatInt(group.OrderAmount()), "reason", reason, ) } func emitTokenMinAmountPerExecutionUpdated( prevAddr address, prevRealm string, tokenPath string, previousMinAmountPerExecution int64, minAmountPerExecution int64, ) { chain.Emit( "DCATokenMinAmountPerExecutionUpdated", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "tokenPath", tokenPath, "prevMinAmountPerExecution", utils.FormatInt(previousMinAmountPerExecution), "minAmountPerExecution", utils.FormatInt(minAmountPerExecution), ) } // emitPairPriceLimitUpdated reports a pair price limit change; // minOutputPerInputX128 "0" and updatedAt 0 mean the limit was removed. func emitPairPriceLimitUpdated( prevAddr address, prevRealm string, inputToken string, outputToken string, previousMinOutputPerInputX128 string, minOutputPerInputX128 string, updatedAt int64, ) { chain.Emit( "DCAPairPriceLimitUpdated", "prevAddr", prevAddr.String(), "prevRealm", prevRealm, "inputToken", inputToken, "outputToken", outputToken, "prevMinOutputPerInputX128", previousMinOutputPerInputX128, "minOutputPerInputX128", minOutputPerInputX128, "updatedAt", utils.FormatInt(updatedAt), ) }
- #14errors.gno
- #15package impl import ( ufmt "gno.land/p/nt/ufmt/v0" ) const ( errInvalidPool = "[GNOSWAP-ORDER-DCA-001] invalid pool" errInvalidToken = "[GNOSWAP-ORDER-DCA-002] invalid token" errInvalidInterval = "[GNOSWAP-ORDER-DCA-003] invalid interval" errInvalidAmount = "[GNOSWAP-ORDER-DCA-004] invalid amount" errInvalidExecutionCount = "[GNOSWAP-ORDER-DCA-005] invalid number of executions" errOrderNotFound = "[GNOSWAP-ORDER-DCA-006] order not found" errNotOrderOwner = "[GNOSWAP-ORDER-DCA-007] caller is not the order owner" errGroupNotFound = "[GNOSWAP-ORDER-DCA-008] group not found" errGroupNotExecutable = "[GNOSWAP-ORDER-DCA-009] group is not executable" errSwapMismatch = "[GNOSWAP-ORDER-DCA-010] swap result mismatch" errInvalidConfig = "[GNOSWAP-ORDER-DCA-011] invalid config" errInvalidState = "[GNOSWAP-ORDER-DCA-012] invalid accounting state" errOverflow = "[GNOSWAP-ORDER-DCA-013] overflow" errReentrant = "[GNOSWAP-ORDER-DCA-014] reentrant call during group execution" errInvalidCursor = "[GNOSWAP-ORDER-DCA-015] invalid cursor" errNotKeeper = "[GNOSWAP-ORDER-DCA-016] caller is not an authorized keeper" errNoEligiblePool = "[GNOSWAP-ORDER-DCA-017] no eligible pool" errInvalidExecutionFeeRate = "[GNOSWAP-ORDER-DCA-018] invalid execution fee rate" errInvalidSlotOffset = "[GNOSWAP-ORDER-DCA-019] invalid slot offset" errInvalidSlotStep = "[GNOSWAP-ORDER-DCA-020] invalid slot step" errHalted = "[GNOSWAP-ORDER-DCA-021] operation halted" errAmountInMismatch = "[GNOSWAP-ORDER-DCA-022] round input does not match the quote" errInsufficientOrderOutput = "[GNOSWAP-ORDER-DCA-024] insufficient output per order" errInsufficientSwapOutput = "[GNOSWAP-ORDER-DCA-025] swap output below amountOutMin" errInvalidPriceLimit = "[GNOSWAP-ORDER-DCA-026] invalid price limit" errMissingPriceLimit = "[GNOSWAP-ORDER-DCA-027] missing price limit" errOrderNotBlocking = "[GNOSWAP-ORDER-DCA-028] order does not block its group" ) func makeErrorWithDetails(message string, details string) error { return ufmt.Errorf("%s || %s", message, details) }
- #16execute.gno
- #17package impl import ( "time" "gno.land/p/gnoswap/gnsmath/v1" pdca "gno.land/p/gnoswap/order/dca/v1" u256 "gno.land/p/gnoswap/uint256/v1" ufmt "gno.land/p/nt/ufmt/v0" "gno.land/r/gnoswap/access/v1" "gno.land/r/gnoswap/common" "gno.land/r/gnoswap/order/halt" "gno.land/r/gnoswap/order/whitelist" ) // ExecuteGroup sells one round of a group with a pool swap // and credits the swap output to the group accumulator. // Each order's execution fee is deducted when the order is paid out; // the round forwards the fee already pending for its output token. // Only keepers allowed by gno.land/r/gnoswap/order/keeper may call it // (DCAKeeperRole at deployment): the schedule and the swap result are checked on-chain, // and a failed swap reverts so the round can be retried. // minOrderAmountOut, raised to minOrderAmountOutFloor, is the least output // every order of the round must be credited. func (d *dcaOrderImpl) ExecuteGroup( _ int, rlm realm, groupID string, expectedAmountIn int64, amountOutMin int64, minOrderAmountOut int64, ) (int64, int64) { access.AssertIsRlmCurrent(0, rlm) common.AssertIsNotHandleNativeCoin() assertIsNotHalted(halt.OperationExecute, halt.OperationWithdraw) d.assertIsNotExecuting() if amountOutMin < 0 || expectedAmountIn < 0 || minOrderAmountOut < 0 { panic(makeErrorWithDetails( errInvalidAmount, ufmt.Sprintf( "expectedAmountIn(%d) amountOutMin(%d) minOrderAmountOut(%d)", expectedAmountIn, amountOutMin, minOrderAmountOut, ), ).Error()) } if minOrderAmountOut < minOrderAmountOutFloor { minOrderAmountOut = minOrderAmountOutFloor } prev := rlm.Previous() assertIsAuthorizedKeeper(rlm.PkgPath(), prev.Address()) group, err := d.getGroup(groupID) if err != nil { panic(err.Error()) } currentTimestamp := time.Now().Unix() result, err := d.executeGroupRound(0, rlm, group, expectedAmountIn, amountOutMin, minOrderAmountOut, currentTimestamp) if err != nil { panic(err.Error()) } emitGroupExecuted(prev.Address(), prev.PkgPath(), group, result) if result.forwardedExecutionFeeAmount > 0 || result.pendingExecutionFeeAmount > 0 { emitExecutionFeeCollected( prev.Address(), prev.PkgPath(), group.ID(), group.OutputToken(), group.Round(), 0, result.forwardedExecutionFeeAmount, result.pendingExecutionFeeAmount, ) } return result.executedAmountIn, result.executedAmountOut } // groupRoundResult describes one executed round. type groupRoundResult struct { poolPath string scheduledTimestamp int64 executionTimestamp int64 executedAmountIn int64 // input sold, the group orderAmount swapAmountOut int64 // pool output of the round executedAmountOut int64 // output credited to the orders, before their execution fees endedOrderAmount int64 // orderAmount of the orders whose last round this was forwardedExecutionFeeAmount int64 // pending execution fee sent to the protocol fee realm pendingExecutionFeeAmount int64 // execution fee still held by this realm } // executeGroupRound runs the group's next round: it checks the schedule // and the quoted input, picks the pool, swaps the whole round input within // the pair price limit, and credits the pool output (swapAmountOut) to the // accumulator per unit of the round input. // // The round charges no fee itself. Each order's execution fee is its own // snapshotted executionFeeRate of its gross output, deducted when the order // is paid out (Claim, ClaimGroupOrders, CancelOrder, ForceCancelOrder) and // held as pending. The round forwards the fee pending for its output token to // the protocol fee realm, so the fee still costs one transfer per round // instead of one per order. // // Every order of the round must be credited at least minOrderAmountOut of // output after its own execution fee rate. A round that cannot // pay its smallest order that much is treated as lacking liquidity: it // reverts, like a failed swap, so it can be retried. // // Checks-effects-interactions: // the round, schedule, and next orderAmount are written before the pool // swap, and an execution lock blocks re-entry while the swap and the // pending execution fee transfer run. // Only the swap-dependent accumulator is written after the swap. func (d *dcaOrderImpl) executeGroupRound( _ int, rlm realm, group *pdca.Group, expectedAmountIn, amountOutMin, minOrderAmountOut, currentTimestamp int64, ) (groupRoundResult, error) { config := d.store.GetConfig() orderAmount := group.OrderAmount() if orderAmount <= 0 { return groupRoundResult{}, makeErrorWithDetails(errGroupNotExecutable, ufmt.Sprintf("groupId(%s) has no active order amount", group.ID())) } // Check the schedule first, // so a round already run by someone else reports "not executable". scheduledTimestamp := group.NextExecutionTimestamp() if currentTimestamp < scheduledTimestamp { return groupRoundResult{}, makeErrorWithDetails( errGroupNotExecutable, ufmt.Sprintf("groupId(%s) next execution at %d, now %d", group.ID(), scheduledTimestamp, currentTimestamp), ) } // Orders may join or leave between the keeper's quote and inclusion; // the keeper then quotes again. assertIsQuotedAmountIn(group, expectedAmountIn, amountOutMin) // The pair price limit bounds the round's price and the pool's tick walk. priceLimit := getPairPriceLimit(d.store.GetPairPriceLimits(), group.InputToken(), group.OutputToken()) selectedPool, err := selectRoundPool(whitelist.GetWhitelistedPools(whitelist.TargetDCA), priceLimit, config.MaxPoolPriceDeviationRate(), config.MaxPairPriceLimitAge(), group, orderAmount) if err != nil { return groupRoundResult{}, err } // Effects independent of the swap result. round := gnsmath.SafeAddUint64(group.Round(), 1) group.SetRound(round) // Orders ending at this round stop selling from the next round. roundMark := group.GetRoundMark(round) endedOrderAmount := int64(0) if roundMark != nil { endedOrderAmount = roundMark.OrderAmount() } // Move to the next slot without the ended order amount, // at least the execution gap after now. // A group with no order amount left drops out of the schedule index. minExecutionGap, err := pdca.CalculateMinExecutionGap(group.Interval(), config.MinExecutionGapRate()) if err != nil { return groupRoundResult{}, err } nextExecutionTimestamp, err := pdca.CalculateNextExecutionTimestampWithGap(scheduledTimestamp, currentTimestamp, group.Interval(), minExecutionGap) if err != nil { return groupRoundResult{}, err } nextOrderAmount := gnsmath.SafeSubInt64(orderAmount, endedOrderAmount) if err := d.rescheduleGroup(group, nextOrderAmount, nextExecutionTimestamp); err != nil { return groupRoundResult{}, err } // Net payouts grow with amountPerExecution at one fee rate, // so the smallest order of each rate bounds every order's output. minAmounts := d.getFeeRateMinAmounts(group, round, true) if len(minAmounts) == 0 { return groupRoundResult{}, makeErrorWithDetails( errInvalidState, ufmt.Sprintf("groupId(%s) has no indexed order for round %d", group.ID(), round), ) } if err := d.store.SetExecuting(0, rlm, true); err != nil { return groupRoundResult{}, err } swapAmountOut, err := swapExactIn(0, rlm, group, selectedPool.fee, selectedPool.sqrtPriceLimitX96, orderAmount, amountOutMin) if err != nil { return groupRoundResult{}, err } executedAmountOut := swapAmountOut outputPerAmountX128, err := pdca.CalculateOutputPerAmountX128(executedAmountOut, orderAmount) if err != nil { return groupRoundResult{}, err } if err := validateOrderOutput(group, minAmounts, minOrderAmountOut, outputPerAmountX128, executedAmountOut, orderAmount); err != nil { return groupRoundResult{}, err } accumulatedOutputPerAmountX128, overflow := u256.Zero().AddOverflow(group.AccumulatedOutputPerAmountX128(), outputPerAmountX128) if overflow { return groupRoundResult{}, makeErrorWithDetails(errOverflow, "accumulator overflow") } group.SetAccumulatedOutputPerAmountX128(accumulatedOutputPerAmountX128) if roundMark != nil { roundMark.SnapshotAccumulatedOutputPerAmountX128(accumulatedOutputPerAmountX128) } forwardedExecutionFeeAmount, pendingExecutionFeeAmount := d.collectExecutionFee(0, rlm, group.OutputToken(), 0) if err := d.store.SetExecuting(0, rlm, false); err != nil { return groupRoundResult{}, err } return groupRoundResult{ poolPath: selectedPool.poolPath, scheduledTimestamp: scheduledTimestamp, executionTimestamp: currentTimestamp, executedAmountIn: orderAmount, swapAmountOut: swapAmountOut, executedAmountOut: executedAmountOut, endedOrderAmount: endedOrderAmount, forwardedExecutionFeeAmount: forwardedExecutionFeeAmount, pendingExecutionFeeAmount: pendingExecutionFeeAmount, }, nil }
- #18execution_fee.gno
- #19package impl import ( "gno.land/p/gnoswap/gnsmath/v1" pdca "gno.land/p/gnoswap/order/dca/v1" prbac "gno.land/p/gnoswap/rbac/v1" bptree "gno.land/p/nt/bptree/v0" ufmt "gno.land/p/nt/ufmt/v0" "gno.land/r/gnoswap/access/v1" "gno.land/r/gnoswap/common" "gno.land/r/gnoswap/order/halt" pf "gno.land/r/gnoswap/protocol_fee" _ "gno.land/r/gnoswap/protocol_fee/v1" ) // SetExecutionFeeRate sets the execution fee rate, in basis points, // snapshotted by orders created afterwards. // Existing orders keep the rate they were created with. // Admin or governance only. func (d *dcaOrderImpl) SetExecutionFeeRate(_ int, rlm realm, executionFeeRate int64) { access.AssertIsRlmCurrent(0, rlm) common.AssertIsNotHandleNativeCoin() d.assertIsNotExecuting() prev := rlm.Previous() access.AssertIsAdminOrGovernance(prev.Address()) config := d.store.GetConfig() previousExecutionFeeRate := config.ExecutionFeeRate() if err := config.SetExecutionFeeRate(executionFeeRate); err != nil { panic(makeErrorWithDetails( errInvalidExecutionFeeRate, ufmt.Sprintf("executionFeeRate(%d) must be in [0, %d]", executionFeeRate, pdca.MaxExecutionFeeRate), ).Error()) } emitExecutionFeeRateChanged(prev.Address(), prev.PkgPath(), previousExecutionFeeRate, executionFeeRate) } // CollectPendingExecutionFee forwards the execution fee pending for // tokenPath to the protocol fee realm. Payouts keep their execution fee as // pending and rounds forward the pending fee of their output token; this // forwards it when no round of that output token runs. // Anyone may call it: the fee only moves to the protocol fee realm. // It returns the amount forwarded and the amount left pending. func (d *dcaOrderImpl) CollectPendingExecutionFee(_ int, rlm realm, tokenPath string) (int64, int64) { access.AssertIsRlmCurrent(0, rlm) common.AssertIsNotHandleNativeCoin() assertIsNotHalted(halt.OperationWithdraw) d.assertIsNotExecuting() prev := rlm.Previous() // The execution lock blocks re-entry while the protocol fee realm pulls // the fee, as it does during a round. if err := d.store.SetExecuting(0, rlm, true); err != nil { panic(err.Error()) } forwardedAmount, pendingAmount := d.collectExecutionFee(0, rlm, tokenPath, 0) if err := d.store.SetExecuting(0, rlm, false); err != nil { panic(err.Error()) } if forwardedAmount > 0 || pendingAmount > 0 { emitExecutionFeeCollected(prev.Address(), prev.PkgPath(), "", tokenPath, 0, 0, forwardedAmount, pendingAmount) } return forwardedAmount, pendingAmount } // addPendingExecutionFee holds a payout's execution fee for tokenPath // until a round or CollectPendingExecutionFee forwards it. // A payout never calls the protocol fee realm, // so that realm cannot block withdrawals. func (d *dcaOrderImpl) addPendingExecutionFee(tokenPath string, executionFeeAmount int64) { if executionFeeAmount <= 0 { return } pendingExecutionFees := d.store.GetPendingExecutionFees() pendingAmount := getPendingExecutionFeeAmount(pendingExecutionFees, tokenPath) pendingExecutionFees.Set(tokenPath, gnsmath.SafeAddInt64(pendingAmount, executionFeeAmount)) } // pendingExecutionFeeAmount returns the execution fee of tokenPath // held by this realm, 0 if none. func (d *dcaOrderImpl) pendingExecutionFeeAmount(tokenPath string) int64 { return getPendingExecutionFeeAmount(d.store.GetPendingExecutionFees(), tokenPath) } // collectExecutionFee forwards executionFeeAmount, plus anything already // pending for tokenPath, to the protocol fee realm. // When collection is halted or the protocol fee realm rejects it, // the total is held as pending and forwarded by a later collection // of the same token, so a halt never blocks execution. // It returns the amount forwarded and the amount left pending. func (d *dcaOrderImpl) collectExecutionFee(_ int, rlm realm, tokenPath string, executionFeeAmount int64) (int64, int64) { pendingExecutionFees := d.store.GetPendingExecutionFees() pendingAmount := getPendingExecutionFeeAmount(pendingExecutionFees, tokenPath) totalAmount := gnsmath.SafeAddInt64(pendingAmount, executionFeeAmount) if totalAmount <= 0 { return 0, 0 } protocolFeeAddress := access.MustGetAddress(prbac.ROLE_PROTOCOL_FEE.String()) common.SafeGRC20Approve(0, rlm, tokenPath, protocolFeeAddress, totalAmount) // AddToProtocolFee pulls the approved amount from this realm. It returns // an error while its collection is halted; nothing was pulled then: // withdraw the approval and keep it pending. if err := pf.AddToProtocolFee(cross(rlm), tokenPath, totalAmount); err != nil { common.SafeGRC20Approve(0, rlm, tokenPath, protocolFeeAddress, 0) pendingExecutionFees.Set(tokenPath, totalAmount) return 0, totalAmount } // Keep the token's entry at zero rather than removing it: payouts add to // it again, and recreating it would charge the next payout its storage. if pendingAmount > 0 { pendingExecutionFees.Set(tokenPath, int64(0)) } return totalAmount, 0 } // getPendingExecutionFeeAmount returns the execution fee of tokenPath // held by this realm, 0 if none. func getPendingExecutionFeeAmount(pendingExecutionFees *bptree.BPTree, tokenPath string) int64 { value := pendingExecutionFees.Get(tokenPath) if value == nil { return 0 } return value.(int64) }
- #20getter.gno
- #21package impl import ( "time" "gno.land/p/gnoswap/gnsmath/v1" pdca "gno.land/p/gnoswap/order/dca/v1" "gno.land/p/gnoswap/utils/v1" rotree "gno.land/p/nt/bptree/rotree/v0" "gno.land/p/onbloc/json/v0" "gno.land/r/gnoswap/order/halt" "gno.land/r/gnoswap/order/whitelist" ) // Getters return copies of stored orders, groups, and configs. // A stored pointer must never leave the realm: methods of pdca types run // with the storing realm's authority, so a caller holding the pointer // could mutate state through its setters. // Store trees are wrapped in read-only views for the same reason: // views of trees holding pointers copy every entry they return. // Group copies leave out the round marks, so their cost does not grow with // the marks any order creator can add; GetGroupRoundMarks reads them. // GetConfig returns a copy of the configuration. func (d *dcaOrderImpl) GetConfig() *pdca.Config { return d.store.GetConfig().Clone() } // GetNextOrderID returns the ID the next created order receives. func (d *dcaOrderImpl) GetNextOrderID() uint64 { return d.store.GetNextOrderID() } // ExistsOrder reports whether orderID is an active order. func (d *dcaOrderImpl) ExistsOrder(orderID uint64) bool { return d.store.GetOrders().Has(pdca.OrderKey(orderID)) } // GetOrder returns a copy of an active order. func (d *dcaOrderImpl) GetOrder(orderID uint64) (*pdca.Order, error) { order, err := d.getOrder(orderID) if err != nil { return nil, err } return order.Clone(), nil } // GetOrders returns a read-only view of active orders keyed by OrderKey. func (d *dcaOrderImpl) GetOrders() *rotree.ReadOnlyTree { return rotree.Wrap(d.store.GetOrders(), cloneOrderEntry) } // GetOrdersByOwner returns the read-only OwnerOrderKey -> orderID index. func (d *dcaOrderImpl) GetOrdersByOwner() *rotree.ReadOnlyTree { return rotree.Wrap(d.store.GetOrdersByOwner(), nil) } // GetClaimableAmount returns what the next Claim of an active order pays. func (d *dcaOrderImpl) GetClaimableAmount(orderID uint64) int64 { order, group, err := d.getOrderWithGroup(orderID) if err != nil { return 0 } claimableAmount, err := calculateClaimableAmount(order, group) if err != nil { panic(err.Error()) } return claimableAmount } // GetOrderIDsByOwner pages an owner's active order IDs. func (d *dcaOrderImpl) GetOrderIDsByOwner(owner address, startAfterID uint64, count int) []uint64 { if count <= 0 { return []uint64{} } prefix := pdca.OwnerOrderPrefix(owner) start := prefix if startAfterID > 0 { if startAfterID == ^uint64(0) { return []uint64{} } start = pdca.OwnerOrderKey(owner, gnsmath.SafeAddUint64(startAfterID, 1)) } orderIDs := []uint64{} d.store.GetOrdersByOwner().Iterate(start, pdca.PrefixEnd(prefix), func(_ string, value any) bool { orderIDs = append(orderIDs, value.(uint64)) return len(orderIDs) >= count }) return orderIDs } // GetOrderIDsByGroup pages a group's active order IDs. func (d *dcaOrderImpl) GetOrderIDsByGroup(groupID string, startAfterID uint64, count int) []uint64 { if count <= 0 { return []uint64{} } orderIDs, _ := d.getGroupOrderIDs(groupID, startAfterID, count) return orderIDs } // ExistsGroup reports whether groupID is a stored group. func (d *dcaOrderImpl) ExistsGroup(groupID string) bool { return d.store.GetGroups().Has(groupID) } // GetGroup returns a copy of a group without its round marks. func (d *dcaOrderImpl) GetGroup(groupID string) (*pdca.Group, error) { group, err := d.getGroup(groupID) if err != nil { return nil, err } return group.CloneWithoutRoundMarks(), nil } // GetGroups returns a read-only view of groups keyed by group ID. func (d *dcaOrderImpl) GetGroups() *rotree.ReadOnlyTree { return rotree.Wrap(d.store.GetGroups(), cloneGroupEntry) } // GetGroupRoundMarks returns a read-only view of a group's round marks // keyed by RoundKey, or nil if the group does not exist. func (d *dcaOrderImpl) GetGroupRoundMarks(groupID string) *rotree.ReadOnlyTree { group, err := d.getGroup(groupID) if err != nil { return nil } return group.RoundMarks() } // GetOrdersByGroup returns the read-only GroupOrderKey -> orderID index. func (d *dcaOrderImpl) GetOrdersByGroup() *rotree.ReadOnlyTree { return rotree.Wrap(d.store.GetOrdersByGroup(), nil) } // GetOrderAmountsByGroup returns the read-only // GroupOrderAmountKey -> endRound index. func (d *dcaOrderImpl) GetOrderAmountsByGroup() *rotree.ReadOnlyTree { return rotree.Wrap(d.store.GetOrderAmountsByGroup(), nil) } // GetScheduledGroups returns the read-only ScheduleKey -> groupID index. func (d *dcaOrderImpl) GetScheduledGroups() *rotree.ReadOnlyTree { return rotree.Wrap(d.store.GetScheduledGroups(), nil) } // GetTokenMinAmountPerExecution returns the minimum input per execution set // for tokenPath, or 0 if none is set. func (d *dcaOrderImpl) GetTokenMinAmountPerExecution(tokenPath string) int64 { return getTokenMinAmountPerExecution(d.store, tokenPath) } // GetMinAmountPerExecution returns the minimum input per execution a new order // selling tokenPath needs: the larger of the global and the token minimum. func (d *dcaOrderImpl) GetMinAmountPerExecution(tokenPath string) int64 { return d.minAmountPerExecution(tokenPath) } // GetTokenMinAmountsPerExecution returns the read-only tokenPath -> int64 // index of per-token minimums. func (d *dcaOrderImpl) GetTokenMinAmountsPerExecution() *rotree.ReadOnlyTree { return rotree.Wrap(d.store.GetTokenMinAmountsPerExecution(), nil) } // GetPairPriceLimit returns a copy of the price limit of selling inputToken // for outputToken, and whether one is set. func (d *dcaOrderImpl) GetPairPriceLimit(inputToken string, outputToken string) (*pdca.PairPriceLimit, bool) { limit := getPairPriceLimit(d.store.GetPairPriceLimits(), inputToken, outputToken) if limit == nil { return nil, false } return limit.Clone(), true } // GetPairPriceLimits returns a read-only view of the pair price limits keyed // by PairKey. func (d *dcaOrderImpl) GetPairPriceLimits() *rotree.ReadOnlyTree { return rotree.Wrap(d.store.GetPairPriceLimits(), clonePairPriceLimitEntry) } // GetExecutableGroups lists copies of due groups after the cursor entry. // The schedule index is ordered by next execution timestamp, // so the scan stops at the first group that is not yet due. // Pools are not quoted; a listed round may still revert. // Nothing is listed while rounds are halted. func (d *dcaOrderImpl) GetExecutableGroups(cursor string, count int) ([]*pdca.Group, error) { if count <= 0 { return []*pdca.Group{}, nil } start, err := pdca.ParseScheduleCursor(cursor) if err != nil { return nil, makeErrorWithDetails(errInvalidCursor, cursor) } // Rounds cannot run while execution is halted. if isExecutionHalted() { return []*pdca.Group{}, nil } currentTimestamp := time.Now().Unix() groupIDs := []string{} d.store.GetScheduledGroups().Iterate(start, "", func(key string, value any) bool { if key == start && start != "" { return false } if pdca.ScheduleKeyTimestamp(key) > currentTimestamp { return true } groupIDs = append(groupIDs, value.(string)) return len(groupIDs) >= count }) groups := make([]*pdca.Group, 0, len(groupIDs)) for _, groupID := range groupIDs { group, err := d.GetGroup(groupID) if err != nil { return nil, err } groups = append(groups, group) } return groups, nil } // GetOrderExecutionLogs returns copies of up to count of an order's unreleased // execution logs, oldest first. func (d *dcaOrderImpl) GetOrderExecutionLogs(orderID uint64, count int) ([]*pdca.ExecutionLog, error) { order, err := d.getOrder(orderID) if err != nil { return nil, err } return pdca.ExecutionLogs(d.store.GetExecutionLogs(), order, count), nil } // GetExecutionLogs returns the read-only ExecutionLogKey -> lastRound index // of unreleased execution logs. func (d *dcaOrderImpl) GetExecutionLogs() *rotree.ReadOnlyTree { return rotree.Wrap(d.store.GetExecutionLogs(), nil) } // GetPendingExecutionFeeAmount returns the execution fee of tokenPath // held by this realm until the protocol fee realm accepts it. func (d *dcaOrderImpl) GetPendingExecutionFeeAmount(tokenPath string) int64 { return getPendingExecutionFeeAmount(d.store.GetPendingExecutionFees(), tokenPath) } // GetPendingExecutionFees returns the read-only tokenPath -> amount index // of execution fees held until the protocol fee realm accepts them. func (d *dcaOrderImpl) GetPendingExecutionFees() *rotree.ReadOnlyTree { return rotree.Wrap(d.store.GetPendingExecutionFees(), nil) } // GetExecutionQuote reports how the group's next round would trade now. // Every pool is quoted here, even a single one, // so the selection and output match ExecuteGroup in the same block. func (d *dcaOrderImpl) GetExecutionQuote(groupID string) string { group, err := d.getGroup(groupID) if err != nil { return "" } config := d.store.GetConfig() amountIn := group.OrderAmount() selectedPoolPath := "" expectedAmountOut := int64(0) expectedExecutionFeeAmount := int64(0) expectedMinOrderAmountOut := int64(0) candidateNodes := []*json.Node{} minAmountNodes := []*json.Node{} // The round checks the smallest order of each execution fee rate after // that rate. The quote's fee and order output assume the highest rate of // the orders the round sells, the most any of them pays. minAmounts := []feeRateMinAmount{} if amountIn > 0 { minAmounts = d.getFeeRateMinAmounts(group, group.Round()+1, false) } minAmountPerExecution := minAmountPerExecutionOf(minAmounts) executionFeeRate := maxExecutionFeeRateOf(minAmounts) priceLimit := getPairPriceLimit(d.store.GetPairPriceLimits(), group.InputToken(), group.OutputToken()) minOutputPerInputX128 := "0" priceLimitUpdatedAt := int64(0) if priceLimit != nil { minOutputPerInputX128 = priceLimit.MinOutputPerInputX128().ToString() priceLimitUpdatedAt = priceLimit.UpdatedAt() } if amountIn > 0 { selectedPool, candidates := selectPool(whitelist.GetWhitelistedPools(whitelist.TargetDCA), priceLimit, config.MaxPoolPriceDeviationRate(), config.MaxPairPriceLimitAge(), group.InputToken(), group.OutputToken(), amountIn, true) if selectedPool != nil { expectedAmountOut = selectedPool.quotedAmountOut selectedPoolPath = selectedPool.poolPath expectedOrderAmountOut, err := pdca.CalculateMinNetAmountOut(expectedAmountOut, executionFeeRate) if err != nil { panic(err.Error()) } expectedExecutionFeeAmount = expectedAmountOut - expectedOrderAmountOut } // The least output the round's per-order check would compare with // max(1, minOrderAmountOut). outputPerAmountX128, err := pdca.CalculateOutputPerAmountX128(expectedAmountOut, amountIn) if err != nil { panic(err.Error()) } for i, minAmount := range minAmounts { orderAmountOut, err := calculateMinOrderAmountOut(minAmount, outputPerAmountX128) if err != nil { panic(err.Error()) } if i == 0 || orderAmountOut < expectedMinOrderAmountOut { expectedMinOrderAmountOut = orderAmountOut } minAmountNodes = append(minAmountNodes, json.ObjectNode("", map[string]*json.Node{ "executionFeeRate": intNode(minAmount.executionFeeRate), "minAmountPerExecution": intNode(minAmount.minAmountPerExecution), })) } for _, candidate := range candidates { candidateAmountOut := int64(0) if candidate.isQuoted { candidateAmountOut = candidate.quotedAmountOut } candidateNodes = append(candidateNodes, json.ObjectNode("", map[string]*json.Node{ "poolPath": json.StringNode("", candidate.poolPath), "eligible": json.BoolNode("", candidate.isEligible()), "ineligibleCode": json.StringNode("", candidate.ineligibleCode), "ineligibleReason": json.StringNode("", candidate.ineligibleReason), "amountOut": intNode(candidateAmountOut), })) } } return marshal(map[string]*json.Node{ "groupId": json.StringNode("", group.ID()), "inputToken": json.StringNode("", group.InputToken()), "outputToken": json.StringNode("", group.OutputToken()), "amountIn": intNode(amountIn), "minAmountPerExecution": intNode(minAmountPerExecution), "executable": json.BoolNode("", isGroupExecutable(group, time.Now().Unix())), "selectedPool": json.StringNode("", selectedPoolPath), "expectedAmountOut": intNode(expectedAmountOut), "executionFeeRate": intNode(executionFeeRate), "expectedExecutionFeeAmount": intNode(expectedExecutionFeeAmount), "expectedOrderAmountOut": intNode(expectedAmountOut - expectedExecutionFeeAmount), "expectedMinOrderAmountOut": intNode(expectedMinOrderAmountOut), "minAmountsByExecutionFeeRate": json.ArrayNode("", minAmountNodes), "minOutputPerInputX128": json.StringNode("", minOutputPerInputX128), "priceLimitUpdatedAt": intNode(priceLimitUpdatedAt), "candidates": json.ArrayNode("", candidateNodes), }) } // calculateClaimableAmount returns what the next Claim pays the owner, // net of the order's execution fee. func calculateClaimableAmount(order *pdca.Order, group *pdca.Group) (int64, error) { endAccumulatedX128, _, err := getOrderEndAccumulatedOutputPerAmountX128(order, group) if err != nil { return 0, err } payout, err := calculateOrderPayout(order, endAccumulatedX128) if err != nil { return 0, err } return payout.claimedAmount, nil } // isGroupExecutable reports whether the schedule and the halts allow // the group's next round now. // Pools are not quoted here. func isGroupExecutable(group *pdca.Group, currentTimestamp int64) bool { return group.OrderAmount() > 0 && currentTimestamp >= group.NextExecutionTimestamp() && !isExecutionHalted() } // isExecutionHalted reports whether execute or withdraw is halted, // matching the checks ExecuteGroup makes before running a round. func isExecutionHalted() bool { _, halted := haltedOperation(halt.OperationExecute, halt.OperationWithdraw) return halted } func marshal(fields map[string]*json.Node) string { b, err := json.Marshal(json.ObjectNode("", fields)) if err != nil { panic(err.Error()) } return string(b) } func intNode(v int64) *json.Node { return json.StringNode("", utils.FormatInt(v)) } func cloneOrderEntry(value any) any { order, ok := value.(*pdca.Order) if !ok { return nil } return order.Clone() } func cloneGroupEntry(value any) any { group, ok := value.(*pdca.Group) if !ok { return nil } return group.CloneWithoutRoundMarks() } func clonePairPriceLimitEntry(value any) any { limit, ok := value.(*pdca.PairPriceLimit) if !ok { return nil } return limit.Clone() }
- #22gnomod.toml
- #23module = "gno.land/r/gnoswap/order/dca/impl/v1" gno = "0.9"
- #24init.gno
Result log
msg:0,success:true,log:,events:[]