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.

trade.gno

3.87 Kb · 105 lines
  1package lastcall
  2
  3// Spot trading against the desk. The desk quotes the oracle price and takes a
  4// fee on each side; it is the counterparty to every trade. Buys pull tUSD from
  5// the user and mint sStock; sells burn sStock and pay tUSD from the desk
  6// reserve, never from tUSD locked behind perp margin or limit escrow.
  7
  8const (
  9	feeBps        = 30            // 0.30% desk fee each side
 10	bpsDenom      = 10000         //
 11	microUSD      = 1000000       // 1 tUSD = 1_000000 micro; 1 share = 1_000000 units
 12	minTradeUnits = 1000          // 0.001 share minimum, blocks dust
 13	maxTradeUnits = 10_000_000000 // 10,000 shares max, keeps price*amount in int64
 14)
 15
 16// notionalMicroUSD returns price * stockAmount / 1e6 — the micro-USD value of
 17// stockAmount units (6 dp) of a stock quoted at `price` micro-USD per share.
 18func notionalMicroUSD(price, stockAmount int64) int64 {
 19	return mulDiv(price, stockAmount, microUSD)
 20}
 21
 22func assertTradeSize(stockAmount int64) {
 23	if stockAmount < minTradeUnits {
 24		panic("desk: amount below minimum (0.001 share)")
 25	}
 26	if stockAmount > maxTradeUnits {
 27		panic("desk: amount above maximum (10,000 shares)")
 28	}
 29}
 30
 31// Buy mints stockAmount units (6 dp) of sTicker to the caller and charges tUSD
 32// at the desk price plus fee. Caller must already hold enough tUSD.
 33func Buy(cur realm, ticker string, stockAmount int64) {
 34	assertTradeSize(stockAmount)
 35	s := mustStock(ticker)
 36	price := freshPrice(ticker)
 37	notional := notionalMicroUSD(price, stockAmount)
 38	cost := mulDiv(notional, bpsDenom+feeBps, bpsDenom)
 39	if cost <= 0 {
 40		panic("desk: trade too small")
 41	}
 42	buyer := cur.Previous().Address()
 43	if err := usdLedger.Transfer(buyer, deskAddr, cost); err != nil {
 44		panic(err.Error())
 45	}
 46	if err := s.ledger.Mint(buyer, stockAmount); err != nil {
 47		panic(err.Error())
 48	}
 49	addCost(buyer, ticker, notional) // cost basis for the UI's avg entry
 50	accrueFee(cost - notional)       // desk fee -> liquidity pool yield
 51	emitSpot("Buy", buyer, ticker, stockAmount, price, cost)
 52}
 53
 54// Sell burns stockAmount units of sTicker from the caller and pays tUSD at the
 55// desk price minus fee, from the desk reserve.
 56func Sell(cur realm, ticker string, stockAmount int64) {
 57	assertTradeSize(stockAmount)
 58	s := mustStock(ticker)
 59	price := freshPrice(ticker)
 60	notional := notionalMicroUSD(price, stockAmount)
 61	proceeds := mulDiv(notional, bpsDenom-feeBps, bpsDenom)
 62	if proceeds > freeReserve() {
 63		panic("desk: the reserve cannot cover this sale right now")
 64	}
 65	seller := cur.Previous().Address()
 66	heldBefore := s.token.BalanceOf(seller)
 67	if err := s.ledger.Burn(seller, stockAmount); err != nil {
 68		panic(err.Error())
 69	}
 70	if err := usdLedger.Transfer(deskAddr, seller, proceeds); err != nil {
 71		panic(err.Error())
 72	}
 73	reduceCost(seller, ticker, stockAmount, heldBefore) // keep avg entry across sells
 74	accrueFee(notional - proceeds)                      // desk fee -> liquidity pool yield
 75	emitSpot("Sell", seller, ticker, stockAmount, price, proceeds)
 76}
 77
 78// QuoteBuy / QuoteSell are read-only helpers for the UI: the tUSD cost/proceeds
 79// of trading stockAmount units at the current price.
 80func QuoteBuy(ticker string, stockAmount int64) int64 {
 81	assertTradeSize(stockAmount)
 82	price, _ := GetPrice(ticker)
 83	return mulDiv(notionalMicroUSD(price, stockAmount), bpsDenom+feeBps, bpsDenom)
 84}
 85
 86func QuoteSell(ticker string, stockAmount int64) int64 {
 87	assertTradeSize(stockAmount)
 88	price, _ := GetPrice(ticker)
 89	return mulDiv(notionalMicroUSD(price, stockAmount), bpsDenom-feeBps, bpsDenom)
 90}
 91
 92// SeedUSD mints tUSD into the desk reserve so it can pay out on sells and
 93// in-the-money perps. Admin only — the desk's bootstrap liquidity.
 94func SeedUSD(cur realm, amount int64) {
 95	assertAdmin(cur)
 96	if amount <= 0 {
 97		panic("desk: amount must be positive")
 98	}
 99	if err := usdLedger.Mint(deskAddr, amount); err != nil {
100		panic(err.Error())
101	}
102}
103
104// DeskReserveUSD is the desk's own tUSD balance.
105func DeskReserveUSD() int64 { return usd.BalanceOf(deskAddr) }