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

order.gno

6.52 Kb · 177 lines
  1package dca
  2
  3import (
  4	"gno.land/p/gnoswap/gnsmath/v1"
  5	"math"
  6
  7	u256 "gno.land/p/gnoswap/uint256/v1"
  8)
  9
 10// OrderStatus is the outcome reported in order events.
 11// Stored orders are always active: a completed or cancelled order is
 12// deleted, and its final state is kept in the event.
 13type OrderStatus string
 14
 15const (
 16	// OrderStatusActive: still selling input or holding unclaimed output.
 17	OrderStatusActive OrderStatus = "ACTIVE"
 18	// OrderStatusCompleted: every round executed and all output was paid.
 19	OrderStatusCompleted OrderStatus = "COMPLETED"
 20	// OrderStatusCancelled: cancelled by the owner; unsold input was refunded.
 21	OrderStatusCancelled OrderStatus = "CANCELLED"
 22)
 23
 24func (s OrderStatus) String() string {
 25	return string(s)
 26}
 27
 28// Order u256 setters copy the value into the field's existing object
 29// instead of attaching a new one: updates create no objects, and an order
 30// can be deleted in the same transaction it was updated in.
 31// Getters return copies, so stored values are never shared.
 32
 33// Order is one user's active DCA order.
 34// It sells amountPerExecution of the group's input token
 35// in each group round of (startRound, endRound].
 36// Accrued gross output is
 37// amountPerExecution * (acc(min(round, endRound)) - debtX128) / 2^128;
 38// each payout deducts the order's execution fee from it
 39// (see CalculatePayoutExecutionFeeAmount).
 40// The execution fee rate is snapshotted at creation for the order's lifetime.
 41// Only the payout state (debtX128, claimedAmount, executionFeeAmount) and the
 42// released execution logs change after creation.
 43type Order struct {
 44	id    uint64
 45	owner address
 46
 47	groupID string // tokens and interval are on the group
 48
 49	amountPerExecution int64
 50	startRound         uint64
 51	endRound           uint64
 52
 53	// executionFeeRate is the share of the order's gross output,
 54	// in basis points, charged when it is paid out.
 55	executionFeeRate int64
 56
 57	debtX128      *u256.Uint // group accumulator already paid out, see CalculateDebtX128AfterPayout
 58	claimedAmount *u256.Uint // lifetime output paid to the owner, net of the execution fee; 256-bit so it never overflows
 59
 60	// executionFeeAmount is the lifetime execution fee charged on payouts;
 61	// claimedAmount + executionFeeAmount is the gross output paid out.
 62	executionFeeAmount *u256.Uint
 63
 64	// Last round whose execution log was released;
 65	// the logs of rounds (releasedRound, endRound] are stored.
 66	releasedRound uint64
 67
 68	createdTimestamp int64
 69	createdHeight    int64
 70}
 71
 72// NewOrder creates an order that joins group at its current round.
 73// Store its execution logs with AllocateExecutionLogs.
 74// Its debt starts at the group's current accumulated output per amount,
 75// so it never shares output from earlier rounds.
 76// executionFeeRate is fixed for the order's lifetime.
 77// It returns ErrInvalidInput if executionCount is not positive or
 78// executionFeeRate is outside [0, MaxExecutionFeeRate],
 79// and ErrOverflow if the end round would pass the uint64 limit.
 80func NewOrder(
 81	id uint64,
 82	owner address,
 83	group *Group,
 84	amountPerExecution int64,
 85	executionCount int64,
 86	executionFeeRate int64,
 87	createdTimestamp int64,
 88	createdHeight int64,
 89) (*Order, error) {
 90	if executionCount <= 0 || !isValidExecutionFeeRate(executionFeeRate) {
 91		return nil, ErrInvalidInput
 92	}
 93
 94	startRound := group.Round()
 95	if uint64(executionCount) > math.MaxUint64-startRound {
 96		return nil, ErrOverflow
 97	}
 98
 99	return &Order{
100		id:                 id,
101		owner:              owner,
102		groupID:            group.ID(),
103		amountPerExecution: amountPerExecution,
104		startRound:         startRound,
105		endRound:           gnsmath.SafeAddUint64(startRound, uint64(executionCount)),
106		executionFeeRate:   executionFeeRate,
107		debtX128:           group.AccumulatedOutputPerAmountX128(), // already a copy
108		claimedAmount:      u256.Zero(),
109		executionFeeAmount: u256.Zero(),
110		releasedRound:      startRound,
111		createdTimestamp:   createdTimestamp,
112		createdHeight:      createdHeight,
113	}, nil
114}
115
116// Clone returns a deep copy of the order,
117// so callers can read it without aliasing stored state.
118func (o *Order) Clone() *Order {
119	return &Order{
120		id:                 o.id,
121		owner:              o.owner,
122		groupID:            o.groupID,
123		amountPerExecution: o.amountPerExecution,
124		startRound:         o.startRound,
125		endRound:           o.endRound,
126		executionFeeRate:   o.executionFeeRate,
127		debtX128:           o.debtX128.Clone(),
128		claimedAmount:      o.claimedAmount.Clone(),
129		executionFeeAmount: o.executionFeeAmount.Clone(),
130		releasedRound:      o.releasedRound,
131		createdTimestamp:   o.createdTimestamp,
132		createdHeight:      o.createdHeight,
133	}
134}
135
136func (o *Order) ID() uint64                { return o.id }
137func (o *Order) Owner() address            { return o.owner }
138func (o *Order) GroupID() string           { return o.groupID }
139func (o *Order) AmountPerExecution() int64 { return o.amountPerExecution }
140func (o *Order) ExecutionCount() int64     { return int64(o.endRound - o.startRound) }
141func (o *Order) StartRound() uint64        { return o.startRound }
142func (o *Order) EndRound() uint64          { return o.endRound }
143func (o *Order) ExecutionFeeRate() int64   { return o.executionFeeRate }
144func (o *Order) CreatedTimestamp() int64   { return o.createdTimestamp }
145func (o *Order) CreatedHeight() int64      { return o.createdHeight }
146
147func (o *Order) DebtX128() *u256.Uint     { return o.debtX128.Clone() }
148func (o *Order) SetDebtX128(v *u256.Uint) { o.debtX128.Set(v) }
149
150func (o *Order) ClaimedAmount() *u256.Uint     { return o.claimedAmount.Clone() }
151func (o *Order) SetClaimedAmount(v *u256.Uint) { o.claimedAmount.Set(v) }
152
153func (o *Order) ExecutionFeeAmount() *u256.Uint     { return o.executionFeeAmount.Clone() }
154func (o *Order) SetExecutionFeeAmount(v *u256.Uint) { o.executionFeeAmount.Set(v) }
155
156// PaidGrossAmount returns the gross output paid out so far:
157// claimedAmount plus executionFeeAmount.
158func (o *Order) PaidGrossAmount() *u256.Uint {
159	return u256.Zero().Add(o.claimedAmount, o.executionFeeAmount)
160}
161
162// ExecutionLogCount returns the number of the order's unreleased logs.
163// Logs start at fixed offsets from the start round, so no lookup is needed.
164func (o *Order) ExecutionLogCount() int64 {
165	remainingRoundCount := o.endRound - o.releasedRound
166
167	logCount := remainingRoundCount / ExecutionLogRoundCount
168	if remainingRoundCount%ExecutionLogRoundCount != 0 {
169		logCount = gnsmath.SafeAddUint64(logCount, 1)
170	}
171
172	return gnsmath.SafeUint64ToInt64(logCount)
173}
174
175// setReleasedRound is a method, not a field write, so an implementation
176// other than the order's creator can update it after an upgrade.
177func (o *Order) setReleasedRound(round uint64) { o.releasedRound = round }