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

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

feed.gno

7.30 Kb · 313 lines
  1package lastcall
  2
  3// The price feed. Off-chain updaters push quotes; the desk trusts them by
  4// address, so no single one sets a price alone once the quorum is above one.
  5//
  6// Each updater's latest quote is kept per ticker. A desk price is formed when a
  7// quorum of updaters have quoted after the current desk price, within
  8// quoteWindow of the newest of those quotes and within agreeBps of their
  9// median: the median of those quotes, stamped with the oldest observation it
 10// used. A quote far from the others is left out, so one updater can delay a
 11// price but not move it beyond the band. Every input to a price was observed at
 12// or after that stamp, which is what lets an order placed at time t fill only
 13// on a price observed after t (pricedAfter).
 14//
 15// Market hours follow the same rule: the market counts as open only while a
 16// quorum of updaters say it is.
 17
 18import (
 19	"strconv"
 20	"strings"
 21	"time"
 22)
 23
 24// Price is quoted in micro-USD per whole share.
 25type Price struct {
 26	Value      int64 // micro-USD per share
 27	ObservedAt int64 // unix seconds, the oldest observation behind this price
 28}
 29
 30const (
 31	maxPriceAge  = 600
 32	maxClockSkew = 60
 33	maxPrice     = 1_000_000_000000
 34	quoteWindow  = 120
 35	agreeBps     = 100
 36	maxUpdaters  = 7
 37)
 38
 39var (
 40	updaters   []address
 41	quorum     = 1
 42	prices     = map[string]Price{}
 43	submitted  = map[string]map[address]Price{}
 44	openVotes  = map[address]bool{}
 45	marketOpen = true
 46	openedAt   int64
 47)
 48
 49// --- updaters (admin) ---
 50
 51func AddUpdater(cur realm, u address) {
 52	assertAdmin(cur)
 53	if !u.IsValid() {
 54		panic("desk: invalid updater address")
 55	}
 56	if isUpdater(u) {
 57		panic("desk: already an updater")
 58	}
 59	if len(updaters) >= maxUpdaters {
 60		panic("desk: too many updaters")
 61	}
 62	updaters = append(updaters, u)
 63}
 64
 65func RemoveUpdater(cur realm, u address) {
 66	assertAdmin(cur)
 67	if !isUpdater(u) {
 68		panic("desk: not an updater")
 69	}
 70	if len(updaters)-1 < quorum {
 71		panic("desk: lower the quorum first")
 72	}
 73	kept := []address{}
 74	for _, a := range updaters {
 75		if a != u {
 76			kept = append(kept, a)
 77		}
 78	}
 79	updaters = kept
 80	delete(openVotes, u)
 81	for _, subs := range submitted {
 82		delete(subs, u)
 83	}
 84	tallyMarket()
 85}
 86
 87func SetQuorum(cur realm, n int) {
 88	assertAdmin(cur)
 89	if n < 1 || n > len(updaters) {
 90		panic("desk: quorum out of range")
 91	}
 92	quorum = n
 93	tallyMarket()
 94}
 95
 96// Updaters lists the updater addresses, comma-separated.
 97func Updaters() string {
 98	out := ""
 99	for i, u := range updaters {
100		if i > 0 {
101			out += ","
102		}
103		out += u.String()
104	}
105	return out
106}
107
108func Quorum() int { return quorum }
109
110func isUpdater(a address) bool {
111	for _, u := range updaters {
112		if u == a {
113			return true
114		}
115	}
116	return false
117}
118
119func assertUpdater(cur realm) address {
120	from := cur.Previous().Address()
121	if !isUpdater(from) {
122		panic("desk: updater only")
123	}
124	return from
125}
126
127// --- quotes ---
128
129// SetPrices records the caller's quotes, "TICKER:microUSD" pairs joined by ',',
130// all observed at observedAt, and forms a desk price where a quorum agrees. A
131// stamp ahead of the block time is lowered to it, so no price is ever dated
132// after a request that could already see it.
133func SetPrices(cur realm, quotes string, observedAt int64) {
134	from := assertUpdater(cur)
135	now := time.Now().Unix()
136	if observedAt > now+maxClockSkew {
137		panic("desk: observation is in the future")
138	}
139	if observedAt > now {
140		observedAt = now
141	}
142	for _, pair := range strings.Split(quotes, ",") {
143		ticker, raw, ok := strings.Cut(pair, ":")
144		value, err := strconv.ParseInt(raw, 10, 64)
145		if !ok || err != nil {
146			panic("desk: malformed quote: " + pair)
147		}
148		submit(from, ticker, value, observedAt)
149	}
150}
151
152func submit(from address, ticker string, value, observedAt int64) {
153	_ = mustStock(ticker)
154	if value <= 0 || value > maxPrice {
155		panic("desk: price out of range")
156	}
157	subs := submitted[ticker]
158	if subs == nil {
159		subs = map[address]Price{}
160		submitted[ticker] = subs
161	}
162	if prev, ok := subs[from]; ok && observedAt < prev.ObservedAt {
163		panic("desk: observation is older than your last quote")
164	}
165	subs[from] = Price{Value: value, ObservedAt: observedAt}
166	aggregate(ticker)
167}
168
169func aggregate(ticker string) {
170	since := int64(-1)
171	if p, ok := prices[ticker]; ok {
172		since = p.ObservedAt
173	}
174	fresh := []Price{}
175	newest := int64(0)
176	for _, u := range updaters {
177		q, ok := submitted[ticker][u]
178		if !ok || q.ObservedAt <= since {
179			continue
180		}
181		fresh = append(fresh, q)
182		if q.ObservedAt > newest {
183			newest = q.ObservedAt
184		}
185	}
186	quotes := []Price{}
187	vals := []int64{}
188	for _, q := range fresh {
189		if newest-q.ObservedAt <= quoteWindow {
190			quotes = append(quotes, q)
191			vals = append(vals, q.Value)
192		}
193	}
194	if len(vals) < quorum {
195		return
196	}
197	mid := median(vals)
198	band := mulDiv(mid, agreeBps, bpsDenom)
199	agreed := []int64{}
200	oldest := newest
201	for _, q := range quotes {
202		if q.Value < mid-band || q.Value > mid+band {
203			continue
204		}
205		agreed = append(agreed, q.Value)
206		if q.ObservedAt < oldest {
207			oldest = q.ObservedAt
208		}
209	}
210	if len(agreed) < quorum {
211		return
212	}
213	prices[ticker] = Price{Value: median(agreed), ObservedAt: oldest}
214}
215
216func median(vals []int64) int64 {
217	s := append([]int64{}, vals...)
218	for i := 1; i < len(s); i++ {
219		for j := i; j > 0 && s[j] < s[j-1]; j-- {
220			s[j], s[j-1] = s[j-1], s[j]
221		}
222	}
223	m := len(s) / 2
224	if len(s)%2 == 1 {
225		return s[m]
226	}
227	return s[m-1] + (s[m]-s[m-1])/2
228}
229
230// GetPrice returns the desk price for a ticker and its observation time. Panics if unknown.
231func GetPrice(ticker string) (int64, int64) {
232	p, ok := prices[ticker]
233	if !ok {
234		panic("desk: no price for " + ticker)
235	}
236	return p.Value, p.ObservedAt
237}
238
239// IsFresh reports whether a ticker has a price young enough to trade against.
240func IsFresh(ticker string) bool {
241	p, ok := prices[ticker]
242	return ok && time.Now().Unix()-p.ObservedAt <= maxPriceAge
243}
244
245// LastCallAt is the time after which the stored price no longer allows a trade,
246// or 0 before the first price.
247func LastCallAt(ticker string) int64 {
248	p, ok := prices[ticker]
249	if !ok {
250		return 0
251	}
252	return p.ObservedAt + maxPriceAge
253}
254
255func freshPrice(ticker string) int64 {
256	value, _ := GetPrice(ticker)
257	if !IsFresh(ticker) {
258		panic("desk: price is stale, last call has passed for " + ticker)
259	}
260	return value
261}
262
263// pricedAfter reports whether the ticker's price was observed after t, so a
264// request made at t may fill on it.
265func pricedAfter(ticker string, t int64) bool {
266	p, ok := prices[ticker]
267	return ok && p.ObservedAt > t
268}
269
270// --- market hours ---
271
272// SetMarketOpen records the caller's view of the US stock market.
273func SetMarketOpen(cur realm, open bool) {
274	from := assertUpdater(cur)
275	openVotes[from] = open
276	tallyMarket()
277}
278
279// MarketVoteOf returns an updater's recorded view of the market: "open",
280// "closed" or "none".
281func MarketVoteOf(u address) string {
282	open, ok := openVotes[u]
283	switch {
284	case !ok:
285		return "none"
286	case open:
287		return "open"
288	}
289	return "closed"
290}
291
292func tallyMarket() {
293	if len(openVotes) == 0 {
294		return
295	}
296	n := 0
297	for _, u := range updaters {
298		if openVotes[u] {
299			n++
300		}
301	}
302	was := marketOpen
303	marketOpen = n >= quorum
304	if marketOpen && !was {
305		openedAt = time.Now().Unix()
306	}
307}
308
309// IsMarketOpen reports whether a quorum of updaters say the stock market is open.
310// While it is not, new perps are held to closedMaxLeverage and positions above it
311// can be cut down to it (Delever). A limit above that leverage fills only on a
312// price observed after the open, never on the last pre-open quote.
313func IsMarketOpen() bool { return marketOpen }