desk.gno
6.01 Kb · 219 lines
1// Package lastcall is a synthetic stocks desk on gno.land.
2//
3// It is self-contained: it runs its own price feed (an off-chain bot pushes
4// quotes from the desk key, trusted by caller address), issues a test-USD
5// collateral token and synthetic stock tokens, and lets users trade them spot
6// against the desk. There is no external oracle and no external liquidity —
7// the desk is always the counterparty at its own quoted price.
8//
9// All amounts are integers. USD values are micro-USD (6 decimals):
10// $190.42 -> 190420000. Token amounts use 6 decimals too, so one whole share
11// is 1_000000 units and lines up 1:1 with the price scale.
12package lastcall
13
14import (
15 "strconv"
16 "strings"
17 "time"
18
19 "gno.land/p/nt/seqid/v0"
20 "gno.land/p/nt/ufmt/v0"
21)
22
23var (
24 admin address // deployer; may rotate admin and updater, seed the reserve
25 updater address // the off-chain price bot
26 deskAddr address // this realm's own address — the escrow / reserve account
27 nextTokID seqid.ID // unique id source for every grc20 token this realm mints
28)
29
30func init(cur realm) {
31 admin = cur.Previous().Address()
32 updater = admin
33 deskAddr = cur.Address()
34 initUSD(cur) // create the tUSD collateral token
35 initStocks(cur) // create the default synthetic stock markets
36}
37
38// --- admin ---
39
40func SetAdmin(cur realm, a address) {
41 assertAdmin(cur)
42 if !a.IsValid() {
43 panic("desk: invalid admin address")
44 }
45 admin = a
46}
47
48func SetUpdater(cur realm, u address) {
49 assertAdmin(cur)
50 if !u.IsValid() {
51 panic("desk: invalid updater address")
52 }
53 updater = u
54}
55
56func Admin() address { return admin }
57func Updater() address { return updater }
58func DeskAddress() address { return deskAddr }
59
60func assertAdmin(cur realm) {
61 if cur.Previous().Address() != admin {
62 panic("desk: admin only")
63 }
64}
65
66func assertUpdater(cur realm) {
67 if cur.Previous().Address() != updater {
68 panic("desk: updater only")
69 }
70}
71
72// --- price feed (own oracle, caller-auth) ---
73
74// Price is quoted in micro-USD per whole share.
75type Price struct {
76 Value int64 // micro-USD per share
77 ObservedAt int64 // unix seconds observed off-chain by the bot
78}
79
80var prices = map[string]Price{}
81
82// SetPrice is pushed by the off-chain bot (updater key) for one ticker.
83func SetPrice(cur realm, ticker string, value int64, observedAt int64) {
84 assertUpdater(cur)
85 storePrice(ticker, value, observedAt)
86}
87
88// SetPrices stores several quotes in one transaction so the keeper pays one fee
89// per cycle. quotes is "TICKER:microUSD" pairs joined by ','.
90func SetPrices(cur realm, quotes string, observedAt int64) {
91 assertUpdater(cur)
92 for _, pair := range strings.Split(quotes, ",") {
93 ticker, raw, ok := strings.Cut(pair, ":")
94 value, err := strconv.ParseInt(raw, 10, 64)
95 if !ok || err != nil {
96 panic("desk: malformed quote: " + pair)
97 }
98 storePrice(ticker, value, observedAt)
99 }
100}
101
102func storePrice(ticker string, value int64, observedAt int64) {
103 _ = mustStock(ticker)
104 if value <= 0 || value > maxPrice {
105 panic("desk: price out of range")
106 }
107 if observedAt > time.Now().Unix()+maxClockSkew {
108 panic("desk: observation is in the future")
109 }
110 if p, ok := prices[ticker]; ok && observedAt < p.ObservedAt {
111 panic("desk: observation is older than the stored quote")
112 }
113 prices[ticker] = Price{Value: value, ObservedAt: observedAt}
114}
115
116// GetPrice returns the last quote for a ticker. Panics if unknown.
117func GetPrice(ticker string) (int64, int64) {
118 p, ok := prices[ticker]
119 if !ok {
120 panic("desk: no price for " + ticker)
121 }
122 return p.Value, p.ObservedAt
123}
124
125const (
126 maxPriceAge = 600
127 maxClockSkew = 60
128 maxPrice = 1_000_000_000000
129)
130
131// IsFresh reports whether a ticker has a quote young enough to trade against.
132func IsFresh(ticker string) bool {
133 p, ok := prices[ticker]
134 return ok && time.Now().Unix()-p.ObservedAt <= maxPriceAge
135}
136
137// LastCallAt is the time after which the stored quote no longer allows a trade,
138// or 0 before the first quote.
139func LastCallAt(ticker string) int64 {
140 p, ok := prices[ticker]
141 if !ok {
142 return 0
143 }
144 return p.ObservedAt + maxPriceAge
145}
146
147func freshPrice(ticker string) int64 {
148 value, _ := GetPrice(ticker)
149 if !IsFresh(ticker) {
150 panic("desk: price is stale, last call has passed for " + ticker)
151 }
152 return value
153}
154
155// --- render ---
156
157func Render(path string) string {
158 out := "# LastCall\n\n"
159 out += "Synthetic stock desk: spot, perps, limit orders and a fee pool. Test funds only.\n\n"
160 out += "## Markets\n\n"
161 out += "| Ticker | Price (USD) | Quote | Supply | Long OI | Short OI |\n|---|---|---|---|---|---|\n"
162 for _, t := range tickers {
163 ps, quote := "-", "none"
164 if p, ok := prices[t]; ok {
165 ps = usdFmt(p.Value)
166 quote = "last call passed"
167 if IsFresh(t) {
168 quote = "live"
169 }
170 }
171 out += ufmt.Sprintf("| s%s | %s | %s | %s | %s | %s |\n", t, ps, quote, sharesFmt(stocks[t].token.TotalSupply()), usdFmt(oiLong[t]), usdFmt(oiShort[t]))
172 }
173 out += "\n## Desk\n\n"
174 out += ufmt.Sprintf("* tUSD total supply: %s\n", usdFmt(usd.TotalSupply()))
175 out += ufmt.Sprintf("* desk tUSD reserve: %s\n", usdFmt(usd.BalanceOf(deskAddr)))
176 out += ufmt.Sprintf("* locked behind positions and orders: %s\n", usdFmt(lockedUSD))
177 out += ufmt.Sprintf("* fee pool: %s, cumulative fees %s\n", usdFmt(assetsNow()), usdFmt(poolFeesAll))
178 out += ufmt.Sprintf("* open positions: %d, pending limits: %d\n", perps.Size(), limits.Size())
179 out += ufmt.Sprintf("* a quote older than %d seconds stops every trade that moves value\n", maxPriceAge)
180 return out
181}
182
183// usdFmt formats micro-USD as a dollar string with two decimals.
184func usdFmt(micro int64) string {
185 neg := micro < 0
186 if neg {
187 micro = -micro
188 }
189 d := micro / 1000000
190 c := (micro % 1000000) / 10000
191 cs := ufmt.Sprintf("%d", c)
192 if len(cs) == 1 {
193 cs = "0" + cs
194 }
195 s := ufmt.Sprintf("$%d.%s", d, cs)
196 if neg {
197 s = "-" + s
198 }
199 return s
200}
201
202// sharesFmt formats a 6-decimal token amount as a share count.
203func sharesFmt(units int64) string {
204 neg := units < 0
205 if neg {
206 units = -units
207 }
208 d := units / 1000000
209 f := units % 1000000
210 fs := ufmt.Sprintf("%d", f)
211 for len(fs) < 6 {
212 fs = "0" + fs
213 }
214 s := ufmt.Sprintf("%d.%s", d, fs)
215 if neg {
216 s = "-" + s
217 }
218 return s
219}