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 synthetic stocks desk on gno.land.
//
// It is self-contained: it runs its own price feed (an off-chain bot pushes
// quotes from the updater 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{}
// SetPrices stores several quotes in one transaction so the keeper pays one fee
// per cycle. quotes is "TICKER:microUSD" pairs joined by ','.
func SetPrices(cur realm, quotes string, observedAt int64) {
assertUpdater(cur)
for _, pair := range strings.Split(quotes, ",") {
ticker, raw, ok := strings.Cut(pair, ":")
value, err := strconv.ParseInt(raw, 10, 64)
if !ok || err != nil {
panic("desk: malformed quote: " + pair)
}
storePrice(ticker, value, observedAt)
}
}
func storePrice(ticker string, value int64, observedAt int64) {
_ = mustStock(ticker)
if value <= 0 || value > maxPrice {
panic("desk: price out of range")
}
if observedAt > time.Now().Unix()+maxClockSkew {
panic("desk: observation is in the future")
}
if p, ok := prices[ticker]; ok && observedAt < p.ObservedAt {
panic("desk: observation is older than the stored quote")
}
prices[ticker] = Price{Value: value, ObservedAt: observedAt}
}
// GetPrice returns the last quote for a ticker. Panics if unknown.
func GetPrice(ticker string) (int64, int64) {
p, ok := prices[ticker]
if !ok {
panic("desk: no price for " + ticker)
}
return p.Value, p.ObservedAt
}
const (
maxPriceAge = 600
maxClockSkew = 60
maxPrice = 1_000_000_000000
)
// IsFresh reports whether a ticker has a quote young enough to trade against.
func IsFresh(ticker string) bool {
p, ok := prices[ticker]
return ok && time.Now().Unix()-p.ObservedAt <= maxPriceAge
}
// LastCallAt is the time after which the stored quote no longer allows a trade,
// or 0 before the first quote.
func LastCallAt(ticker string) int64 {
p, ok := prices[ticker]
if !ok {
return 0
}
return p.ObservedAt + maxPriceAge
}
func freshPrice(ticker string) int64 {
value, _ := GetPrice(ticker)
if !IsFresh(ticker) {
panic("desk: price is stale, last call has passed for " + ticker)
}
return value
}
// --- render ---
func Render(path string) string {
out := "# LastCall\n\n"
out += "Synthetic stock desk: spot, perps, limit orders and a fee pool. Test funds only.\n\n"
out += "## Markets\n\n"
out += "| Ticker | Price (USD) | Quote | Supply | Long OI | Short OI |\n|---|---|---|---|---|---|\n"
for _, t := range tickers {
ps, quote := "-", "none"
if p, ok := prices[t]; ok {
ps = usdFmt(p.Value)
quote = "last call passed"
if IsFresh(t) {
quote = "live"
}
}
out += ufmt.Sprintf("| s%s | %s | %s | %s | %s | %s |\n", t, ps, quote, sharesFmt(stocks[t].token.TotalSupply()), usdFmt(oiLong[t]), usdFmt(oiShort[t]))
}
out += "\n## Desk\n\n"
out += ufmt.Sprintf("* tUSD total supply: %s\n", usdFmt(usd.TotalSupply()))
out += ufmt.Sprintf("* desk tUSD reserve: %s\n", usdFmt(usd.BalanceOf(deskAddr)))
out += ufmt.Sprintf("* locked behind positions and orders: %s\n", usdFmt(lockedUSD))
out += ufmt.Sprintf("* fee pool: %s, cumulative fees %s\n", usdFmt(assetsNow()), usdFmt(poolFeesAll))
out += ufmt.Sprintf("* open positions: %d, pending limits: %d\n", perps.Size(), limits.Size())
out += ufmt.Sprintf("* a quote older than %d seconds stops every trade that moves value\n", maxPriceAge)
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\n", closedMaxLeverage)
}
out += "\n## Keys\n\n"
out += ufmt.Sprintf("* admin: %s\n* price updater: %s\n* desk reserve account: %s\n", admin.String(), updater.String(), deskAddr.String())
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 emitLimit(kind string, o *limitOrder, extra ...string) {
attrs := []string{"owner", o.owner.String(), "id", ref(o.id), "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 emitPool(kind string, owner address, usd, shares int64) {
chain.Emit(kind, "owner", owner.String(), "usd", num(usd), "shares", num(shares))
}
gnomod.toml
module = "gno.land/r/g1p8v5lkq5mqp7r8h8stcv4fgrwrx3zupvww9m85/lastcall/v3" gno = "0.9" [addpkg] creator = "g1p8v5lkq5mqp7r8h8stcv4fgrwrx3zupvww9m85" height = 1648684 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()
limits = avl.NewTree()
ownerLimits = 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 LimitCount tell the keeper how many pages to read.
func OpenPerpCount() int { return perps.Size() }
func LimitCount() int { return limits.Size() }
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. While the market is closed only orders at
// up to closedMaxLeverage fill; the rest queue over the 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), settled at the fill
limit int64 // trigger price, micro-USD per share
placedAt int64
}
var nextLimitID uint64
func mustLimit(id uint64) *limitOrder {
v := limits.Get(idKey(id))
if v == nil {
panic("desk: unknown limit order")
}
return v.(*limitOrder)
}
// 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)
_, _ = GetPrice(ticker) // an order on a never-quoted market could not be listed
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*openLevOf(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
o := &limitOrder{
id: id, owner: owner, ticker: ticker, isLong: isLong,
size: size, margin: margin, fee: fee, limit: limit, placedAt: time.Now().Unix(),
}
putItem(limits, ownerLimits, owner, id, o)
lock(margin + fee)
emitLimit("LimitPlace", o)
return id
}
// CancelLimit refunds a pending order's locked margin + fee to its owner.
func CancelLimit(cur realm, id uint64) {
o := mustLimit(id)
if o.owner != cur.Previous().Address() {
panic("desk: not your order")
}
unlock(o.margin + o.fee)
if err := usdLedger.Transfer(deskAddr, o.owner, o.margin+o.fee); err != nil {
panic(err.Error())
}
dropItem(limits, ownerLimits, o.owner, id)
emitLimit("LimitCancel", o)
}
// 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)
}
// limitFill settles the open fee on what actually fills at `mark`. A surplus of
// the prepaid fee is refunded; a shortfall comes out of the margin, and the size
// is capped so the smaller margin still carries it.
func limitFill(o *limitOrder, 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
}
// TriggerLimit executes a ready order at the current oracle price, using the locked
// margin + prepaid fee. Permissionless (keeper / UI). Requires the trigger reached,
// including any skew impact on the entry, and while the market is closed a
// leverage within closedMaxLeverage; panics otherwise so the keeper retries later.
func TriggerLimit(cur realm, id uint64) uint64 {
o := mustLimit(id)
if !marketOpen && notionalMicroUSD(o.limit, o.size) > o.margin*closedMaxLeverage {
panic("desk: market closed, this order's leverage waits for the open")
}
mark := freshPrice(o.ticker)
if !limitReady(o, mark) {
panic("desk: limit not reached")
}
size, margin, fee, refund := limitFill(o, mark)
entry := skewEntry(mark, skewImpactBps(o.ticker, o.isLong, notionalMicroUSD(mark, size)), o.isLong)
if (o.isLong && entry > o.limit) || (!o.isLong && entry < o.limit) {
panic("desk: skew impact puts the fill past your limit")
}
unlock(o.margin + o.fee)
if refund > 0 {
if err := usdLedger.Transfer(deskAddr, o.owner, refund); err != nil {
panic(err.Error())
}
}
pid := openPositionCore(o.owner, o.ticker, o.isLong, size, margin, mark, fee)
dropItem(limits, ownerLimits, o.owner, id)
emitLimit("LimitFill", o, "position", ref(pid))
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 := ""
eachOwned(ownerLimits, owner, func(item any) {
o := item.(*limitOrder)
mark, _ := GetPrice(o.ticker)
out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d", o.id, o.ticker, sideOf(o.isLong), o.size, o.margin, o.limit, mark))
})
return out
}
// AllLimits lists one page of pending orders for the keeper to scan, ';'-joined:
// id,ticker,L|S,limit,mark. The keeper triggers the ones whose condition holds.
func AllLimits(offset, count int) string {
out := ""
eachPage(limits, offset, count, func(item any) {
o := item.(*limitOrder)
mark, _ := GetPrice(o.ticker)
out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d", o.id, o.ticker, sideOf(o.isLong), 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 the quote stands still. The updater pushes the real market
// status each cycle. While it is closed, new perps and limit fills are held to
// closedMaxLeverage (risk.gno), so a gap at the open hits smaller positions.
// Closing, stops, liquidations and spot work as usual so no one is trapped.
var marketOpen = true
// 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 stock market is open, as last pushed by the
// updater. While it is false the leverage cap is closedMaxLeverage.
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 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)")
}
}
// 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
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) and not
// locked. 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")
}
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 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")
}
settlePerp(p, freshPrice(p.ticker), "close")
}
// 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")
}
closePortion(p, closeSize, freshPrice(p.ticker), "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.
// 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 := ""
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",
p.id, p.ticker, sideOf(p.isLong), p.size, p.entry, p.margin, mark, perpPnL(p, mark), liqPrice(p), p.stopLoss, p.takeProfit))
})
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
}
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 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 (
"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")
}
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")
}
// 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 ---
// AllStops lists, within one page of open positions, those with 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(offset, count int) string {
out := ""
eachPage(perps, offset, count, func(item any) {
p := item.(*perp)
if p.stopLoss == 0 && p.takeProfit == 0 {
return
}
mark, _ := GetPrice(p.ticker)
out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d,%d", p.id, p.ticker, sideOf(p.isLong), 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, never from tUSD locked behind perp margin or limit escrow.
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
emitSpot("Buy", buyer, ticker, stockAmount, price, cost)
}
// 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)
if proceeds > freeReserve() {
panic("desk: the reserve cannot cover this sale right now")
}
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
emitSpot("Sell", seller, ticker, stockAmount, price, proceeds)
}
// 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)
}