desk.gno
5.70 Kb · 208 lines
1// Package lastcall is a fully-collateralized 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
137func freshPrice(ticker string) int64 {
138 value, _ := GetPrice(ticker)
139 if !IsFresh(ticker) {
140 panic("desk: price is stale, last call has passed for " + ticker)
141 }
142 return value
143}
144
145// --- render ---
146
147func Render(path string) string {
148 out := "# LastCall\n\n"
149 out += "Synthetic stock desk: spot, perps, limit orders and a fee pool. Test funds only.\n\n"
150 out += "## Markets\n\n"
151 out += "| Ticker | Price (USD) | Quote | Supply | Long OI | Short OI |\n|---|---|---|---|---|---|\n"
152 for _, t := range tickers {
153 ps, quote := "-", "none"
154 if p, ok := prices[t]; ok {
155 ps = usdFmt(p.Value)
156 quote = "last call passed"
157 if IsFresh(t) {
158 quote = "live"
159 }
160 }
161 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]))
162 }
163 out += "\n## Desk\n\n"
164 out += ufmt.Sprintf("* tUSD total supply: %s\n", usdFmt(usd.TotalSupply()))
165 out += ufmt.Sprintf("* desk tUSD reserve: %s\n", usdFmt(usd.BalanceOf(deskAddr)))
166 out += ufmt.Sprintf("* fee pool: %s, cumulative fees %s\n", usdFmt(poolAssets), usdFmt(poolFeesAll))
167 out += ufmt.Sprintf("* open positions: %d, pending limits: %d\n", len(perps), len(limits))
168 out += ufmt.Sprintf("* a quote older than %d seconds stops every trade that moves value\n", maxPriceAge)
169 return out
170}
171
172// usdFmt formats micro-USD as a dollar string with two decimals.
173func usdFmt(micro int64) string {
174 neg := micro < 0
175 if neg {
176 micro = -micro
177 }
178 d := micro / 1000000
179 c := (micro % 1000000) / 10000
180 cs := ufmt.Sprintf("%d", c)
181 if len(cs) == 1 {
182 cs = "0" + cs
183 }
184 s := ufmt.Sprintf("$%d.%s", d, cs)
185 if neg {
186 s = "-" + s
187 }
188 return s
189}
190
191// sharesFmt formats a 6-decimal token amount as a share count.
192func sharesFmt(units int64) string {
193 neg := units < 0
194 if neg {
195 units = -units
196 }
197 d := units / 1000000
198 f := units % 1000000
199 fs := ufmt.Sprintf("%d", f)
200 for len(fs) < 6 {
201 fs = "0" + fs
202 }
203 s := ufmt.Sprintf("%d.%s", d, fs)
204 if neg {
205 s = "-" + s
206 }
207 return s
208}