Playground
collateral.gno
package lastcall
import "gno.land/p/nt/grc20/v0"
// tUSD is the test-USD collateral token. 6 decimals, so one tUSD unit is
// 1_000000 and token amounts line up 1:1 with micro-USD price quotes.
var (
usd *grc20.Token
usdLedger *grc20.PrivateLedger
)
func initUSD(cur realm) {
usd, usdLedger = grc20.NewToken("Test USD", "tUSD", 6, nextTokID.Next(), cur)
}
// FaucetUSD mints 10,000 tUSD to the caller. Open faucet — demo only.
func FaucetUSD(cur realm) {
caller := cur.Previous().Address()
if err := usdLedger.Mint(caller, 10_000_000000); err != nil {
panic(err.Error())
}
}
func BalanceUSD(owner address) int64 { return usd.BalanceOf(owner) }
cost.gno
package lastcall
// Spot cost basis. The desk records what each holder has paid for their current
// sStock position so the UI can show an average entry price and unrealized P&L on
// spot — the desk itself only needs balances, this is bookkeeping for the trader.
//
// spotCost[{owner,ticker}] is the total micro-USD paid (sum of price*units/1e6 at each
// buy, fee excluded), reduced pro-rata on every sell so the average per share is
// preserved. Plain stock transfers are not tracked (received shares carry no recorded
// cost); for a testnet desk that is acceptable.
type costKey struct {
owner address
ticker string
}
var spotCost = map[costKey]int64{}
// addCost records the tUSD notional (micro) a buyer paid toward their cost basis.
func addCost(owner address, ticker string, paid int64) {
spotCost[costKey{owner, ticker}] += paid
}
func costOf(owner address, ticker string) int64 { return spotCost[costKey{owner, ticker}] }
// reduceCost removes the cost of `sold` units from a holder whose balance BEFORE the
// sale was `heldBefore`, keeping the average per-share cost unchanged.
func reduceCost(owner address, ticker string, sold, heldBefore int64) {
if heldBefore <= 0 {
return
}
k := costKey{owner, ticker}
spotCost[k] -= mulDiv(spotCost[k], sold, heldBefore)
if spotCost[k] < 0 {
spotCost[k] = 0
}
}
// AvgEntry returns the owner's average entry price for ticker in micro-USD per share,
// or 0 if they hold none.
func AvgEntry(ticker string, owner address) int64 {
held := mustStock(ticker).token.BalanceOf(owner)
if held <= 0 {
return 0
}
cost := spotCost[costKey{owner, ticker}]
return mulDiv(cost, microUSD, held)
}
delever.gno
package lastcall
// Last call before the close. A stock can gap between the close and the next
// open while the desk price stands still, and with isolated margin a losing
// position stops at its margin while the winning one is paid in full. An equal
// long and short at 10x would then earn from any gap beyond 10% at the desk's
// expense. So while the market is closed no position may stay above
// closedMaxLeverage: anyone (in practice the keeper) may cut one down to it with
// Delever. The cut part is settled like a close, and what it returns stays in
// the position as margin. AddMargin lets an owner keep the full size instead.
import (
"time"
"gno.land/p/nt/ufmt/v0"
)
// AddMargin adds `amount` tUSD micro from the caller to their own position,
// lowering its leverage. It trades nothing, so it applies at once.
func AddMargin(cur realm, id uint64, amount int64) {
p := mustPerp(id)
owner := cur.Previous().Address()
if p.owner != owner {
panic("desk: not your position")
}
if amount <= 0 || p.margin+amount > maxMargin {
panic("desk: margin out of range")
}
pull(owner, amount)
lock(amount)
p.margin += amount
emitPerp("MarginAdd", p, "usd", num(amount), "margin", num(p.margin))
}
func overLeveraged(p *perp, mark int64) bool {
return notionalMicroUSD(mark, p.size) > p.margin*closedMaxLeverage
}
// Delever cuts a position held above closedMaxLeverage while the market is
// closed, at the desk price, to the size its margin carries at that leverage.
// Permissionless.
func Delever(cur realm, id uint64) {
if marketOpen {
panic("desk: the market is open")
}
p := mustPerp(id)
mark := freshPrice(p.ticker)
if !overLeveraged(p, mark) {
panic("desk: within the closed-market leverage")
}
if payout, _, _, _ := sliceSettle(p, p.size, mark, time.Now().Unix()); payout > freeReserve()+p.margin {
panic("desk: the reserve cannot pay this cut in full right now")
}
if cut := deleverSize(p, mark, time.Now().Unix()); cut < p.size {
cutToMargin(p, cut, mark)
if !overLeveraged(p, mark) {
return
}
}
settlePerp(p, mark, "delever")
}
func deleverSize(p *perp, mark, now int64) int64 {
notional := notionalMicroUSD(mark, p.size)
pnl := perpPnL(p, mark)
fee := mulDiv(notional, perpFeeBps, bpsDenom)
gain := pnl - fee - holdingFee(p, now)
room := notional + closedMaxLeverage*gain
if room <= 0 {
return p.size
}
cut := mulDiv(notional-closedMaxLeverage*p.margin, p.size, room) + 1
if cut < minTradeUnits {
cut = minTradeUnits
}
if cut > p.size {
return p.size
}
return cut
}
func cutToMargin(p *perp, sz, mark int64) {
payout, fee, hold, marginSlice := sliceSettle(p, sz, mark, time.Now().Unix())
unlock(marginSlice)
if free := freeReserve(); payout > free {
payout = free
}
lock(payout)
accrueFee(collectedFee(p, sz, mark, marginSlice, fee+hold))
subOI(p.ticker, p.isLong, notionalMicroUSD(p.entry, sz))
emitPerpClose(p, "delever", sz, mark, payout)
p.size -= sz
p.margin = p.margin - marginSlice + payout
}
// Overleveraged lists, within one page of open positions, the ids Delever would
// cut now, ';'-joined, for the keeper. Empty while the market is open.
func Overleveraged(offset, count int) string {
out := ""
if marketOpen {
return out
}
eachPage(perps, offset, count, func(item any) {
p := item.(*perp)
if !IsFresh(p.ticker) {
return
}
if mark, _ := GetPrice(p.ticker); overLeveraged(p, mark) {
out = joinRow(out, ufmt.Sprintf("%d", p.id))
}
})
return out
}
desk.gno
// Package lastcall is a synthetic stocks desk on gno.land.
//
// It is self-contained: it runs its own price feed (off-chain updaters push
// quotes, trusted by caller address, see feed.gno), 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 (
"gno.land/p/nt/seqid/v0"
"gno.land/p/nt/ufmt/v0"
)
var (
admin address // deployer; may rotate admin, manage updaters, seed the reserve
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()
updaters = []address{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 Admin() address { return admin }
func DeskAddress() address { return deskAddr }
func assertAdmin(cur realm) {
if cur.Previous().Address() != admin {
panic("desk: admin only")
}
}
// --- 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 orders: %d\n", perps.Size(), orders.Size())
out += ufmt.Sprintf("* a price older than %d seconds stops every trade that moves value\n", maxPriceAge)
out += "* every trade fills on the first price observed after it was placed\n"
if marketOpen {
out += ufmt.Sprintf("* stock market open: new perps up to %dx\n", maxLeverage)
} else {
out += ufmt.Sprintf("* stock market closed: new perps up to %dx until the open, positions above it are cut to it\n", closedMaxLeverage)
}
out += "\n## Keys\n\n"
out += ufmt.Sprintf("* admin: %s\n* desk reserve account: %s\n", admin.String(), deskAddr.String())
out += ufmt.Sprintf("* price updaters, %d must agree: %s\n", quorum, Updaters())
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
}
events.gno
package lastcall
// Every trade emits a chain event, so an indexer, gnoweb or an agent can rebuild
// an account's history without replaying the realm's state. Amounts are
// integers at 6 dp, like the rest of the desk.
import (
"chain"
"strconv"
)
func num(v int64) string { return strconv.FormatInt(v, 10) }
func ref(v uint64) string { return strconv.FormatUint(v, 10) }
func sideOf(isLong bool) string {
if isLong {
return "L"
}
return "S"
}
func emitSpot(kind string, owner address, ticker string, size, price, usd int64) {
chain.Emit(kind, "owner", owner.String(), "ticker", ticker, "size", num(size), "price", num(price), "usd", num(usd))
}
func emitPerpOpen(p *perp) {
chain.Emit("PerpOpen", "owner", p.owner.String(), "id", ref(p.id), "ticker", p.ticker, "side", sideOf(p.isLong),
"size", num(p.size), "price", num(p.entry), "margin", num(p.margin))
}
func emitPerpClose(p *perp, kind string, size, mark, payout int64) {
chain.Emit("PerpClose", "owner", p.owner.String(), "id", ref(p.id), "ticker", p.ticker, "side", sideOf(p.isLong),
"size", num(size), "price", num(mark), "usd", num(payout), "kind", kind)
}
func emitOrder(kind string, o *order, extra ...string) {
attrs := []string{"owner", o.owner.String(), "id", ref(o.id), "kind", o.kind, "ticker", o.ticker, "side", sideOf(o.isLong),
"size", num(o.size), "price", num(o.limit), "margin", num(o.margin)}
chain.Emit(kind, append(attrs, extra...)...)
}
func emitPerp(kind string, p *perp, extra ...string) {
attrs := []string{"owner", p.owner.String(), "id", ref(p.id), "ticker", p.ticker, "side", sideOf(p.isLong)}
chain.Emit(kind, append(attrs, extra...)...)
}
func emitPool(kind string, owner address, usd, shares int64) {
chain.Emit(kind, "owner", owner.String(), "usd", num(usd), "shares", num(shares))
}
feed.gno
package lastcall
// The price feed. Off-chain updaters push quotes; the desk trusts them by
// address, so no single one sets a price alone once the quorum is above one.
//
// Each updater's latest quote is kept per ticker. A desk price is formed when a
// quorum of updaters have quoted after the current desk price, within
// quoteWindow of the newest of those quotes and within agreeBps of their
// median: the median of those quotes, stamped with the oldest observation it
// used. A quote far from the others is left out, so one updater can delay a
// price but not move it beyond the band. Every input to a price was observed at
// or after that stamp, which is what lets an order placed at time t fill only
// on a price observed after t (pricedAfter).
//
// Market hours follow the same rule: the market counts as open only while a
// quorum of updaters say it is.
import (
"strconv"
"strings"
"time"
)
// Price is quoted in micro-USD per whole share.
type Price struct {
Value int64 // micro-USD per share
ObservedAt int64 // unix seconds, the oldest observation behind this price
}
const (
maxPriceAge = 600
maxClockSkew = 60
maxPrice = 1_000_000_000000
quoteWindow = 120
agreeBps = 100
maxUpdaters = 7
)
var (
updaters []address
quorum = 1
prices = map[string]Price{}
submitted = map[string]map[address]Price{}
openVotes = map[address]bool{}
marketOpen = true
openedAt int64
)
// --- updaters (admin) ---
func AddUpdater(cur realm, u address) {
assertAdmin(cur)
if !u.IsValid() {
panic("desk: invalid updater address")
}
if isUpdater(u) {
panic("desk: already an updater")
}
if len(updaters) >= maxUpdaters {
panic("desk: too many updaters")
}
updaters = append(updaters, u)
}
func RemoveUpdater(cur realm, u address) {
assertAdmin(cur)
if !isUpdater(u) {
panic("desk: not an updater")
}
if len(updaters)-1 < quorum {
panic("desk: lower the quorum first")
}
kept := []address{}
for _, a := range updaters {
if a != u {
kept = append(kept, a)
}
}
updaters = kept
delete(openVotes, u)
for _, subs := range submitted {
delete(subs, u)
}
tallyMarket()
}
func SetQuorum(cur realm, n int) {
assertAdmin(cur)
if n < 1 || n > len(updaters) {
panic("desk: quorum out of range")
}
quorum = n
tallyMarket()
}
// Updaters lists the updater addresses, comma-separated.
func Updaters() string {
out := ""
for i, u := range updaters {
if i > 0 {
out += ","
}
out += u.String()
}
return out
}
func Quorum() int { return quorum }
func isUpdater(a address) bool {
for _, u := range updaters {
if u == a {
return true
}
}
return false
}
func assertUpdater(cur realm) address {
from := cur.Previous().Address()
if !isUpdater(from) {
panic("desk: updater only")
}
return from
}
// --- quotes ---
// SetPrices records the caller's quotes, "TICKER:microUSD" pairs joined by ',',
// all observed at observedAt, and forms a desk price where a quorum agrees. A
// stamp ahead of the block time is lowered to it, so no price is ever dated
// after a request that could already see it.
func SetPrices(cur realm, quotes string, observedAt int64) {
from := assertUpdater(cur)
now := time.Now().Unix()
if observedAt > now+maxClockSkew {
panic("desk: observation is in the future")
}
if observedAt > now {
observedAt = now
}
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)
}
submit(from, ticker, value, observedAt)
}
}
func submit(from address, ticker string, value, observedAt int64) {
_ = mustStock(ticker)
if value <= 0 || value > maxPrice {
panic("desk: price out of range")
}
subs := submitted[ticker]
if subs == nil {
subs = map[address]Price{}
submitted[ticker] = subs
}
if prev, ok := subs[from]; ok && observedAt < prev.ObservedAt {
panic("desk: observation is older than your last quote")
}
subs[from] = Price{Value: value, ObservedAt: observedAt}
aggregate(ticker)
}
func aggregate(ticker string) {
since := int64(-1)
if p, ok := prices[ticker]; ok {
since = p.ObservedAt
}
fresh := []Price{}
newest := int64(0)
for _, u := range updaters {
q, ok := submitted[ticker][u]
if !ok || q.ObservedAt <= since {
continue
}
fresh = append(fresh, q)
if q.ObservedAt > newest {
newest = q.ObservedAt
}
}
quotes := []Price{}
vals := []int64{}
for _, q := range fresh {
if newest-q.ObservedAt <= quoteWindow {
quotes = append(quotes, q)
vals = append(vals, q.Value)
}
}
if len(vals) < quorum {
return
}
mid := median(vals)
band := mulDiv(mid, agreeBps, bpsDenom)
agreed := []int64{}
oldest := newest
for _, q := range quotes {
if q.Value < mid-band || q.Value > mid+band {
continue
}
agreed = append(agreed, q.Value)
if q.ObservedAt < oldest {
oldest = q.ObservedAt
}
}
if len(agreed) < quorum {
return
}
prices[ticker] = Price{Value: median(agreed), ObservedAt: oldest}
}
func median(vals []int64) int64 {
s := append([]int64{}, vals...)
for i := 1; i < len(s); i++ {
for j := i; j > 0 && s[j] < s[j-1]; j-- {
s[j], s[j-1] = s[j-1], s[j]
}
}
m := len(s) / 2
if len(s)%2 == 1 {
return s[m]
}
return s[m-1] + (s[m]-s[m-1])/2
}
// GetPrice returns the desk price for a ticker and its observation time. 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
}
// IsFresh reports whether a ticker has a price 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 price no longer allows a trade,
// or 0 before the first price.
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
}
// pricedAfter reports whether the ticker's price was observed after t, so a
// request made at t may fill on it.
func pricedAfter(ticker string, t int64) bool {
p, ok := prices[ticker]
return ok && p.ObservedAt > t
}
// --- market hours ---
// SetMarketOpen records the caller's view of the US stock market.
func SetMarketOpen(cur realm, open bool) {
from := assertUpdater(cur)
openVotes[from] = open
tallyMarket()
}
// MarketVoteOf returns an updater's recorded view of the market: "open",
// "closed" or "none".
func MarketVoteOf(u address) string {
open, ok := openVotes[u]
switch {
case !ok:
return "none"
case open:
return "open"
}
return "closed"
}
func tallyMarket() {
if len(openVotes) == 0 {
return
}
n := 0
for _, u := range updaters {
if openVotes[u] {
n++
}
}
was := marketOpen
marketOpen = n >= quorum
if marketOpen && !was {
openedAt = time.Now().Unix()
}
}
// IsMarketOpen reports whether a quorum of updaters say the stock market is open.
// While it is not, new perps are held to closedMaxLeverage and positions above it
// can be cut down to it (Delever). A limit above that leverage fills only on a
// price observed after the open, never on the last pre-open quote.
func IsMarketOpen() bool { return marketOpen }
gnomod.toml
module = "gno.land/r/g1p8v5lkq5mqp7r8h8stcv4fgrwrx3zupvww9m85/lastcall/v4" gno = "0.9" [addpkg] creator = "g1p8v5lkq5mqp7r8h8stcv4fgrwrx3zupvww9m85" height = 1651863 max_deposit = "100000000ugnot"
index.gno
package lastcall
// Open positions and pending orders live in ordered trees, globally and per
// owner, so list reads walk only what is open and the keeper can page them.
import (
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/seqid/v0"
)
const maxPage = 200
var (
perps = avl.NewTree()
ownerPerps = avl.NewTree()
orders = avl.NewTree()
ownerOrders = avl.NewTree()
)
func idKey(id uint64) string { return seqid.ID(id).String() }
func ownerTree(index *avl.Tree, owner address) *avl.Tree {
if v := index.Get(owner.String()); v != nil {
return v.(*avl.Tree)
}
t := avl.NewTree()
index.Set(owner.String(), t)
return t
}
func putItem(all, index *avl.Tree, owner address, id uint64, item any) {
all.Set(idKey(id), item)
ownerTree(index, owner).Set(idKey(id), item)
}
func dropItem(all, index *avl.Tree, owner address, id uint64) {
all.Remove(idKey(id))
t := ownerTree(index, owner)
t.Remove(idKey(id))
if t.Size() == 0 {
index.Remove(owner.String())
}
}
func eachOwned(index *avl.Tree, owner address, cb func(item any)) {
v := index.Get(owner.String())
if v == nil {
return
}
v.(*avl.Tree).Iterate("", "", func(_ string, item any) bool {
cb(item)
return false
})
}
func eachPage(all *avl.Tree, offset, count int, cb func(item any)) {
if offset < 0 || count <= 0 {
return
}
if count > maxPage {
count = maxPage
}
all.IterateByOffset(offset, count, func(_ string, item any) bool {
cb(item)
return false
})
}
func joinRow(out, row string) string {
if out == "" {
return row
}
return out + ";" + row
}
// OpenPerpCount and OrderCount tell the keeper how many pages to read.
func OpenPerpCount() int { return perps.Size() }
func OrderCount() int { return orders.Size() }
math.gno
package lastcall
import "math/bits"
const maxInt64 = uint64(1<<63 - 1)
func mulDiv(a, b, c int64) int64 {
if a < 0 || b < 0 || c <= 0 {
panic("desk: math domain")
}
hi, lo := bits.Mul64(uint64(a), uint64(b))
if hi >= uint64(c) {
panic("desk: math overflow")
}
q, _ := bits.Div64(hi, lo, uint64(c))
if q > maxInt64 {
panic("desk: math overflow")
}
return int64(q)
}
orders.gno
package lastcall
// Every trade is an order that fills on the first desk price observed after it
// was placed. The desk price is pushed every minute or so; without this rule a
// trader who watches the real market could trade on a quote they already know
// to be stale.
//
// Kinds: "market" and "limit" open a perp, "buy" and "sell" trade spot. Money is
// taken when the order is placed (margin and fee, or the spot cost at the worst
// price the order accepts; a sell burns the shares), so filling needs no
// signature from the owner. Filling is permissionless: the keeper fills orders
// right after each price, and anyone else may.
//
// A market order, buy or sell accepts a price up to marketBandBps worse than the
// one it saw. If the next price is past that, or no new price comes within
// orderTTL, it is refunded in full. A limit waits until its price is reached and
// can be cancelled, except while it is fillable.
import (
"time"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/ufmt/v0"
)
const (
marketBandBps = 200
orderTTL = 900
)
type order struct {
id uint64
owner address
kind string
ticker string
isLong bool
size int64
margin int64
fee int64
limit int64
basis int64
placedAt int64
}
var (
nextOrderID uint64
results = avl.NewTree()
)
func mustOrder(id uint64) *order {
v := orders.Get(idKey(id))
if v == nil {
panic("desk: unknown order")
}
return v.(*order)
}
func isPerpOrder(o *order) bool { return o.kind == "market" || o.kind == "limit" }
func bandPrice(mark int64, worseUp bool) int64 {
if worseUp {
return mulDiv(mark, bpsDenom+marketBandBps, bpsDenom)
}
return mulDiv(mark, bpsDenom-marketBandBps, bpsDenom)
}
func pull(from address, amount int64) {
if err := usdLedger.Transfer(from, deskAddr, amount); err != nil {
panic(err.Error())
}
}
func pay(to address, amount int64) {
if amount <= 0 {
return
}
if err := usdLedger.Transfer(deskAddr, to, amount); err != nil {
panic(err.Error())
}
}
func queue(o *order) uint64 {
nextOrderID++
o.id = nextOrderID
o.placedAt = time.Now().Unix()
putItem(orders, ownerOrders, o.owner, o.id, o)
emitOrder("OrderPlace", o)
return o.id
}
// --- placing ---
// OpenPerp places a market order for a long or short of `size` stock units
// (6 dp) backed by `margin` tUSD micro, plus the open fee. It fills on the next
// price if that is within marketBandBps of the price now, else it is refunded.
// Returns the order id; the position id comes with the OrderFill event.
func OpenPerp(cur realm, ticker string, isLong bool, size int64, margin int64) uint64 {
return openMarket(cur.Previous().Address(), ticker, isLong, size, margin)
}
func openMarket(owner address, ticker string, isLong bool, size, margin int64) uint64 {
mark := freshPrice(ticker)
return placePerp(owner, "market", ticker, isLong, size, margin, bandPrice(mark, isLong), mark, maxLevOf(ticker))
}
// PlaceLimit places an order to open a perp once the desk price reaches `limit`
// (long: at or below, short: at or above). Returns the order id.
func PlaceLimit(cur realm, ticker string, isLong bool, size, margin, limit int64) uint64 {
_, _ = GetPrice(ticker)
if limit <= 0 || limit > maxPrice {
panic("desk: limit price out of range")
}
return placePerp(cur.Previous().Address(), "limit", ticker, isLong, size, margin, limit, limit, openLevOf(ticker))
}
func placePerp(owner address, kind, ticker string, isLong bool, size, margin, limit, ref, lev int64) uint64 {
_ = mustStock(ticker)
assertPerpSize(size)
assertMargin(margin)
notional := notionalMicroUSD(ref, size)
if notional <= 0 || notional > perpMaxNotional {
panic("desk: notional out of range")
}
if notional > margin*lev {
panic("desk: over this market's max leverage")
}
if kind == "market" && sideOI(ticker, isLong)+notional > oiCap(ticker) {
panic("desk: open-interest cap reached for this side")
}
fee := mulDiv(notional, perpFeeBps, bpsDenom)
pull(owner, margin+fee)
lock(margin + fee)
return queue(&order{owner: owner, kind: kind, ticker: ticker, isLong: isLong, size: size, margin: margin, fee: fee, limit: limit})
}
// Buy places an order for stockAmount units (6 dp) of sTicker. It locks the cost
// at the worst price it accepts and refunds the difference when it fills.
// Returns the order id.
func Buy(cur realm, ticker string, stockAmount int64) uint64 {
assertTradeSize(stockAmount)
_ = mustStock(ticker)
limit := bandPrice(freshPrice(ticker), true)
cost := mulDiv(notionalMicroUSD(limit, stockAmount), bpsDenom+feeBps, bpsDenom)
if cost <= 0 {
panic("desk: trade too small")
}
owner := cur.Previous().Address()
pull(owner, cost)
lock(cost)
return queue(&order{owner: owner, kind: "buy", ticker: ticker, isLong: true, size: stockAmount, margin: cost, limit: limit})
}
// Sell places an order to sell stockAmount units of sTicker. The shares are
// burned now and minted back if the order is refunded. Returns the order id.
func Sell(cur realm, ticker string, stockAmount int64) uint64 {
assertTradeSize(stockAmount)
s := mustStock(ticker)
mark := freshPrice(ticker)
if mulDiv(notionalMicroUSD(mark, stockAmount), bpsDenom-feeBps, bpsDenom) > freeReserve() {
panic("desk: the reserve cannot cover this sale right now")
}
owner := cur.Previous().Address()
held := s.token.BalanceOf(owner)
if err := s.ledger.Burn(owner, stockAmount); err != nil {
panic(err.Error())
}
basis := costOf(owner, ticker)
reduceCost(owner, ticker, stockAmount, held)
return queue(&order{owner: owner, kind: "sell", ticker: ticker, size: stockAmount, limit: bandPrice(mark, false), basis: basis - costOf(owner, ticker)})
}
// CancelOrder refunds the caller's pending limit order. Market orders, buys and
// sells cannot be cancelled: they fill or are refunded on the next price.
func CancelOrder(cur realm, id uint64) {
o := mustOrder(id)
if o.owner != cur.Previous().Address() {
panic("desk: not your order")
}
if o.kind != "limit" {
panic("desk: this order fills or is refunded on the next price")
}
if fillable(o) {
panic("desk: this order fills at the current price, it cannot be cancelled now")
}
refund(o, "cancel")
}
// --- filling ---
// FillOrder executes an order on the first price observed after it was placed,
// or refunds a market order, buy or sell that the price moved past or that
// waited longer than orderTTL. Permissionless. Returns the new position id for
// a perp order that filled, otherwise 0.
func FillOrder(cur realm, id uint64) uint64 { return fillOrder(id) }
func fillOrder(id uint64) uint64 {
o := mustOrder(id)
if o.kind != "limit" && time.Now().Unix()-o.placedAt > orderTTL {
refund(o, "expired")
return 0
}
if !pricedAfter(o.ticker, o.placedAt) {
panic("desk: the order waits for the next price")
}
mark := freshPrice(o.ticker)
switch o.kind {
case "buy":
fillBuy(o, mark)
return 0
case "sell":
fillSell(o, mark)
return 0
}
return fillPerp(o, mark)
}
func limitReady(o *order, mark int64) bool {
if o.isLong {
return mark <= o.limit
}
return mark >= o.limit
}
func waitsForOpen(o *order) bool {
if o.kind != "limit" || notionalMicroUSD(o.limit, o.size) <= o.margin*closedMaxLeverage {
return false
}
return !marketOpen || !pricedAfter(o.ticker, openedAt)
}
type perpFill struct {
size, margin, fee, back, notional int64
}
func quotePerp(o *order, mark int64) (perpFill, string) {
if !limitReady(o, mark) {
return perpFill{}, "price moved"
}
f := perpFill{}
f.size, f.margin, f.fee, f.back = limitFill(o, mark)
f.notional = notionalMicroUSD(mark, f.size)
switch {
case !limitReady(o, skewEntry(mark, skewImpactBps(o.ticker, o.isLong, f.notional), o.isLong)):
return f, "skew impact moves the fill past the limit"
case f.size < minTradeUnits || f.margin <= 0:
return f, "size below minimum"
case sideOI(o.ticker, o.isLong)+f.notional > oiCap(o.ticker):
return f, "open-interest cap"
}
return f, ""
}
func fillable(o *order) bool {
if !pricedAfter(o.ticker, o.placedAt) || !IsFresh(o.ticker) || waitsForOpen(o) {
return false
}
mark, _ := GetPrice(o.ticker)
_, why := quotePerp(o, mark)
return why == ""
}
func fillPerp(o *order, mark int64) uint64 {
if waitsForOpen(o) {
panic("desk: this order's leverage waits for a price after the open")
}
f, why := quotePerp(o, mark)
if why != "" {
if o.kind == "limit" {
panic("desk: the limit does not fill at this price: " + why)
}
refund(o, why)
return 0
}
unlock(o.margin + o.fee)
pay(o.owner, f.back)
pid := openPositionCore(o.owner, o.ticker, o.isLong, f.size, f.margin, mark, f.fee)
done(o, "filled:"+ref(pid))
emitOrder("OrderFill", o, "position", ref(pid), "fill", num(mark))
return pid
}
func fillSize(o *order, mark int64) int64 {
maxNotional := o.margin * maxLevOf(o.ticker)
if maxNotional > perpMaxNotional {
maxNotional = perpMaxNotional
}
if notionalMicroUSD(mark, o.size) <= maxNotional {
return o.size
}
return mulDiv(maxNotional, microUSD, mark)
}
func limitFill(o *order, mark int64) (size, margin, fee, refund int64) {
size = fillSize(o, mark)
fee = mulDiv(notionalMicroUSD(mark, size), perpFeeBps, bpsDenom)
if fee <= o.fee {
return size, o.margin, fee, o.fee - fee
}
lev := maxLevOf(o.ticker)
maxNotional := mulDiv((o.margin+o.fee)*lev, bpsDenom, bpsDenom+lev*perpFeeBps)
if notionalMicroUSD(mark, size) > maxNotional {
size = mulDiv(maxNotional, microUSD, mark)
fee = mulDiv(notionalMicroUSD(mark, size), perpFeeBps, bpsDenom)
}
if fee <= o.fee {
return size, o.margin, fee, o.fee - fee
}
return size, o.margin - (fee - o.fee), fee, 0
}
func fillBuy(o *order, mark int64) {
if mark > o.limit {
refund(o, "price moved")
return
}
notional := notionalMicroUSD(mark, o.size)
cost := mulDiv(notional, bpsDenom+feeBps, bpsDenom)
unlock(o.margin)
pay(o.owner, o.margin-cost)
if err := mustStock(o.ticker).ledger.Mint(o.owner, o.size); err != nil {
panic(err.Error())
}
addCost(o.owner, o.ticker, notional)
accrueFee(cost - notional)
done(o, "filled")
emitSpot("Buy", o.owner, o.ticker, o.size, mark, cost)
emitOrder("OrderFill", o, "fill", num(mark))
}
func fillSell(o *order, mark int64) {
if mark < o.limit {
refund(o, "price moved")
return
}
notional := notionalMicroUSD(mark, o.size)
proceeds := mulDiv(notional, bpsDenom-feeBps, bpsDenom)
if proceeds > freeReserve() {
refund(o, "reserve")
return
}
pay(o.owner, proceeds)
accrueFee(notional - proceeds)
done(o, "filled")
emitSpot("Sell", o.owner, o.ticker, o.size, mark, proceeds)
emitOrder("OrderFill", o, "fill", num(mark))
}
func refund(o *order, reason string) {
if o.kind == "sell" {
if err := mustStock(o.ticker).ledger.Mint(o.owner, o.size); err != nil {
panic(err.Error())
}
addCost(o.owner, o.ticker, o.basis)
} else {
unlock(o.margin + o.fee)
pay(o.owner, o.margin+o.fee)
}
done(o, "refunded:"+reason)
emitOrder("OrderRefund", o, "reason", reason)
}
func done(o *order, result string) {
dropItem(orders, ownerOrders, o.owner, o.id)
results.Set(idKey(o.id), result)
}
// --- reads ---
// OrderStatus is "pending", "filled", "filled:<position id>" for a perp order,
// "refunded:<reason>", or "unknown".
func OrderStatus(id uint64) string {
if orders.Has(idKey(id)) {
return "pending"
}
if v := results.Get(idKey(id)); v != nil {
return v.(string)
}
return "unknown"
}
// OrdersOf returns an owner's pending orders, ';'-joined, fields comma-separated:
// id,kind,ticker,L|S,size,margin,limit,mark,placedAt (money and size at 6 dp).
func OrdersOf(owner address) string {
out := ""
eachOwned(ownerOrders, owner, func(item any) {
o := item.(*order)
mark, _ := GetPrice(o.ticker)
out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%s,%d,%d,%d,%d,%d", o.id, o.kind, o.ticker, sideOf(o.isLong), o.size, o.margin, o.limit, mark, o.placedAt))
})
return out
}
// ReadyOrders lists, within one page of pending orders, the ids FillOrder would
// act on now, ';'-joined, for the keeper.
func ReadyOrders(offset, count int) string {
out := ""
now := time.Now().Unix()
eachPage(orders, offset, count, func(item any) {
o := item.(*order)
expired := o.kind != "limit" && now-o.placedAt > orderTTL
ready := pricedAfter(o.ticker, o.placedAt) && IsFresh(o.ticker)
if o.kind == "limit" {
ready = fillable(o)
}
if expired || ready {
out = joinRow(out, ufmt.Sprintf("%d", o.id))
}
})
return out
}
perp.gno
package lastcall
// Perpetual stock positions against the desk. Isolated margin, the desk is the
// counterparty. Margin is tUSD locked in the desk reserve; profit is paid from
// the reserve on close, loss is kept by the desk, both capped at the margin
// (isolated). Mark price = the desk reference price (same feed as spot), so
// there is no perp-vs-spot basis and no funding in this version.
//
// All money is micro-USD (6 dp); size is stock units (6 dp), like spot.
import (
"time"
"gno.land/p/nt/ufmt/v0"
)
const (
perpFeeBps = 10 // 0.10% of notional, each side (open + close)
maxLeverage = 10 // 10x: notional <= margin * 10
maintBps = 1000 // 10% maintenance: liquidatable when equity <= 10% of margin
minMargin = 1_000000 // $1 minimum margin, blocks dust
perpMaxNotional = 1_000_000_000000 // $1,000,000 notional cap
maxMargin = 1_000_000_000000
holdRateBpsYear = 1000 // 10%/yr borrow fee on notional while a position is open
secondsYear = 31_536_000 // 365d, for prorating the borrow fee
)
type perp struct {
id uint64
owner address
ticker string
isLong bool
size int64 // stock units (6 dp), > 0
entry int64 // micro-USD per share at open
margin int64 // tUSD micro locked for this position
openTime int64 // block time at open (unix seconds), for the borrow fee
stopLoss int64 // optional stop-loss trigger, micro-USD/share (0 = unset)
takeProfit int64 // optional take-profit trigger, micro-USD/share (0 = unset)
stopsAt int64 // when the stops were last set; they trigger only on a later price
closeSize int64 // size of a requested close, 0 for all of it
closeAt int64 // when a close was requested, 0 when none is waiting
}
var nextPerpID uint64
func mustPerp(id uint64) *perp {
v := perps.Get(idKey(id))
if v == nil {
panic("desk: unknown perp id")
}
return v.(*perp)
}
// perpPnL is size * (mark - entry) / 1e6 for a long, negated for a short.
func perpPnL(p *perp, mark int64) int64 {
pnl := notionalMicroUSD(mark, p.size) - notionalMicroUSD(p.entry, p.size)
if !p.isLong {
pnl = -pnl
}
return pnl
}
// equity is the position's margin plus unrealized PnL.
func perpEquity(p *perp, mark int64) int64 { return p.margin + perpPnL(p, mark) }
// liquidatable: equity net of the accrued borrow fee has fallen to the
// maintenance fraction of the margin.
func liquidatable(p *perp, mark int64) bool {
return perpEquity(p, mark)-holdingFee(p, time.Now().Unix()) <= mulDiv(p.margin, maintBps, bpsDenom)
}
// liqPrice is the mark price at which the position becomes liquidatable.
func liqPrice(p *perp) int64 {
// allowed loss before maintenance = margin * (1 - maintBps/1e4)
allowedLoss := mulDiv(p.margin, bpsDenom-maintBps, bpsDenom) - holdingFee(p, time.Now().Unix())
var drop int64 // micro-USD per share
if allowedLoss >= 0 {
drop = mulDiv(allowedLoss, microUSD, p.size)
} else {
drop = -mulDiv(-allowedLoss, microUSD, p.size)
}
if p.isLong {
return p.entry - drop
}
return p.entry + drop
}
// assertPerpSize bounds the size so price*size stays inside int64.
func assertPerpSize(size int64) {
if size < minTradeUnits {
panic("desk: size below minimum (0.001 share)")
}
if size > maxTradeUnits {
panic("desk: size above maximum (10,000 shares)")
}
}
func assertMargin(margin int64) {
if margin < minMargin {
panic("desk: margin below minimum ($1)")
}
if margin > maxMargin {
panic("desk: margin above maximum ($1,000,000)")
}
}
// openPositionCore validates and creates a perp, assuming `margin`+`fee` tUSD are
// ALREADY in the desk reserve and not locked. Called when a perp order fills
// (FillOrder). A panic here reverts the whole tx, so nothing is stranded.
func openPositionCore(owner address, ticker string, isLong bool, size, margin, price, fee int64) uint64 {
assertPerpSize(size)
notional := notionalMicroUSD(price, size)
if notional <= 0 || notional > perpMaxNotional {
panic("desk: notional out of range")
}
if margin <= 0 || notional > margin*maxLevOf(ticker) {
panic("desk: over this market's max leverage")
}
if sideOI(ticker, isLong)+notional > oiCap(ticker) {
panic("desk: open-interest cap reached for this side")
}
// skew-priced entry on the pre-trade open interest.
entry := skewEntry(price, skewImpactBps(ticker, isLong, notional), isLong)
accrueFee(fee) // open fee -> liquidity pool yield
nextPerpID++
id := nextPerpID
p := &perp{
id: id, owner: owner, ticker: ticker, isLong: isLong,
size: size, entry: entry, margin: margin,
openTime: time.Now().Unix(),
}
putItem(perps, ownerPerps, owner, id, p)
lock(margin)
emitPerpOpen(p)
// OI is tracked at entry-notional (same basis subOI uses on close) so skew
// impact doesn't silently drift the open-interest sum across many trades.
addOI(ticker, isLong, notionalMicroUSD(entry, size))
return id
}
// ClosePerp asks to close the caller's whole position. It closes on the first
// price observed after the request (FillClose).
func ClosePerp(cur realm, id uint64) { requestClose(cur.Previous().Address(), id, 0) }
// ClosePartial asks to close `closeSize` units (6 dp) of the caller's position on
// the first price observed after the request. Allowed while the market is closed.
func ClosePartial(cur realm, id uint64, closeSize int64) {
if closeSize <= 0 {
panic("desk: invalid close size")
}
requestClose(cur.Previous().Address(), id, closeSize)
}
func requestClose(owner address, id uint64, size int64) {
p := mustPerp(id)
if p.owner != owner {
panic("desk: not your position")
}
if size > p.size {
panic("desk: invalid close size")
}
if p.closeAt > 0 && time.Now().Unix()-p.closeAt <= orderTTL {
panic("desk: a close is already waiting for the next price")
}
if size == p.size {
size = 0
}
p.closeSize, p.closeAt = size, time.Now().Unix()
emitPerp("CloseRequest", p, "size", num(closingSize(p)))
}
func closingSize(p *perp) int64 {
if p.closeAt == 0 {
return 0
}
if p.closeSize == 0 || p.closeSize > p.size {
return p.size
}
return p.closeSize
}
// FillClose closes a requested position on the first price observed after the
// request, or drops a request that waited longer than orderTTL. Permissionless.
func FillClose(cur realm, id uint64) { fillClose(id) }
func fillClose(id uint64) {
p := mustPerp(id)
if p.closeAt == 0 {
panic("desk: no close requested")
}
if time.Now().Unix()-p.closeAt > orderTTL {
p.closeSize, p.closeAt = 0, 0
emitPerp("CloseExpire", p)
return
}
if !pricedAfter(p.ticker, p.closeAt) {
panic("desk: the close waits for the next price")
}
mark := freshPrice(p.ticker)
size := closingSize(p)
p.closeSize, p.closeAt = 0, 0
if size == p.size {
settlePerp(p, mark, "close")
return
}
closePortion(p, size, mark, "partial")
}
// Liquidate closes an underwater position. Permissionless: anyone (the desk's
// keeper bot, or the UI) may call it once the position is at maintenance.
func Liquidate(cur realm, id uint64) {
p := mustPerp(id)
mark := freshPrice(p.ticker)
if !liquidatable(p, mark) {
panic("desk: not liquidatable")
}
settlePerp(p, mark, "liquidate")
}
// holdingFee is the borrow fee owed to the pool for keeping a position open:
// holdRateBpsYear of the entry notional, prorated by seconds held. It prices the
// pool's directional risk over time — the honest substitute for funding on an
// oracle-mark desk (there is no perp-vs-spot basis to correct, but the pool is
// still carrying the position). Overflow-safe: perYear <= 1e11, elapsed clamped.
func holdingFee(p *perp, now int64) int64 {
el := now - p.openTime
if el <= 0 {
return 0
}
if el > 60_000_000 { // ~1.9y clamp keeps perYear*el well inside int64
el = 60_000_000
}
perYear := mulDiv(notionalMicroUSD(p.entry, p.size), holdRateBpsYear, bpsDenom)
return mulDiv(perYear, el, secondsYear)
}
// sliceSettle computes the numbers for closing `sz` units of a position at `mark`:
// pro-rata margin, the slice's PnL, the close fee and the borrow fee, and the owner
// payout (floored at 0). Pure — no transfers — so it is unit-tested directly.
func sliceSettle(p *perp, sz int64, mark int64, now int64) (payout, fee, hold, marginSlice int64) {
marginSlice = mulDiv(p.margin, sz, p.size)
pnl := notionalMicroUSD(mark, sz) - notionalMicroUSD(p.entry, sz)
if !p.isLong {
pnl = -pnl
}
fee = mulDiv(notionalMicroUSD(mark, sz), perpFeeBps, bpsDenom)
hold = mulDiv(holdingFee(p, now), sz, p.size)
payout = marginSlice + pnl - fee - hold
if payout < 0 {
payout = 0
}
return payout, fee, hold, marginSlice
}
// collectedFee caps a close's fees at the equity the closed slice still had.
func collectedFee(p *perp, sz, mark, marginSlice, owed int64) int64 {
pnl := notionalMicroUSD(mark, sz) - notionalMicroUSD(p.entry, sz)
if !p.isLong {
pnl = -pnl
}
equity := marginSlice + pnl
if equity < 0 {
return 0
}
if equity < owed {
return equity
}
return owed
}
// closePortion closes `sz` units of the position at `mark`: pays the owner the slice
// payout, routes the fees to the pool, releases the slice's open interest, and
// shrinks the position (or removes it when `sz` is the whole size). Leverage, entry
// and liq price of the remainder are unchanged (margin and size shrink together).
func closePortion(p *perp, sz int64, mark int64, kind string) {
if sz <= 0 || sz > p.size {
panic("desk: invalid close size")
}
payout, fee, hold, marginSlice := sliceSettle(p, sz, mark, time.Now().Unix())
unlock(marginSlice)
if free := freeReserve(); payout > free {
payout = free // profit comes only from tUSD nobody else is owed
}
if payout > 0 {
if err := usdLedger.Transfer(deskAddr, p.owner, payout); err != nil {
panic(err.Error())
}
}
accrueFee(collectedFee(p, sz, mark, marginSlice, fee+hold)) // only what the margin covered
subOI(p.ticker, p.isLong, notionalMicroUSD(p.entry, sz))
emitPerpClose(p, kind, sz, mark, payout)
if sz == p.size {
dropItem(perps, ownerPerps, p.owner, p.id)
} else {
p.size -= sz
p.margin -= marginSlice
}
}
// settlePerp fully closes and removes the position.
func settlePerp(p *perp, mark int64, kind string) { closePortion(p, p.size, mark, kind) }
// --- reads for the UI ---
// PerpsOf returns the caller's open positions, one per line, fields comma-
// separated: id,ticker,L|S,size,entry,margin,mark,pnl,liq,stopLoss,takeProfit,closing.
// Money and size are integers at 6 dp; mark/pnl/liq are computed live. Stop prices
// are 0 when unset; closing is the size of a close waiting for the next price.
func PerpsOf(owner address) string {
out := ""
eachOwned(ownerPerps, owner, func(item any) {
p := item.(*perp)
mark, _ := GetPrice(p.ticker)
out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d",
p.id, p.ticker, sideOf(p.isLong), p.size, p.entry, p.margin, mark, perpPnL(p, mark), liqPrice(p), p.stopLoss, p.takeProfit, closingSize(p)))
})
return out
}
// AllLiquidatable lists, within one page of open positions, the ids at or below
// maintenance on a fresh quote, ';'-joined, for the keeper.
func AllLiquidatable(offset, count int) string {
out := ""
eachPage(perps, offset, count, func(item any) {
p := item.(*perp)
if !IsFresh(p.ticker) {
return
}
if mark, _ := GetPrice(p.ticker); liquidatable(p, mark) {
out = joinRow(out, ufmt.Sprintf("%d", p.id))
}
})
return out
}
// ReadyCloses lists, within one page of open positions, the ids FillClose would
// act on now, ';'-joined, for the keeper.
func ReadyCloses(offset, count int) string {
out := ""
now := time.Now().Unix()
eachPage(perps, offset, count, func(item any) {
p := item.(*perp)
if p.closeAt == 0 {
return
}
if now-p.closeAt > orderTTL || (pricedAfter(p.ticker, p.closeAt) && IsFresh(p.ticker)) {
out = joinRow(out, ufmt.Sprintf("%d", p.id))
}
})
return out
}
reserve.gno
package lastcall
// lockedUSD is tUSD the reserve holds on behalf of open positions and pending
// limit orders. Payouts, spot sales and pool withdrawals may only spend the rest,
// so a margin or an escrow can always be returned to its owner.
var lockedUSD int64
func lock(amount int64) { lockedUSD += amount }
func unlock(amount int64) { lockedUSD -= amount }
func freeReserve() int64 {
free := usd.BalanceOf(deskAddr) - lockedUSD
if free < 0 {
return 0
}
return free
}
// LockedUSD is the part of the reserve owed back as margin and limit escrow.
func LockedUSD() int64 { return lockedUSD }
risk.gno
package lastcall
// Desk risk controls for perps. The desk/pool is the counterparty, so unbounded
// one-sided open interest would put the liquidity pool at unbounded directional
// risk. Two guards, both pool-protecting and both standard on pool-backed perp
// desks (GMX v2, Ostium, gTrade):
// - per-market open-interest caps, long and short tracked separately;
// - per-asset max leverage (can be lowered below the global 10x per market).
// All notional is micro-USD, measured at entry price.
import "gno.land/p/nt/ufmt/v0"
const (
defaultOICap = 250_000_000000 // $250,000 of open notional per side, per market
closedMaxLeverage = 2
skewImpactMaxBps = 100 // max +/-1.00% skew price impact on entry
skewScaleK = 500_000_000000 // $500,000: net skew at which impact reaches the max
)
var (
oiLong = map[string]int64{} // open long notional (micro-USD, at entry) per ticker
oiShort = map[string]int64{} // open short notional per ticker
oiCapOv = map[string]int64{} // per-ticker per-side cap override; 0 => default
maxLevOv = map[string]int64{} // per-ticker max leverage override; 0 => global maxLeverage
)
func oiCap(ticker string) int64 {
if c := oiCapOv[ticker]; c > 0 {
return c
}
return defaultOICap
}
// openLevOf is the leverage ceiling for a market while it trades: a per-asset
// override if set, otherwise the global maxLeverage. Overrides may only lower it.
func openLevOf(ticker string) int64 {
if l := maxLevOv[ticker]; l > 0 {
return l
}
return maxLeverage
}
// maxLevOf is the ceiling a new position gets right now. While the stock market
// is closed the quote cannot move, but the next open can gap, so new exposure is
// held to closedMaxLeverage until then.
func maxLevOf(ticker string) int64 {
if l := openLevOf(ticker); marketOpen || l <= closedMaxLeverage {
return l
}
return closedMaxLeverage
}
func sideOI(ticker string, isLong bool) int64 {
if isLong {
return oiLong[ticker]
}
return oiShort[ticker]
}
func addOI(ticker string, isLong bool, notional int64) {
if isLong {
oiLong[ticker] += notional
} else {
oiShort[ticker] += notional
}
}
func subOI(ticker string, isLong bool, notional int64) {
if isLong {
oiLong[ticker] -= notional
if oiLong[ticker] < 0 {
oiLong[ticker] = 0
}
} else {
oiShort[ticker] -= notional
if oiShort[ticker] < 0 {
oiShort[ticker] = 0
}
}
}
// --- admin config ---
// SetOICap sets the per-side open-interest cap for a market (micro-USD). 0 restores
// the default.
func SetOICap(cur realm, ticker string, perSide int64) {
assertAdmin(cur)
if perSide < 0 {
panic("desk: cap must be >= 0")
}
oiCapOv[ticker] = perSide
}
// SetMaxLev lowers (never raises) the max leverage for a market. 0 restores the
// global default.
func SetMaxLev(cur realm, ticker string, lev int64) {
assertAdmin(cur)
if lev < 0 || lev > maxLeverage {
panic("desk: leverage out of range")
}
maxLevOv[ticker] = lev
}
// --- reads ---
// OIOf returns a market's open-interest state, comma-separated:
// oiLong,oiShort,capPerSide,maxLev (notional micro-USD; maxLev a plain integer).
func OIOf(ticker string) string {
return ufmt.Sprintf("%d,%d,%d,%d", oiLong[ticker], oiShort[ticker], oiCap(ticker), maxLevOf(ticker))
}
// --- skew-priced entry ---
// A desk with no order book discourages one-sided books by pricing open interest:
// a trade that deepens the long/short imbalance fills at a worse entry. Only the
// entry price is adjusted; mark stays the oracle, so the impact is realized as the
// position's starting PnL.
// skewImpactBps is the entry price impact in bps for opening `notional` on
// `isLong`: the opener pays when they deepen the skew and fills at the oracle
// price when they balance it. A rebate would let an instant round trip profit.
func skewImpactBps(ticker string, isLong bool, notional int64) int64 {
var before int64 // how much heavier the opener's own side already is (signed)
if isLong {
before = oiLong[ticker] - oiShort[ticker]
} else {
before = oiShort[ticker] - oiLong[ticker]
}
mid := before + notional/2 // average skew the trade pushes through, on its side
imp := skewImpactMaxBps * mid / skewScaleK
if imp > skewImpactMaxBps {
imp = skewImpactMaxBps
}
if imp < 0 {
imp = 0
}
return imp
}
// skewEntry applies a bps impact to the oracle price to get the fill/entry price:
// a long fills higher and a short fills lower by `impBps` (worse when impBps > 0).
func skewEntry(price, impBps int64, isLong bool) int64 {
if isLong {
return mulDiv(price, bpsDenom+impBps, bpsDenom)
}
return mulDiv(price, bpsDenom-impBps, bpsDenom)
}
stocks.gno
package lastcall
import "gno.land/p/nt/grc20/v0"
// A stock is one synthetic-equity market: a GRC20 token (6 decimals) whose
// ledger the desk owns, so the desk can mint on Buy and burn on Sell.
type stock struct {
token *grc20.Token
ledger *grc20.PrivateLedger
}
var (
stocks = map[string]*stock{}
tickers = []string{} // insertion order, for Render
)
var defaultMarkets = []struct{ ticker, name string }{
{"NVDA", "Synthetic NVIDIA"},
{"AAPL", "Synthetic Apple"},
{"TSLA", "Synthetic Tesla"},
{"MSFT", "Synthetic Microsoft"},
{"AMZN", "Synthetic Amazon"},
}
func initStocks(cur realm) {
for _, m := range defaultMarkets {
listStock(cur, m.ticker, m.name)
}
}
func listStock(cur realm, ticker, name string) {
if _, ok := stocks[ticker]; ok {
panic("desk: market exists: " + ticker)
}
t, l := grc20.NewToken(name, "s"+ticker, 6, nextTokID.Next(), cur)
stocks[ticker] = &stock{token: t, ledger: l}
tickers = append(tickers, ticker)
}
func mustStock(ticker string) *stock {
s, ok := stocks[ticker]
if !ok {
panic("desk: unknown ticker " + ticker)
}
return s
}
func StockBalance(ticker string, owner address) int64 {
return mustStock(ticker).token.BalanceOf(owner)
}
func StockSupply(ticker string) int64 {
return mustStock(ticker).token.TotalSupply()
}
stops.gno
package lastcall
// Stop-loss / take-profit for open perps. A stop is an instruction attached to a
// position: close it at the desk price once that price crosses the trigger. Like
// orders, a stop acts only on a price observed after it was set, and execution is
// permissionless (TriggerStop). The close settles like a normal close.
import (
"time"
"gno.land/p/nt/ufmt/v0"
)
// validateStops rejects stop prices on the wrong side of the current mark, which would
// trigger instantly, and keeps SL below TP for a long / above TP for a short. A 0 clears
// that leg. Prices are micro-USD per share.
func validateStops(p *perp, sl, tp int64) {
if sl < 0 || tp < 0 {
panic("desk: stop prices must be >= 0")
}
mark, _ := GetPrice(p.ticker)
if p.isLong {
if sl > 0 && sl >= mark {
panic("desk: long stop-loss must be below mark")
}
if tp > 0 && tp <= mark {
panic("desk: long take-profit must be above mark")
}
} else {
if sl > 0 && sl <= mark {
panic("desk: short stop-loss must be above mark")
}
if tp > 0 && tp >= mark {
panic("desk: short take-profit must be below mark")
}
}
}
// SetStops sets, updates or clears the stop-loss and take-profit of the caller's own
// position. Each price is micro-USD per share; pass 0 to clear that leg.
func SetStops(cur realm, id uint64, stopLoss, takeProfit int64) {
p := mustPerp(id)
if p.owner != cur.Previous().Address() {
panic("desk: not your position")
}
if stopFillable(p) {
panic("desk: your stop has been reached, it closes at this price")
}
validateStops(p, stopLoss, takeProfit)
p.stopLoss = stopLoss
p.takeProfit = takeProfit
p.stopsAt = time.Now().Unix()
}
func stopFillable(p *perp) bool {
if (p.stopLoss == 0 && p.takeProfit == 0) || !pricedAfter(p.ticker, p.stopsAt) || !IsFresh(p.ticker) {
return false
}
mark, _ := GetPrice(p.ticker)
return stopReady(p, mark)
}
// stopReady reports whether a position's stop-loss or take-profit has been reached at
// `mark`. Long: SL when mark <= SL, TP when mark >= TP. Short: mirrored.
func stopReady(p *perp, mark int64) bool {
if p.isLong {
if p.stopLoss > 0 && mark <= p.stopLoss {
return true
}
if p.takeProfit > 0 && mark >= p.takeProfit {
return true
}
} else {
if p.stopLoss > 0 && mark >= p.stopLoss {
return true
}
if p.takeProfit > 0 && mark <= p.takeProfit {
return true
}
}
return false
}
// TriggerStop closes a position whose stop-loss or take-profit has been reached, at the
// current mark. Permissionless (keeper / UI); panics if no stop is set or not reached,
// so the keeper simply retries later.
func TriggerStop(cur realm, id uint64) {
p := mustPerp(id)
if p.stopLoss == 0 && p.takeProfit == 0 {
panic("desk: no stop set")
}
if !pricedAfter(p.ticker, p.stopsAt) {
panic("desk: the stop waits for a price after it was set")
}
mark := freshPrice(p.ticker)
if !stopReady(p, mark) {
panic("desk: stop not reached")
}
// Anyone can call this, so it must not close a winner for less than it is
// owed: the position waits until the reserve can pay it in full.
if payout, _, _, _ := sliceSettle(p, p.size, mark, time.Now().Unix()); payout > freeReserve()+p.margin {
panic("desk: the reserve cannot pay this stop in full right now")
}
settlePerp(p, mark, "stop")
}
// --- reads ---
// ReadyStops lists, within one page of open positions, the ids whose stop
// TriggerStop would act on now, ';'-joined, for the keeper.
func ReadyStops(offset, count int) string {
out := ""
eachPage(perps, offset, count, func(item any) {
if p := item.(*perp); stopFillable(p) {
out = joinRow(out, ufmt.Sprintf("%d", p.id))
}
})
return out
}
trade.gno
package lastcall
// Spot trading against the desk. The desk quotes its own price and takes a fee on
// each side; it is the counterparty to every trade. Buy and Sell are orders that
// fill on the next price (orders.gno): a buy mints sStock, a sell pays tUSD from
// the desk reserve, never from tUSD locked behind margin or orders.
const (
feeBps = 30 // 0.30% desk fee each side
bpsDenom = 10000 //
microUSD = 1000000 // 1 tUSD = 1_000000 micro; 1 share = 1_000000 units
minTradeUnits = 1000 // 0.001 share minimum, blocks dust
maxTradeUnits = 10_000_000000 // 10,000 shares max, keeps price*amount in int64
)
// notionalMicroUSD returns price * stockAmount / 1e6 — the micro-USD value of
// stockAmount units (6 dp) of a stock quoted at `price` micro-USD per share.
func notionalMicroUSD(price, stockAmount int64) int64 {
return mulDiv(price, stockAmount, microUSD)
}
func assertTradeSize(stockAmount int64) {
if stockAmount < minTradeUnits {
panic("desk: amount below minimum (0.001 share)")
}
if stockAmount > maxTradeUnits {
panic("desk: amount above maximum (10,000 shares)")
}
}
// QuoteBuy / QuoteSell are read-only helpers for the UI: the tUSD cost/proceeds
// of trading stockAmount units at the current price.
func QuoteBuy(ticker string, stockAmount int64) int64 {
assertTradeSize(stockAmount)
price, _ := GetPrice(ticker)
return mulDiv(notionalMicroUSD(price, stockAmount), bpsDenom+feeBps, bpsDenom)
}
func QuoteSell(ticker string, stockAmount int64) int64 {
assertTradeSize(stockAmount)
price, _ := GetPrice(ticker)
return mulDiv(notionalMicroUSD(price, stockAmount), bpsDenom-feeBps, bpsDenom)
}
// SeedUSD mints tUSD into the desk reserve so it can pay out on sells and
// in-the-money perps. Admin only — the desk's bootstrap liquidity.
func SeedUSD(cur realm, amount int64) {
assertAdmin(cur)
if amount <= 0 {
panic("desk: amount must be positive")
}
if err := usdLedger.Mint(deskAddr, amount); err != nil {
panic(err.Error())
}
}
// DeskReserveUSD is the desk's own tUSD balance.
func DeskReserveUSD() int64 { return usd.BalanceOf(deskAddr) }
vault.gno
package lastcall
// The LastCall liquidity pool — the desk's yield product.
//
// Anyone can deposit tUSD into the pool. Pooled tUSD sits in the desk reserve
// next to the admin-seeded float. Trader wins and losses settle against the
// reserve and never change the share price; the pool
// earns 100% of the desk's trading fees — 0.30% on each spot trade and 0.10%
// on each perp open/close — shared pro-rata across depositors. There is no
// emitted reward token and no made-up APY: the yield is exactly the fees the
// desk actually collects.
//
// Accounting is share-based, like an ERC-4626 vault. A deposit mints shares at
// the current share price (poolAssets / poolShares); accrued fees stream into
// poolAssets over a day while shares stay fixed, so each share is worth more over
// time and depositing just before a fee lands captures none of it. A withdrawal
// burns shares for their pro-rata slice of poolAssets, paid in tUSD from the part
// of the reserve that is not locked behind open positions and orders. All amounts are micro-USD (6 dp), like the rest of the
// desk.
import (
"time"
"gno.land/p/nt/ufmt/v0"
)
const (
minPoolDeposit = 1_000000 // $1 minimum, blocks dust shares
minPoolShares = 100000 // a holding is zero or at least 0.1 share, so a share cannot be inflated
feeStreamSec = 86400
)
var (
poolShares int64 // total shares outstanding
poolAssets int64 // micro-USD the pool is entitled to in the reserve
poolFeesAll int64 // cumulative fees ever routed to the pool (metrics)
poolBals = map[address]int64{} // shares held per depositor
pendingFees int64 // fees not yet part of poolAssets
streamAt int64 // time up to which pendingFees have been released
streamEnd int64 // time at which the rest is fully released
)
func releasedFees(now int64) int64 {
if pendingFees == 0 || now <= streamAt {
return 0
}
if now >= streamEnd {
return pendingFees
}
return mulDiv(pendingFees, now-streamAt, streamEnd-streamAt)
}
func drip(now int64) {
r := releasedFees(now)
pendingFees -= r
poolAssets += r
streamAt = now
}
func assetsNow() int64 { return poolAssets + releasedFees(time.Now().Unix()) }
// accrueFee routes a desk fee into the pool. Called by spot and perp trading.
// If no one has deposited yet (poolShares == 0) the fee simply stays in the
// reserve as it did before — there is no one to credit.
func accrueFee(fee int64) {
if fee <= 0 || poolShares == 0 {
return
}
now := time.Now().Unix()
drip(now)
pendingFees += fee
streamEnd = now + feeStreamSec
poolFeesAll += fee
}
// PoolDeposit pulls `amount` tUSD micro from the caller into the desk reserve
// and mints pool shares at the current share price. Returns the shares minted.
func PoolDeposit(cur realm, amount int64) int64 {
if amount < minPoolDeposit {
panic("pool: deposit below minimum ($1)")
}
lp := cur.Previous().Address()
drip(time.Now().Unix())
// A reserve that no longer covers what the pool already claims would hand the
// new money to the earlier depositors.
if freeReserve() < poolAssets+pendingFees {
panic("pool: under water, deposits are paused")
}
if err := usdLedger.Transfer(lp, deskAddr, amount); err != nil {
panic(err.Error())
}
var shares int64
if poolShares == 0 || poolAssets == 0 {
shares = amount // bootstrap: 1 share == 1 micro-tUSD
} else {
shares = mulDiv(amount, poolShares, poolAssets)
}
if shares < minPoolShares {
panic("pool: deposit too small, it must buy at least 0.1 share")
}
poolShares += shares
poolAssets += amount
poolBals[lp] += shares
emitPool("PoolDeposit", lp, amount, shares)
return shares
}
// PoolWithdraw burns `shares` from the caller and pays their pro-rata slice of
// the pool in tUSD from the desk reserve. Returns the tUSD micro paid out.
func PoolWithdraw(cur realm, shares int64) int64 {
lp := cur.Previous().Address()
have := poolBals[lp]
if shares <= 0 || shares > have {
panic("pool: not enough shares")
}
if left := have - shares; left > 0 && left < minPoolShares {
panic("pool: leave at least 0.1 share or withdraw everything")
}
drip(time.Now().Unix())
assets := mulDiv(shares, poolAssets, poolShares)
if assets > freeReserve() {
panic("pool: the reserve is backing open positions, withdraw less")
}
poolBals[lp] = have - shares
poolShares -= shares
poolAssets -= assets
if poolShares == 0 {
poolAssets, pendingFees = 0, 0 // unreleased fees stay in the reserve
}
if assets > 0 {
if err := usdLedger.Transfer(deskAddr, lp, assets); err != nil {
panic(err.Error())
}
}
emitPool("PoolWithdraw", lp, assets, shares)
return assets
}
// --- reads for the UI ---
// PoolSharePrice is the value of one share in micro-USD, scaled by 1e6 (so a
// fresh pool reads 1_000000 == $1.000000 per share). Returns 1e6 when empty.
func PoolSharePrice() int64 {
if poolShares == 0 {
return microUSD
}
return mulDiv(assetsNow(), microUSD, poolShares)
}
// PoolInfo returns pool-wide figures, comma-separated:
// totalShares,poolAssets,feesAll,deskReserve (all micro, 6 dp).
func PoolInfo() string {
return ufmt.Sprintf("%d,%d,%d,%d", poolShares, assetsNow(), poolFeesAll, usd.BalanceOf(deskAddr))
}
// PoolOf returns one depositor's position, comma-separated:
// shares,assets where assets is the current tUSD micro value of those shares.
func PoolOf(owner address) string {
sh := poolBals[owner]
assets := int64(0)
if sh > 0 && poolShares > 0 {
assets = mulDiv(sh, assetsNow(), poolShares)
}
return ufmt.Sprintf("%d,%d", sh, assets)
}