// Package lastcall is a synthetic stocks desk on gno.land. // // It is self-contained: it runs its own price feed (an off-chain bot pushes // quotes from the desk key, trusted by caller address), issues a test-USD // collateral token and synthetic stock tokens, and lets users trade them spot // against the desk. There is no external oracle and no external liquidity — // the desk is always the counterparty at its own quoted price. // // All amounts are integers. USD values are micro-USD (6 decimals): // $190.42 -> 190420000. Token amounts use 6 decimals too, so one whole share // is 1_000000 units and lines up 1:1 with the price scale. package lastcall import ( "strconv" "strings" "time" "gno.land/p/nt/seqid/v0" "gno.land/p/nt/ufmt/v0" ) var ( admin address // deployer; may rotate admin and updater, seed the reserve updater address // the off-chain price bot deskAddr address // this realm's own address — the escrow / reserve account nextTokID seqid.ID // unique id source for every grc20 token this realm mints ) func init(cur realm) { admin = cur.Previous().Address() updater = admin deskAddr = cur.Address() initUSD(cur) // create the tUSD collateral token initStocks(cur) // create the default synthetic stock markets } // --- admin --- func SetAdmin(cur realm, a address) { assertAdmin(cur) if !a.IsValid() { panic("desk: invalid admin address") } admin = a } func SetUpdater(cur realm, u address) { assertAdmin(cur) if !u.IsValid() { panic("desk: invalid updater address") } updater = u } func Admin() address { return admin } func Updater() address { return updater } func DeskAddress() address { return deskAddr } func assertAdmin(cur realm) { if cur.Previous().Address() != admin { panic("desk: admin only") } } func assertUpdater(cur realm) { if cur.Previous().Address() != updater { panic("desk: updater only") } } // --- price feed (own oracle, caller-auth) --- // Price is quoted in micro-USD per whole share. type Price struct { Value int64 // micro-USD per share ObservedAt int64 // unix seconds observed off-chain by the bot } var prices = map[string]Price{} // SetPrice is pushed by the off-chain bot (updater key) for one ticker. func SetPrice(cur realm, ticker string, value int64, observedAt int64) { assertUpdater(cur) storePrice(ticker, value, observedAt) } // SetPrices stores several quotes in one transaction so the keeper pays one fee // per cycle. quotes is "TICKER:microUSD" pairs joined by ','. func SetPrices(cur realm, quotes string, observedAt int64) { assertUpdater(cur) for _, pair := range strings.Split(quotes, ",") { ticker, raw, ok := strings.Cut(pair, ":") value, err := strconv.ParseInt(raw, 10, 64) if !ok || err != nil { panic("desk: malformed quote: " + pair) } storePrice(ticker, value, observedAt) } } func storePrice(ticker string, value int64, observedAt int64) { _ = mustStock(ticker) if value <= 0 || value > maxPrice { panic("desk: price out of range") } if observedAt > time.Now().Unix()+maxClockSkew { panic("desk: observation is in the future") } if p, ok := prices[ticker]; ok && observedAt < p.ObservedAt { panic("desk: observation is older than the stored quote") } prices[ticker] = Price{Value: value, ObservedAt: observedAt} } // GetPrice returns the last quote for a ticker. Panics if unknown. func GetPrice(ticker string) (int64, int64) { p, ok := prices[ticker] if !ok { panic("desk: no price for " + ticker) } return p.Value, p.ObservedAt } const ( maxPriceAge = 600 maxClockSkew = 60 maxPrice = 1_000_000_000000 ) // IsFresh reports whether a ticker has a quote young enough to trade against. func IsFresh(ticker string) bool { p, ok := prices[ticker] return ok && time.Now().Unix()-p.ObservedAt <= maxPriceAge } // LastCallAt is the time after which the stored quote no longer allows a trade, // or 0 before the first quote. func LastCallAt(ticker string) int64 { p, ok := prices[ticker] if !ok { return 0 } return p.ObservedAt + maxPriceAge } func freshPrice(ticker string) int64 { value, _ := GetPrice(ticker) if !IsFresh(ticker) { panic("desk: price is stale, last call has passed for " + ticker) } return value } // --- render --- func Render(path string) string { out := "# LastCall\n\n" out += "Synthetic stock desk: spot, perps, limit orders and a fee pool. Test funds only.\n\n" out += "## Markets\n\n" out += "| Ticker | Price (USD) | Quote | Supply | Long OI | Short OI |\n|---|---|---|---|---|---|\n" for _, t := range tickers { ps, quote := "-", "none" if p, ok := prices[t]; ok { ps = usdFmt(p.Value) quote = "last call passed" if IsFresh(t) { quote = "live" } } 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])) } out += "\n## Desk\n\n" out += ufmt.Sprintf("* tUSD total supply: %s\n", usdFmt(usd.TotalSupply())) out += ufmt.Sprintf("* desk tUSD reserve: %s\n", usdFmt(usd.BalanceOf(deskAddr))) out += ufmt.Sprintf("* locked behind positions and orders: %s\n", usdFmt(lockedUSD)) out += ufmt.Sprintf("* fee pool: %s, cumulative fees %s\n", usdFmt(assetsNow()), usdFmt(poolFeesAll)) out += ufmt.Sprintf("* open positions: %d, pending limits: %d\n", perps.Size(), limits.Size()) out += ufmt.Sprintf("* a quote older than %d seconds stops every trade that moves value\n", maxPriceAge) return out } // usdFmt formats micro-USD as a dollar string with two decimals. func usdFmt(micro int64) string { neg := micro < 0 if neg { micro = -micro } d := micro / 1000000 c := (micro % 1000000) / 10000 cs := ufmt.Sprintf("%d", c) if len(cs) == 1 { cs = "0" + cs } s := ufmt.Sprintf("$%d.%s", d, cs) if neg { s = "-" + s } return s } // sharesFmt formats a 6-decimal token amount as a share count. func sharesFmt(units int64) string { neg := units < 0 if neg { units = -units } d := units / 1000000 f := units % 1000000 fs := ufmt.Sprintf("%d", f) for len(fs) < 6 { fs = "0" + fs } s := ufmt.Sprintf("%d.%s", d, fs) if neg { s = "-" + s } return s }