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.

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
}

// 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)
}

desk.gno

// Package lastcall is a fully-collateralized 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
}

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("* fee pool: %s, cumulative fees %s\n", usdFmt(poolAssets), usdFmt(poolFeesAll))
	out += ufmt.Sprintf("* open positions: %d, pending limits: %d\n", len(perps), len(limits))
	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
}

gnomod.toml

module = "gno.land/r/g1p8v5lkq5mqp7r8h8stcv4fgrwrx3zupvww9m85/lastcall"
gno = "0.9"

[addpkg]
  creator = "g1p8v5lkq5mqp7r8h8stcv4fgrwrx3zupvww9m85"
  height = 1644694
  max_deposit = "100000000ugnot"

limit.gno

package lastcall

// Limit orders for perps. On an oracle-priced desk there is no order book, so a
// limit is a queued instruction: lock the margin + open fee now, and open the perp
// once the oracle price reaches the limit (long: at or below; short: at or above).
// Execution is permissionless (TriggerLimit) — the price bot acts as the keeper,
// and anyone can trigger a ready order. Orders only execute while the market is
// open, so they naturally queue over a weekend and fire on reopen.

import (
	"time"

	"gno.land/p/nt/ufmt/v0"
)

type limitOrder struct {
	id       uint64
	owner    address
	ticker   string
	isLong   bool
	size     int64 // stock units (6 dp)
	margin   int64 // tUSD micro locked up-front
	fee      int64 // prepaid open fee (at the limit price)
	limit    int64 // trigger price, micro-USD per share
	placedAt int64
}

var (
	limits      = map[uint64]*limitOrder{}
	nextLimitID uint64
)

// PlaceLimit locks `margin` + the open fee and queues an order to open a perp when
// the oracle price reaches `limit`. Returns the order id.
func PlaceLimit(cur realm, ticker string, isLong bool, size, margin, limit int64) uint64 {
	_ = mustStock(ticker)
	assertPerpSize(size)
	assertMargin(margin)
	if limit <= 0 || limit > maxPrice {
		panic("desk: limit price out of range")
	}
	notional := notionalMicroUSD(limit, size)
	if notional <= 0 || notional > perpMaxNotional {
		panic("desk: notional out of range")
	}
	if notional > margin*maxLevOf(ticker) {
		panic("desk: over this market's max leverage")
	}
	fee := mulDiv(notional, perpFeeBps, bpsDenom)
	owner := cur.Previous().Address()
	if err := usdLedger.Transfer(owner, deskAddr, margin+fee); err != nil {
		panic(err.Error())
	}
	nextLimitID++
	id := nextLimitID
	limits[id] = &limitOrder{
		id: id, owner: owner, ticker: ticker, isLong: isLong,
		size: size, margin: margin, fee: fee, limit: limit, placedAt: time.Now().Unix(),
	}
	return id
}

// CancelLimit refunds a pending order's locked margin + fee to its owner.
func CancelLimit(cur realm, id uint64) {
	o, ok := limits[id]
	if !ok {
		panic("desk: unknown limit order")
	}
	if o.owner != cur.Previous().Address() {
		panic("desk: not your order")
	}
	if err := usdLedger.Transfer(deskAddr, o.owner, o.margin+o.fee); err != nil {
		panic(err.Error())
	}
	delete(limits, id)
}

// limitReady reports whether an order's trigger condition holds at `mark`:
// a long fills at or below its limit, a short at or above.
func limitReady(o *limitOrder, mark int64) bool {
	if o.isLong {
		return mark <= o.limit
	}
	return mark >= o.limit
}

// fillSize shrinks an order whose notional at the fill price would exceed the
// leverage its margin allows, so a price gap past the limit still fills.
func fillSize(o *limitOrder, 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)
}

