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.

desk.gno

6.18 Kb · 220 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 updater 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// SetPrices stores several quotes in one transaction so the keeper pays one fee
 83// per cycle. quotes is "TICKER:microUSD" pairs joined by ','.
 84func SetPrices(cur realm, quotes string, observedAt int64) {
 85	assertUpdater(cur)
 86	for _, pair := range strings.Split(quotes, ",") {
 87		ticker, raw, ok := strings.Cut(pair, ":")
 88		value, err := strconv.ParseInt(raw, 10, 64)
 89		if !ok || err != nil {
 90			panic("desk: malformed quote: " + pair)
 91		}
 92		storePrice(ticker, value, observedAt)
 93	}
 94}
 95
 96func storePrice(ticker string, value int64, observedAt int64) {
 97	_ = mustStock(ticker)
 98	if value <= 0 || value > maxPrice {
 99		panic("desk: price out of range")
100	}
101	if observedAt > time.Now().Unix()+maxClockSkew {
102		panic("desk: observation is in the future")
103	}
104	if p, ok := prices[ticker]; ok && observedAt < p.ObservedAt {
105		panic("desk: observation is older than the stored quote")
106	}
107	prices[ticker] = Price{Value: value, ObservedAt: observedAt}
108}
109
110// GetPrice returns the last quote for a ticker. Panics if unknown.
111func GetPrice(ticker string) (int64, int64) {
112	p, ok := prices[ticker]
113	if !ok {
114		panic("desk: no price for " + ticker)
115	}
116	return p.Value, p.ObservedAt
117}
118
119const (
120	maxPriceAge  = 600
121	maxClockSkew = 60
122	maxPrice     = 1_000_000_000000
123)
124
125// IsFresh reports whether a ticker has a quote young enough to trade against.
126func IsFresh(ticker string) bool {
127	p, ok := prices[ticker]
128	return ok && time.Now().Unix()-p.ObservedAt <= maxPriceAge
129}
130
131// LastCallAt is the time after which the stored quote no longer allows a trade,
132// or 0 before the first quote.
133func LastCallAt(ticker string) int64 {
134	p, ok := prices[ticker]
135	if !ok {
136		return 0
137	}
138	return p.ObservedAt + maxPriceAge
139}
140
141func freshPrice(ticker string) int64 {
142	value, _ := GetPrice(ticker)
143	if !IsFresh(ticker) {
144		panic("desk: price is stale, last call has passed for " + ticker)
145	}
146	return value
147}
148
149// --- render ---
150
151func Render(path string) string {
152	out := "# LastCall\n\n"
153	out += "Synthetic stock desk: spot, perps, limit orders and a fee pool. Test funds only.\n\n"
154	out += "## Markets\n\n"
155	out += "| Ticker | Price (USD) | Quote | Supply | Long OI | Short OI |\n|---|---|---|---|---|---|\n"
156	for _, t := range tickers {
157		ps, quote := "-", "none"
158		if p, ok := prices[t]; ok {
159			ps = usdFmt(p.Value)
160			quote = "last call passed"
161			if IsFresh(t) {
162				quote = "live"
163			}
164		}
165		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]))
166	}
167	out += "\n## Desk\n\n"
168	out += ufmt.Sprintf("* tUSD total supply: %s\n", usdFmt(usd.TotalSupply()))
169	out += ufmt.Sprintf("* desk tUSD reserve: %s\n", usdFmt(usd.BalanceOf(deskAddr)))
170	out += ufmt.Sprintf("* locked behind positions and orders: %s\n", usdFmt(lockedUSD))
171	out += ufmt.Sprintf("* fee pool: %s, cumulative fees %s\n", usdFmt(assetsNow()), usdFmt(poolFeesAll))
172	out += ufmt.Sprintf("* open positions: %d, pending limits: %d\n", perps.Size(), limits.Size())
173	out += ufmt.Sprintf("* a quote older than %d seconds stops every trade that moves value\n", maxPriceAge)
174	if marketOpen {
175		out += ufmt.Sprintf("* stock market open: new perps up to %dx\n", maxLeverage)
176	} else {
177		out += ufmt.Sprintf("* stock market closed: new perps up to %dx until the open\n", closedMaxLeverage)
178	}
179	out += "\n## Keys\n\n"
180	out += ufmt.Sprintf("* admin: %s\n* price updater: %s\n* desk reserve account: %s\n", admin.String(), updater.String(), deskAddr.String())
181	return out
182}
183
184// usdFmt formats micro-USD as a dollar string with two decimals.
185func usdFmt(micro int64) string {
186	neg := micro < 0
187	if neg {
188		micro = -micro
189	}
190	d := micro / 1000000
191	c := (micro % 1000000) / 10000
192	cs := ufmt.Sprintf("%d", c)
193	if len(cs) == 1 {
194		cs = "0" + cs
195	}
196	s := ufmt.Sprintf("$%d.%s", d, cs)
197	if neg {
198		s = "-" + s
199	}
200	return s
201}
202
203// sharesFmt formats a 6-decimal token amount as a share count.
204func sharesFmt(units int64) string {
205	neg := units < 0
206	if neg {
207		units = -units
208	}
209	d := units / 1000000
210	f := units % 1000000
211	fs := ufmt.Sprintf("%d", f)
212	for len(fs) < 6 {
213		fs = "0" + fs
214	}
215	s := ufmt.Sprintf("%d.%s", d, fs)
216	if neg {
217		s = "-" + s
218	}
219	return s
220}