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

11.63 Kb · 351 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	stopsAt    int64 // when the stops were last set; they trigger only on a later price
 40	closeSize  int64 // size of a requested close, 0 for all of it
 41	closeAt    int64 // when a close was requested, 0 when none is waiting
 42}
 43
 44var nextPerpID uint64
 45
 46func mustPerp(id uint64) *perp {
 47	v := perps.Get(idKey(id))
 48	if v == nil {
 49		panic("desk: unknown perp id")
 50	}
 51	return v.(*perp)
 52}
 53
 54// perpPnL is size * (mark - entry) / 1e6 for a long, negated for a short.
 55func perpPnL(p *perp, mark int64) int64 {
 56	pnl := notionalMicroUSD(mark, p.size) - notionalMicroUSD(p.entry, p.size)
 57	if !p.isLong {
 58		pnl = -pnl
 59	}
 60	return pnl
 61}
 62
 63// equity is the position's margin plus unrealized PnL.
 64func perpEquity(p *perp, mark int64) int64 { return p.margin + perpPnL(p, mark) }
 65
 66// liquidatable: equity net of the accrued borrow fee has fallen to the
 67// maintenance fraction of the margin.
 68func liquidatable(p *perp, mark int64) bool {
 69	return perpEquity(p, mark)-holdingFee(p, time.Now().Unix()) <= mulDiv(p.margin, maintBps, bpsDenom)
 70}
 71
 72// liqPrice is the mark price at which the position becomes liquidatable.
 73func liqPrice(p *perp) int64 {
 74	// allowed loss before maintenance = margin * (1 - maintBps/1e4)
 75	allowedLoss := mulDiv(p.margin, bpsDenom-maintBps, bpsDenom) - holdingFee(p, time.Now().Unix())
 76	var drop int64 // micro-USD per share
 77	if allowedLoss >= 0 {
 78		drop = mulDiv(allowedLoss, microUSD, p.size)
 79	} else {
 80		drop = -mulDiv(-allowedLoss, microUSD, p.size)
 81	}
 82	if p.isLong {
 83		return p.entry - drop
 84	}
 85	return p.entry + drop
 86}
 87
 88// assertPerpSize bounds the size so price*size stays inside int64.
 89func assertPerpSize(size int64) {
 90	if size < minTradeUnits {
 91		panic("desk: size below minimum (0.001 share)")
 92	}
 93	if size > maxTradeUnits {
 94		panic("desk: size above maximum (10,000 shares)")
 95	}
 96}
 97
 98func assertMargin(margin int64) {
 99	if margin < minMargin {
100		panic("desk: margin below minimum ($1)")
101	}
102	if margin > maxMargin {
103		panic("desk: margin above maximum ($1,000,000)")
104	}
105}
106
107// openPositionCore validates and creates a perp, assuming `margin`+`fee` tUSD are
108// ALREADY in the desk reserve and not locked. Called when a perp order fills
109// (FillOrder). A panic here reverts the whole tx, so nothing is stranded.
110func openPositionCore(owner address, ticker string, isLong bool, size, margin, price, fee int64) uint64 {
111	assertPerpSize(size)
112	notional := notionalMicroUSD(price, size)
113	if notional <= 0 || notional > perpMaxNotional {
114		panic("desk: notional out of range")
115	}
116	if margin <= 0 || notional > margin*maxLevOf(ticker) {
117		panic("desk: over this market's max leverage")
118	}
119	if sideOI(ticker, isLong)+notional > oiCap(ticker) {
120		panic("desk: open-interest cap reached for this side")
121	}
122	// skew-priced entry on the pre-trade open interest.
123	entry := skewEntry(price, skewImpactBps(ticker, isLong, notional), isLong)
124	accrueFee(fee) // open fee -> liquidity pool yield
125	nextPerpID++
126	id := nextPerpID
127	p := &perp{
128		id: id, owner: owner, ticker: ticker, isLong: isLong,
129		size: size, entry: entry, margin: margin,
130		openTime: time.Now().Unix(),
131	}
132	putItem(perps, ownerPerps, owner, id, p)
133	lock(margin)
134	emitPerpOpen(p)
135	// OI is tracked at entry-notional (same basis subOI uses on close) so skew
136	// impact doesn't silently drift the open-interest sum across many trades.
137	addOI(ticker, isLong, notionalMicroUSD(entry, size))
138	return id
139}
140
141// ClosePerp asks to close the caller's whole position. It closes on the first
142// price observed after the request (FillClose).
143func ClosePerp(cur realm, id uint64) { requestClose(cur.Previous().Address(), id, 0) }
144
145// ClosePartial asks to close `closeSize` units (6 dp) of the caller's position on
146// the first price observed after the request. Allowed while the market is closed.
147func ClosePartial(cur realm, id uint64, closeSize int64) {
148	if closeSize <= 0 {
149		panic("desk: invalid close size")
150	}
151	requestClose(cur.Previous().Address(), id, closeSize)
152}
153
154func requestClose(owner address, id uint64, size int64) {
155	p := mustPerp(id)
156	if p.owner != owner {
157		panic("desk: not your position")
158	}
159	if size > p.size {
160		panic("desk: invalid close size")
161	}
162	if p.closeAt > 0 && time.Now().Unix()-p.closeAt <= orderTTL {
163		panic("desk: a close is already waiting for the next price")
164	}
165	if size == p.size {
166		size = 0
167	}
168	p.closeSize, p.closeAt = size, time.Now().Unix()
169	emitPerp("CloseRequest", p, "size", num(closingSize(p)))
170}
171
172func closingSize(p *perp) int64 {
173	if p.closeAt == 0 {
174		return 0
175	}
176	if p.closeSize == 0 || p.closeSize > p.size {
177		return p.size
178	}
179	return p.closeSize
180}
181
182// FillClose closes a requested position on the first price observed after the
183// request, or drops a request that waited longer than orderTTL. Permissionless.
184func FillClose(cur realm, id uint64) { fillClose(id) }
185
186func fillClose(id uint64) {
187	p := mustPerp(id)
188	if p.closeAt == 0 {
189		panic("desk: no close requested")
190	}
191	if time.Now().Unix()-p.closeAt > orderTTL {
192		p.closeSize, p.closeAt = 0, 0
193		emitPerp("CloseExpire", p)
194		return
195	}
196	if !pricedAfter(p.ticker, p.closeAt) {
197		panic("desk: the close waits for the next price")
198	}
199	mark := freshPrice(p.ticker)
200	size := closingSize(p)
201	p.closeSize, p.closeAt = 0, 0
202	if size == p.size {
203		settlePerp(p, mark, "close")
204		return
205	}
206	closePortion(p, size, mark, "partial")
207}
208
209// Liquidate closes an underwater position. Permissionless: anyone (the desk's
210// keeper bot, or the UI) may call it once the position is at maintenance.
211func Liquidate(cur realm, id uint64) {
212	p := mustPerp(id)
213	mark := freshPrice(p.ticker)
214	if !liquidatable(p, mark) {
215		panic("desk: not liquidatable")
216	}
217	settlePerp(p, mark, "liquidate")
218}
219
220// holdingFee is the borrow fee owed to the pool for keeping a position open:
221// holdRateBpsYear of the entry notional, prorated by seconds held. It prices the
222// pool's directional risk over time — the honest substitute for funding on an
223// oracle-mark desk (there is no perp-vs-spot basis to correct, but the pool is
224// still carrying the position). Overflow-safe: perYear <= 1e11, elapsed clamped.
225func holdingFee(p *perp, now int64) int64 {
226	el := now - p.openTime
227	if el <= 0 {
228		return 0
229	}
230	if el > 60_000_000 { // ~1.9y clamp keeps perYear*el well inside int64
231		el = 60_000_000
232	}
233	perYear := mulDiv(notionalMicroUSD(p.entry, p.size), holdRateBpsYear, bpsDenom)
234	return mulDiv(perYear, el, secondsYear)
235}
236
237// sliceSettle computes the numbers for closing `sz` units of a position at `mark`:
238// pro-rata margin, the slice's PnL, the close fee and the borrow fee, and the owner
239// payout (floored at 0). Pure — no transfers — so it is unit-tested directly.
240func sliceSettle(p *perp, sz int64, mark int64, now int64) (payout, fee, hold, marginSlice int64) {
241	marginSlice = mulDiv(p.margin, sz, p.size)
242	pnl := notionalMicroUSD(mark, sz) - notionalMicroUSD(p.entry, sz)
243	if !p.isLong {
244		pnl = -pnl
245	}
246	fee = mulDiv(notionalMicroUSD(mark, sz), perpFeeBps, bpsDenom)
247	hold = mulDiv(holdingFee(p, now), sz, p.size)
248	payout = marginSlice + pnl - fee - hold
249	if payout < 0 {
250		payout = 0
251	}
252	return payout, fee, hold, marginSlice
253}
254
255// collectedFee caps a close's fees at the equity the closed slice still had.
256func collectedFee(p *perp, sz, mark, marginSlice, owed int64) int64 {
257	pnl := notionalMicroUSD(mark, sz) - notionalMicroUSD(p.entry, sz)
258	if !p.isLong {
259		pnl = -pnl
260	}
261	equity := marginSlice + pnl
262	if equity < 0 {
263		return 0
264	}
265	if equity < owed {
266		return equity
267	}
268	return owed
269}
270
271// closePortion closes `sz` units of the position at `mark`: pays the owner the slice
272// payout, routes the fees to the pool, releases the slice's open interest, and
273// shrinks the position (or removes it when `sz` is the whole size). Leverage, entry
274// and liq price of the remainder are unchanged (margin and size shrink together).
275func closePortion(p *perp, sz int64, mark int64, kind string) {
276	if sz <= 0 || sz > p.size {
277		panic("desk: invalid close size")
278	}
279	payout, fee, hold, marginSlice := sliceSettle(p, sz, mark, time.Now().Unix())
280	unlock(marginSlice)
281	if free := freeReserve(); payout > free {
282		payout = free // profit comes only from tUSD nobody else is owed
283	}
284	if payout > 0 {
285		if err := usdLedger.Transfer(deskAddr, p.owner, payout); err != nil {
286			panic(err.Error())
287		}
288	}
289	accrueFee(collectedFee(p, sz, mark, marginSlice, fee+hold)) // only what the margin covered
290	subOI(p.ticker, p.isLong, notionalMicroUSD(p.entry, sz))
291	emitPerpClose(p, kind, sz, mark, payout)
292	if sz == p.size {
293		dropItem(perps, ownerPerps, p.owner, p.id)
294	} else {
295		p.size -= sz
296		p.margin -= marginSlice
297	}
298}
299
300// settlePerp fully closes and removes the position.
301func settlePerp(p *perp, mark int64, kind string) { closePortion(p, p.size, mark, kind) }
302
303// --- reads for the UI ---
304
305// PerpsOf returns the caller's open positions, one per line, fields comma-
306// separated: id,ticker,L|S,size,entry,margin,mark,pnl,liq,stopLoss,takeProfit,closing.
307// Money and size are integers at 6 dp; mark/pnl/liq are computed live. Stop prices
308// are 0 when unset; closing is the size of a close waiting for the next price.
309func PerpsOf(owner address) string {
310	out := ""
311	eachOwned(ownerPerps, owner, func(item any) {
312		p := item.(*perp)
313		mark, _ := GetPrice(p.ticker)
314		out = joinRow(out, ufmt.Sprintf("%d,%s,%s,%d,%d,%d,%d,%d,%d,%d,%d,%d",
315			p.id, p.ticker, sideOf(p.isLong), p.size, p.entry, p.margin, mark, perpPnL(p, mark), liqPrice(p), p.stopLoss, p.takeProfit, closingSize(p)))
316	})
317	return out
318}
319
320// AllLiquidatable lists, within one page of open positions, the ids at or below
321// maintenance on a fresh quote, ';'-joined, for the keeper.
322func AllLiquidatable(offset, count int) string {
323	out := ""
324	eachPage(perps, offset, count, func(item any) {
325		p := item.(*perp)
326		if !IsFresh(p.ticker) {
327			return
328		}
329		if mark, _ := GetPrice(p.ticker); liquidatable(p, mark) {
330			out = joinRow(out, ufmt.Sprintf("%d", p.id))
331		}
332	})
333	return out
334}
335
336// ReadyCloses lists, within one page of open positions, the ids FillClose would
337// act on now, ';'-joined, for the keeper.
338func ReadyCloses(offset, count int) string {
339	out := ""
340	now := time.Now().Unix()
341	eachPage(perps, offset, count, func(item any) {
342		p := item.(*perp)
343		if p.closeAt == 0 {
344			return
345		}
346		if now-p.closeAt > orderTTL || (pricedAfter(p.ticker, p.closeAt) && IsFresh(p.ticker)) {
347			out = joinRow(out, ufmt.Sprintf("%d", p.id))
348		}
349	})
350	return out
351}