// TriggerLimit executes a ready order at the current oracle price, using the locked
// margin + prepaid fee. Permissionless (keeper / UI). Requires the market open and
// the trigger reached; panics otherwise so the keeper simply retries later.
func TriggerLimit(cur realm, id uint64) uint64 {
	o, ok := limits[id]
	if !ok {
		panic("desk: unknown limit order")
	}
	if !marketOpen {
		panic("desk: market closed")
	}
	mark := freshPrice(o.ticker)
	if !limitReady(o, mark) {
		panic("desk: limit not reached")
	}
	pid := openPositionCore(o.owner, o.ticker, o.isLong, fillSize(o, mark), o.margin, mark, o.fee)
	delete(limits, id)
	return pid
}

// --- reads ---

// LimitsOf returns an owner's pending orders, ';'-joined, fields comma-separated:
// id,ticker,L|S,size,margin,limit,mark  (size/money micro, 6 dp).
func LimitsOf(owner address) string {
	out := ""
	for id := uint64(1); id <= nextLimitID; id++ {
		o, ok := limits[id]
		if !ok || o.owner != owner {
			continue
		}
		mark, _ := GetPrice(o.ticker)
		side := "S"
		if o.isLong {
			side = "L"
		}
		if out != "" {
			out += ";"
		}
		out += ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d", o.id, o.ticker, side, o.size, o.margin, o.limit, mark)
	}
	return out
}

// AllLimits lists every pending order for the keeper to scan, ';'-joined:
// id,ticker,L|S,limit,mark. The keeper triggers the ones whose condition holds.
func AllLimits() string {
	out := ""
	for id := uint64(1); id <= nextLimitID; id++ {
		o, ok := limits[id]
		if !ok {
			continue
		}
		mark, _ := GetPrice(o.ticker)
		side := "S"
		if o.isLong {
			side = "L"
		}
		if out != "" {
			out += ";"
		}
		out += ufmt.Sprintf("%d,%s,%s,%d,%d", o.id, o.ticker, side, o.limit, mark)
	}
	return out
}

market.gno

package lastcall

// Market hours. US equities don't trade 24/7, and a stock can gap over a weekend
// or overnight while positions are frozen. The off-chain updater (price bot) pushes
// the real market status each cycle; the desk only accepts NEW perp opens while the
// market is open — opening a leveraged position against a stale, closed-market price
// is the gap-risk trap. Closing and liquidating stay allowed so no one is trapped,
// and spot stays available (1:1 mint/burn at the reference, no leverage).

var marketOpen = true // default open until the updater pushes the real status

// SetMarketOpen is pushed by the off-chain updater (bot) from the live market state.
func SetMarketOpen(cur realm, open bool) {
	assertUpdater(cur)
	marketOpen = open
}

// IsMarketOpen reports whether the desk is accepting new perp opens.
func IsMarketOpen() bool { return marketOpen }

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)
}

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)
}

var (
	perps      = map[uint64]*perp{}
	nextPerpID uint64
)

func mustPerp(id uint64) *perp {
	p, ok := perps[id]
	if !ok {
		panic("desk: unknown perp id")
	}
	return p
}

// 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 has fallen to the maintenance fraction of the margin.
func liquidatable(p *perp, mark int64) bool {
	return perpEquity(p, mark) <= 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)
	drop := mulDiv(allowedLoss, microUSD, p.size) // micro-USD per share
	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)")
	}
}

// OpenPerp opens a long or short on `ticker` of `size` stock units (6 dp), backed
// by `margin` tUSD micro pulled from the caller (plus the open fee). Market order.
func OpenPerp(cur realm, ticker string, isLong bool, size int64, margin int64) uint64 {
	_ = mustStock(ticker) // only real markets
	if !marketOpen {
		panic("desk: market closed — new perps open only during market hours")
	}
	assertPerpSize(size)
	assertMargin(margin)
	price := freshPrice(ticker)
	notional := notionalMicroUSD(price, size)
	fee := mulDiv(notional, perpFeeBps, bpsDenom)
	owner := cur.Previous().Address()
	if err := usdLedger.Transfer(owner, deskAddr, margin+fee); err != nil {
		panic(err.Error())
	}
	return openPositionCore(owner, ticker, isLong, size, margin, price, fee)
}

