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.

perp.gno

10.55 Kb · 304 lines
  1package lastcall
  2
  3// Perpetual stock positions against the desk. Isolated margin, the desk is the
  4// counterparty. Margin is tUSD locked in the desk reserve; profit is paid from
  5// the reserve on close, loss is kept by the desk, both capped at the margin
  6// (isolated). Mark price = the desk reference price (same feed as spot), so
  7// there is no perp-vs-spot basis and no funding in this version.
  8//
  9// All money is micro-USD (6 dp); size is stock units (6 dp), like spot.
 10
 11import (
 12	"time"
 13
 14	"gno.land/p/nt/ufmt/v0"
 15)
 16
 17const (
 18	perpFeeBps      = 10               // 0.10% of notional, each side (open + close)
 19	maxLeverage     = 10               // 10x: notional <= margin * 10
 20	maintBps        = 1000             // 10% maintenance: liquidatable when equity <= 10% of margin
 21	minMargin       = 1_000000         // $1 minimum margin, blocks dust
 22	perpMaxNotional = 1_000_000_000000 // $1,000,000 notional cap
 23	maxMargin       = 1_000_000_000000
 24	holdRateBpsYear = 1000       // 10%/yr borrow fee on notional while a position is open
 25	secondsYear     = 31_536_000 // 365d, for prorating the borrow fee
 26)
 27
 28type perp struct {
 29	id         uint64
 30	owner      address
 31	ticker     string
 32	isLong     bool
 33	size       int64 // stock units (6 dp), > 0
 34	entry      int64 // micro-USD per share at open
 35	margin     int64 // tUSD micro locked for this position
 36	openTime   int64 // block time at open (unix seconds), for the borrow fee
 37	stopLoss   int64 // optional stop-loss trigger, micro-USD/share (0 = unset)
 38	takeProfit int64 // optional take-profit trigger, micro-USD/share (0 = unset)
 39}
 40
 41var nextPerpID uint64
 42
 43func mustPerp(id uint64) *perp {
 44	v := perps.Get(idKey(id))
 45	if v == nil {
 46		panic("desk: unknown perp id")
 47	}
 48	return v.(*perp)
 49}
 50
 51// perpPnL is size * (mark - entry) / 1e6 for a long, negated for a short.
 52func perpPnL(p *perp, mark int64) int64 {
 53	pnl := notionalMicroUSD(mark, p.size) - notionalMicroUSD(p.entry, p.size)
 54	if !p.isLong {
 55		pnl = -pnl
 56	}
 57	return pnl
 58}
 59
 60// equity is the position's margin plus unrealized PnL.
 61func perpEquity(p *perp, mark int64) int64 { return p.margin + perpPnL(p, mark) }
 62
 63// liquidatable: equity net of the accrued borrow fee has fallen to the
 64// maintenance fraction of the margin.
 65func liquidatable(p *perp, mark int64) bool {
 66	return perpEquity(p, mark)-holdingFee(p, time.Now().Unix()) <= mulDiv(p.margin, maintBps, bpsDenom)
 67}
 68
 69// liqPrice is the mark price at which the position becomes liquidatable.
 70func liqPrice(p *perp) int64 {
 71	// allowed loss before maintenance = margin * (1 - maintBps/1e4)
 72	allowedLoss := mulDiv(p.margin, bpsDenom-maintBps, bpsDenom) - holdingFee(p, time.Now().Unix())
 73	var drop int64 // micro-USD per share
 74	if allowedLoss >= 0 {
 75		drop = mulDiv(allowedLoss, microUSD, p.size)
 76	} else {
 77		drop = -mulDiv(-allowedLoss, microUSD, p.size)
 78	}
 79	if p.isLong {
 80		return p.entry - drop
 81	}
 82	return p.entry + drop
 83}
 84
 85// assertPerpSize bounds the size so price*size stays inside int64.
 86func assertPerpSize(size int64) {
 87	if size < minTradeUnits {
 88		panic("desk: size below minimum (0.001 share)")
 89	}
 90	if size > maxTradeUnits {
 91		panic("desk: size above maximum (10,000 shares)")
 92	}
 93}
 94
 95func assertMargin(margin int64) {
 96	if margin < minMargin {
 97		panic("desk: margin below minimum ($1)")
 98	}
 99	if margin > maxMargin {
100		panic("desk: margin above maximum ($1,000,000)")
101	}
102}
103
104// OpenPerp opens a long or short on `ticker` of `size` stock units (6 dp), backed
105// by `margin` tUSD micro pulled from the caller (plus the open fee). Market order.
106func OpenPerp(cur realm, ticker string, isLong bool, size int64, margin int64) uint64 {
107	_ = mustStock(ticker) // only real markets
108	assertPerpSize(size)
109	assertMargin(margin)
110	price := freshPrice(ticker)
111	notional := notionalMicroUSD(price, size)
112	fee := mulDiv(notional, perpFeeBps, bpsDenom)
113	owner := cur.Previous().Address()
114	if err := usdLedger.Transfer(owner, deskAddr, margin+fee); err != nil {
115		panic(err.Error())
116	}
117	return openPositionCore(owner, ticker, isLong, size, margin, price, fee)
118}
119
120// openPositionCore validates and creates a perp, assuming `margin`+`fee` tUSD are
121// ALREADY in the desk reserve (pulled from the owner by the caller) and not
122// locked. Shared by
123// market opens (OpenPerp) and limit-order execution (TriggerLimit). A panic here
124// reverts the whole tx, including the funds pull, so nothing is stranded.
125func openPositionCore(owner address, ticker string, isLong bool, size, margin, price, fee int64) uint64 {
126	assertPerpSize(size)
127	notional := notionalMicroUSD(price, size)
128	if notional <= 0 || notional > perpMaxNotional {
129		panic("desk: notional out of range")
130	}
131	if margin <= 0 || notional > margin*maxLevOf(ticker) {
132		panic("desk: over this market's max leverage")
133	}
134	if sideOI(ticker, isLong)+notional > oiCap(ticker) {
135		panic("desk: open-interest cap reached for this side")
136	}
137	// skew-priced entry on the pre-trade open interest.
138	entry := skewEntry(price, skewImpactBps(ticker, isLong, notional), isLong)
139	accrueFee(fee) // open fee -> liquidity pool yield
140	nextPerpID++
141	id := nextPerpID
142	p := &perp{
143		id: id, owner: owner, ticker: ticker, isLong: isLong,
144		size: size, entry: entry, margin: margin,
145		openTime: time.Now().Unix(),
146	}
147	putItem(perps, ownerPerps, owner, id, p)
148	lock(margin)
149	emitPerpOpen(p)
150	// OI is tracked at entry-notional (same basis subOI uses on close) so skew
151	// impact doesn't silently drift the open-interest sum across many trades.
152	addOI(ticker, isLong, notionalMicroUSD(entry, size))
153	return id
154}
155
156// ClosePerp closes the caller's own position at the current mark and settles.
157func ClosePerp(cur realm, id uint64) {
158	p := mustPerp(id)
159	if p.owner != cur.Previous().Address() {
160		panic("desk: not your position")
161	}
162	settlePerp(p, freshPrice(p.ticker), "close")
163}
164
165// ClosePartial closes `closeSize` units (6 dp) of the caller's own position at the
166// current mark, leaving the rest open. Always allowed, even when the market is
167// closed. closeSize == the full size behaves like ClosePerp.
168func ClosePartial(cur realm, id uint64, closeSize int64) {
169	p := mustPerp(id)
170	if p.owner != cur.Previous().Address() {
171		panic("desk: not your position")
172	}
173	if closeSize <= 0 || closeSize > p.size {
174		panic("desk: invalid close size")
175	}
176	closePortion(p, closeSize, freshPrice(p.ticker), "partial")
177}
178
179// Liquidate closes an underwater position. Permissionless: anyone (the desk's
180// keeper bot, or the UI) may call it once the position is at maintenance.
181func Liquidate(cur realm, id uint64) {
182	p := mustPerp(id)
183	mark := freshPrice(p.ticker)
184	if !liquidatable(p, mark) {
185		panic("desk: not liquidatable")
186	}
187	settlePerp(p, mark, "liquidate")
188}
189
190// holdingFee is the borrow fee owed to the pool for keeping a position open:
191// holdRateBpsYear of the entry notional, prorated by seconds held. It prices the
192// pool's directional risk over time — the honest substitute for funding on an
193// oracle-mark desk (there is no perp-vs-spot basis to correct, but the pool is
194// still carrying the position). Overflow-safe: perYear <= 1e11, elapsed clamped.
195func holdingFee(p *perp, now int64) int64 {
196	el := now - p.openTime
197	if el <= 0 {
198		return 0
199	}
200	if el > 60_000_000 { // ~1.9y clamp keeps perYear*el well inside int64
201		el = 60_000_000
202	}
203	perYear := mulDiv(notionalMicroUSD(p.entry, p.size), holdRateBpsYear, bpsDenom)
204	return mulDiv(perYear, el, secondsYear)
205}
206
207// sliceSettle computes the numbers for closing `sz` units of a position at `mark`:
208// pro-rata margin, the slice's PnL, the close fee and the borrow fee, and the owner
209// payout (floored at 0). Pure — no transfers — so it is unit-tested directly.
210func sliceSettle(p *perp, sz int64, mark int64, now int64) (payout, fee, hold, marginSlice int64) {
211	marginSlice = mulDiv(p.margin, sz, p.size)
212	pnl := notionalMicroUSD(mark, sz) - notionalMicroUSD(p.entry, sz)
213	if !p.isLong {
214		pnl = -pnl
215	}
216	fee = mulDiv(notionalMicroUSD(mark, sz), perpFeeBps, bpsDenom)
217	hold = mulDiv(holdingFee(p, now), sz, p.size)
218	payout = marginSlice + pnl - fee - hold
219	if payout < 0 {
220		payout = 0
221	}
222	return payout, fee, hold, marginSlice
223}
224
225// collectedFee caps a close's fees at the equity the closed slice still had.
226func collectedFee(p *perp, sz, mark, marginSlice, owed int64) int64 {
227	pnl := notionalMicroUSD(mark, sz) - notionalMicroUSD(p.entry, sz)
228	if !p.isLong {
229		pnl = -pnl
230	}
231	equity := marginSlice + pnl
232	if equity < 0 {
233		return 0
234	}
235	if equity < owed {
236		return equity
237	}
238	return owed
239}
240
241// closePortion closes `sz` units of the position at `mark`: pays the owner the slice
242// payout, routes the fees to the pool, releases the slice's open interest, and
243// shrinks the position (or removes it when `sz` is the whole size). Leverage, entry
244// and liq price of the remainder are unchanged (margin and size shrink together).
245func closePortion(p *perp, sz int64, mark int64, kind string) {
246	if sz <= 0 || sz > p.size {
247		panic("desk: invalid close size")
248	}
249	payout, fee, hold, marginSlice := sliceSettle(p, sz, mark, time.Now().Unix())
250	unlock(marginSlice)
251	if free := freeReserve(); payout > free {
252		payout = free // profit comes only from tUSD nobody else is owed
253	}
254	if payout > 0 {
255		if err := usdLedger.Transfer(deskAddr, p.owner, payout); err != nil {
256			panic(err.Error())
257		}
258	}
259	accrueFee(collectedFee(p, sz, mark, marginSlice, fee+hold)) // only what the margin covered
260	subOI(p.ticker, p.isLong, notionalMicroUSD(p.entry, sz))
261	emitPerpClose(p, kind, sz, mark, payout)
262	if sz == p.size {
263		dropItem(perps, ownerPerps, p.owner, p.id)
264	} else {
265		p.size -= sz
266		p.margin -= marginSlice
267	}
268}
269
270// settlePerp fully closes and removes the position.
271func settlePerp(p *perp, mark int64, kind string) { closePortion(p, p.size, mark, kind) }
272
273// --- reads for the UI ---
274
275// PerpsOf returns the caller's open positions, one per line, fields comma-
276// separated: id,ticker,L|S,size,entry,margin,mark,pnl,liq,stopLoss,takeProfit.
277// Money and size are integers at 6 dp; mark/pnl/liq are computed live. Stop prices
278// are 0 when unset. Empty string if none.
279func PerpsOf(owner address) string {
280	out := ""
281	eachOwned(ownerPerps, owner, func(item any) {
282		p := item.(*perp)
283		mark, _ := GetPrice(p.ticker)
284		out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d,%d,%d,%d,%d",
285			p.id, p.ticker, sideOf(p.isLong), p.size, p.entry, p.margin, mark, perpPnL(p, mark), liqPrice(p), p.stopLoss, p.takeProfit))
286	})
287	return out
288}
289
290// AllLiquidatable lists, within one page of open positions, the ids at or below
291// maintenance on a fresh quote, ';'-joined, for the keeper.
292func AllLiquidatable(offset, count int) string {
293	out := ""
294	eachPage(perps, offset, count, func(item any) {
295		p := item.(*perp)
296		if !IsFresh(p.ticker) {
297			return
298		}
299		if mark, _ := GetPrice(p.ticker); liquidatable(p, mark) {
300			out = joinRow(out, ufmt.Sprintf("%d", p.id))
301		}
302	})
303	return out
304}