// openPositionCore validates and creates a perp, assuming `margin`+`fee` tUSD are
// ALREADY in the desk reserve (pulled from the owner by the caller). Shared by
// market opens (OpenPerp) and limit-order execution (TriggerLimit). A panic here
// reverts the whole tx, including the funds pull, 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")
	}
	assertMargin(margin)
	if 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
	perps[id] = &perp{
		id: id, owner: owner, ticker: ticker, isLong: isLong,
		size: size, entry: entry, margin: margin,
		openTime: time.Now().Unix(),
	}
	// 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 closes the caller's own position at the current mark and settles.
func ClosePerp(cur realm, id uint64) {
	p := mustPerp(id)
	if p.owner != cur.Previous().Address() {
		panic("desk: not your position")
	}
	mark := freshPrice(p.ticker)
	settlePerp(p, mark)
}

// ClosePartial closes `closeSize` units (6 dp) of the caller's own position at the
// current mark, leaving the rest open. Always allowed, even when the market is
// closed. closeSize == the full size behaves like ClosePerp.
func ClosePartial(cur realm, id uint64, closeSize int64) {
	p := mustPerp(id)
	if p.owner != cur.Previous().Address() {
		panic("desk: not your position")
	}
	if closeSize <= 0 || closeSize > p.size {
		panic("desk: invalid close size")
	}
	mark := freshPrice(p.ticker)
	closePortion(p, closeSize, mark)
}

// 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)
}

// 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) {
	if sz <= 0 || sz > p.size {
		panic("desk: invalid close size")
	}
	payout, fee, hold, marginSlice := sliceSettle(p, sz, mark, time.Now().Unix())
	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))
	if sz == p.size {
		delete(perps, p.id)
	} else {
		p.size -= sz
		p.margin -= marginSlice
	}
}

// settlePerp fully closes and removes the position.
func settlePerp(p *perp, mark int64) { closePortion(p, p.size, mark) }

// --- 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.
// Money and size are integers at 6 dp; mark/pnl/liq are computed live. Stop prices
// are 0 when unset. Empty string if none.
func PerpsOf(owner address) string {
	out := ""
	for id := uint64(1); id <= nextPerpID; id++ {
		p, ok := perps[id]
		if !ok || p.owner != owner {
			continue
		}
		mark, _ := GetPrice(p.ticker)
		side := "S"
		if p.isLong {
			side = "L"
		}
		if out != "" {
			out += ";"
		}
		out += ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d,%d,%d,%d,%d",
			p.id, p.ticker, side, p.size, p.entry, p.margin, mark, perpPnL(p, mark), liqPrice(p), p.stopLoss, p.takeProfit)
	}
	return out
}

// AllLiquidatable lists the ids of positions at or below maintenance on a fresh
// quote, ';'-joined, for the keeper.
func AllLiquidatable() string {
	out := ""
	for id := uint64(1); id <= nextPerpID; id++ {
		p, ok := perps[id]
		if !ok || !IsFresh(p.ticker) {
			continue
		}
		mark, _ := GetPrice(p.ticker)
		if !liquidatable(p, mark) {
			continue
		}
		if out != "" {
			out += ";"
		}
		out += ufmt.Sprintf("%d", p.id)
	}
	return out
}

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
	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
}

// maxLevOf is the leverage ceiling for a market: a per-asset override if set,
// otherwise the global maxLeverage. Overrides may only lower it.
func maxLevOf(ticker string) int64 {
	if l := maxLevOv[ticker]; l > 0 {
		return l
	}
	return maxLeverage
}

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 current mark once the oracle price crosses the trigger.
// Like limit orders, execution is permissionless (TriggerStop) — the price bot acts
// as the keeper and anyone may trigger a position whose stop has been reached. The
// close settles exactly like a normal close (same fees, same payout).

import "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")
	}
	validateStops(p, stopLoss, takeProfit)
	p.stopLoss = stopLoss
	p.takeProfit = takeProfit
}

// 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")
	}
	mark := freshPrice(p.ticker)
	if !stopReady(p, mark) {
		panic("desk: stop not reached")
	}
	settlePerp(p, mark)
}

// --- reads ---

// AllStops lists every open position that has a stop set, for the keeper to scan,
// ';'-joined, fields comma-separated: id,ticker,L|S,stopLoss,takeProfit,mark. The
// keeper triggers the ones whose condition holds.
func AllStops() string {
	out := ""
	for id := uint64(1); id <= nextPerpID; id++ {
		p, ok := perps[id]
		if !ok || (p.stopLoss == 0 && p.takeProfit == 0) {
			continue
		}
		mark, _ := GetPrice(p.ticker)
		side := "S"
		if p.isLong {
			side = "L"
		}
		if out != "" {
			out += ";"
		}
		out += ufmt.Sprintf("%d,%s,%s,%d,%d,%d", p.id, p.ticker, side, p.stopLoss, p.takeProfit, mark)
	}
	return out
}

trade.gno

package lastcall

// Spot trading against the desk. The desk quotes the oracle price and takes a
// fee on each side; it is the counterparty to every trade. Buys pull tUSD from
// the user and mint sStock; sells burn sStock and pay tUSD from the desk
// reserve. Fully collateralized in tUSD held by the desk.

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)")
	}
}

// Buy mints stockAmount units (6 dp) of sTicker to the caller and charges tUSD
// at the desk price plus fee. Caller must already hold enough tUSD.
func Buy(cur realm, ticker string, stockAmount int64) {
	assertTradeSize(stockAmount)
	s := mustStock(ticker)
	price := freshPrice(ticker)
	notional := notionalMicroUSD(price, stockAmount)
	cost := mulDiv(notional, bpsDenom+feeBps, bpsDenom)
	if cost <= 0 {
		panic("desk: trade too small")
	}
	buyer := cur.Previous().Address()
	if err := usdLedger.Transfer(buyer, deskAddr, cost); err != nil {
		panic(err.Error())
	}
	if err := s.ledger.Mint(buyer, stockAmount); err != nil {
		panic(err.Error())
	}
	addCost(buyer, ticker, notional) // cost basis for the UI's avg entry
	accrueFee(cost - notional)       // desk fee -> liquidity pool yield
}

// Sell burns stockAmount units of sTicker from the caller and pays tUSD at the
// desk price minus fee, from the desk reserve.
func Sell(cur realm, ticker string, stockAmount int64) {
	assertTradeSize(stockAmount)
	s := mustStock(ticker)
	price := freshPrice(ticker)
	notional := notionalMicroUSD(price, stockAmount)
	proceeds := mulDiv(notional, bpsDenom-feeBps, bpsDenom)
	seller := cur.Previous().Address()
	heldBefore := s.token.BalanceOf(seller)
	if err := s.ledger.Burn(seller, stockAmount); err != nil {
		panic(err.Error())
	}
	if err := usdLedger.Transfer(deskAddr, seller, proceeds); err != nil {
		panic(err.Error())
	}
	reduceCost(seller, ticker, stockAmount, heldBefore) // keep avg entry across sells
	accrueFee(notional - proceeds)                      // desk fee -> liquidity pool yield
}

// 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 raise
// poolAssets while shares stay fixed, so each share is worth more over time. A
// withdrawal burns shares for their pro-rata slice of poolAssets, paid in tUSD
// from the desk reserve. All amounts are micro-USD (6 dp), like the rest of the
// desk.

import "gno.land/p/nt/ufmt/v0"

const minPoolDeposit = 1_000000 // $1 minimum, blocks dust shares

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
)

// 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
	}
	poolAssets += fee
	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()
	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 <= 0 {
		panic("pool: deposit too small for a share")
	}
	poolShares += shares
	poolAssets += amount
	poolBals[lp] += 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")
	}
	assets := mulDiv(shares, poolAssets, poolShares)
	poolBals[lp] = have - shares
	poolShares -= shares
	poolAssets -= assets
	if poolShares == 0 {
		poolAssets = 0 // avoid dust stranding the last share price
	}
	if assets > 0 {
		if err := usdLedger.Transfer(deskAddr, lp, assets); err != nil {
			panic(err.Error())
		}
	}
	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(poolAssets, 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, poolAssets, 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, poolAssets, poolShares)
	}
	return ufmt.Sprintf("%d,%d", sh, assets)
}