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.

rooms.gno

16.89 Kb · 620 lines
  1// Package rooms is the on-chain trade window.
  2//
  3// Two parties share a room. Each one puts assets on their own side: native
  4// coins (GNOT and any other bank denom), GRC20 tokens from the registry at
  5// gno.land/r/nt/grc20reg/v0, and GRC721 NFTs from collections registered
  6// with this realm (see RegisterCollection). The realm holds the deposits.
  7//
  8// Every change to the room raises its version. A party locks the room by
  9// naming the exact version they reviewed, so a lock can never apply to
 10// contents the party has not seen. When both sides hold a lock on the
 11// current version, the second lock swaps everything in the same
 12// transaction: the maker's side goes to the taker and the taker's side
 13// goes to the maker.
 14//
 15// Until that moment each party can withdraw their own deposits, and either
 16// party can cancel the room, which returns every deposit to its owner. An
 17// expired room can no longer settle; its deposits stay withdrawable, and
 18// anyone may cancel it to send them home.
 19//
 20// A maker can also turn a room into an offer (see Offer): their side plus an
 21// exact list of what they want in return. The first account allowed to take
 22// the other seat that puts in exactly that list completes the trade in one
 23// transaction (see Fill).
 24//
 25// On settlement the realm keeps a service fee on coins and tokens (see
 26// fee.gno); NFTs, withdrawals and cancellations pay nothing.
 27package rooms
 28
 29import (
 30	"chain"
 31	"chain/banker"
 32	"chain/runtime/unsafe"
 33	"math"
 34	"strconv"
 35	"strings"
 36	"time"
 37
 38	"gno.land/p/nt/avl/v0"
 39	"gno.land/r/nt/grc20reg/v0"
 40)
 41
 42const (
 43	StatusOpen      = "open"
 44	StatusSettled   = "settled"
 45	StatusCancelled = "cancelled"
 46
 47	// statusFilling holds a room for the length of one Fill, so nothing an
 48	// asset's own code runs during the transfers can change it.
 49	statusFilling = "filling"
 50
 51	KindCoin  = "coin"
 52	KindToken = "token"
 53	KindNFT   = "nft"
 54
 55	// MaxAssetsPerSide bounds the work a settlement or refund can do.
 56	MaxAssetsPerSide = 8
 57
 58	DefaultTTLMinutes = 24 * 60
 59	MinTTLMinutes     = 10
 60	MaxTTLMinutes     = 7 * 24 * 60
 61)
 62
 63type asset struct {
 64	kind   string // KindCoin, KindToken or KindNFT
 65	denom  string // bank denom, grc20reg key, or collection key + "#" + token id
 66	amount int64  // always 1 for an NFT
 67}
 68
 69type side struct {
 70	owner  address
 71	assets []asset
 72	locked uint64 // version this side locked; 0 when not locked
 73}
 74
 75// A room keeps both sides inline and its times as unix seconds: every
 76// separate object costs storage deposit, and a room is opened often.
 77type room struct {
 78	id       uint64
 79	maker    side
 80	taker    side
 81	openSeat bool // anyone may take the taker seat with Join
 82	// openMarket rooms take any registered asset; ordinary rooms take only
 83	// verified ones (see verified.gno).
 84	openMarket bool
 85	status     string
 86	version    uint64
 87	// want is the maker's standing offer: exactly what the taker must put
 88	// in for Fill to complete the trade. Any change to the room clears it.
 89	want      []asset
 90	feeBps    uint64 // the fee rate this room was opened with
 91	createdAt int64  // unix seconds of block time
 92	expiresAt int64
 93	closedAt  int64 // 0 while open
 94	closedBy  address
 95}
 96
 97var (
 98	rooms   avl.Tree // padded id -> *room
 99	byParty avl.Tree // address -> []uint64 room ids, oldest first
100	volume  avl.Tree // kind + ":" + denom -> int64 settled amount; NFTs count per collection
101
102	lastID     uint64
103	nSettled   uint64
104	nCancelled uint64
105
106	self address
107)
108
109func init(cur realm) {
110	if !cur.IsCurrent() {
111		panic("unauthorized: realm token is not current")
112	}
113	self = cur.Address()
114	seedVerified()
115	prev := cur.Previous()
116	if prev.IsUserCall() && prev.Address().IsValid() {
117		admin = prev.Address()
118		treasury = admin
119	}
120}
121
122// Open creates a room with the caller as maker and returns its id. The room
123// takes only verified assets (see Verify). counterparty is the taker's
124// address, or "" to leave the seat open for the first account that calls
125// Join. ttlMinutes is how long the room can settle; 0 means 24 hours, and
126// the allowed range is 10 minutes to 7 days.
127func Open(cur realm, counterparty string, ttlMinutes int) uint64 {
128	return open(cur, counterparty, ttlMinutes, false)
129}
130
131// OpenMarket is Open for a room that takes any registered asset, verified
132// or not. Both parties trade unverified assets at their own risk; the app
133// says so in every view of such a room.
134func OpenMarket(cur realm, counterparty string, ttlMinutes int) uint64 {
135	return open(cur, counterparty, ttlMinutes, true)
136}
137
138func open(cur realm, counterparty string, ttlMinutes int, openMarket bool) uint64 {
139	maker := callerOf(cur)
140	refuseCoins(cur)
141	assertNotPaused()
142
143	ttl := ttlMinutes
144	if ttl == 0 {
145		ttl = DefaultTTLMinutes
146	}
147	if ttl < MinTTLMinutes || ttl > MaxTTLMinutes {
148		panic("room lifetime must be between 10 minutes and 7 days")
149	}
150
151	r := &room{
152		maker:      side{owner: maker},
153		status:     StatusOpen,
154		feeBps:     openingFee(),
155		openMarket: openMarket,
156	}
157	counterparty = strings.TrimSpace(counterparty)
158	if counterparty == "" {
159		r.openSeat = true
160	} else {
161		cp := address(counterparty)
162		if !cp.IsValid() {
163			panic("counterparty is not a valid address")
164		}
165		if cp == maker {
166			panic("you cannot open a room with yourself")
167		}
168		r.taker.owner = cp
169	}
170
171	lastID++
172	r.id = lastID
173	r.version = 1
174	now := time.Now().Unix()
175	r.createdAt = now
176	r.expiresAt = now + int64(ttl)*60
177
178	rooms.Set(roomKey(r.id), r)
179	index(maker, r.id)
180	if r.taker.owner != "" {
181		index(r.taker.owner, r.id)
182	}
183
184	chain.Emit("RoomOpened",
185		"id", idString(r.id),
186		"maker", maker.String(),
187		"taker", r.taker.owner.String(),
188		"expires", strconv.FormatInt(r.expiresAt, 10),
189		"openMarket", strconv.FormatBool(openMarket),
190	)
191	return r.id
192}
193
194// Join takes the open taker seat of a room.
195func Join(cur realm, roomID uint64) {
196	who := callerOf(cur)
197	refuseCoins(cur)
198	assertNotPaused()
199
200	r := mustRoom(roomID)
201	r.assertLive()
202	if !r.openSeat {
203		panic("this room is invite only")
204	}
205	if r.taker.owner != "" {
206		panic("the seat is already taken")
207	}
208	if who == r.maker.owner {
209		panic("you opened this room")
210	}
211	if len(r.want) > 0 {
212		panic("this room is an offer: fill it instead")
213	}
214	r.taker.owner = who
215	index(who, r.id)
216	r.bump()
217
218	chain.Emit("RoomJoined", "id", idString(r.id), "taker", who.String())
219}
220
221// DepositCoins adds the coins sent with this call to the caller's side.
222// It must be called directly from the depositing account (maketx call or a
223// wallet MsgCall), because only then are the sent coins guaranteed to have
224// reached this realm.
225func DepositCoins(cur realm, roomID uint64) {
226	if !cur.IsCurrent() {
227		panic("unauthorized: realm token is not current")
228	}
229	prev := cur.Previous()
230	// IsUserCall and OriginSend are a pair: OriginSend describes coins that
231	// actually arrived here only when the caller is the signing account.
232	// A code realm or a maketx run script could spend the envelope first.
233	if !prev.IsUserCall() {
234		panic("send coins with a direct call from your account")
235	}
236	who := prev.Address()
237	sent := unsafe.OriginSend()
238	if len(sent) == 0 {
239		panic("attach the coins to this call")
240	}
241	assertNotPaused()
242
243	r := mustRoom(roomID)
244	r.assertLive()
245	mine, _ := r.sideOf(who)
246	for _, c := range sent {
247		if c.Amount <= 0 {
248			panic("coin amounts must be positive")
249		}
250		r.assertAccepts(KindCoin, c.Denom)
251		mine.add(KindCoin, c.Denom, c.Amount)
252	}
253	r.bump()
254
255	chain.Emit("Deposited",
256		"id", idString(r.id),
257		"party", who.String(),
258		"coins", sent.String(),
259		"version", idString(r.version),
260	)
261}
262
263// DepositToken moves amount of a registered GRC20 token from the caller to
264// this realm and adds it to the caller's side. The caller must first
265// approve this realm's address (see Address) for at least amount.
266func DepositToken(cur realm, roomID uint64, tokenKey string, amount int64) {
267	who := callerOf(cur)
268	refuseCoins(cur)
269	assertNotPaused()
270	if amount <= 0 {
271		panic("amount must be positive")
272	}
273	if grc20reg.Get(tokenKey) == nil {
274		panic("token is not in the GRC20 registry")
275	}
276
277	r := mustRoom(roomID)
278	r.assertLive()
279	mine, _ := r.sideOf(who)
280	r.assertAccepts(KindToken, tokenKey)
281	mine.assertRoomFor(KindToken, tokenKey, amount)
282
283	// This realm is the spender: the owner's allowance to it is what moves.
284	// The canonical GRC20 ledger runs no code of the token's author, so
285	// nothing can call back into this realm before the deposit is recorded.
286	grc20reg.TransferFrom(0, cur, tokenKey, who, cur.Address(), amount)
287	mine.add(KindToken, tokenKey, amount)
288	r.bump()
289
290	chain.Emit("Deposited",
291		"id", idString(r.id),
292		"party", who.String(),
293		"token", tokenKey,
294		"amount", strconv.FormatInt(amount, 10),
295		"version", idString(r.version),
296	)
297}
298
299// WithdrawCoins returns amount of denom from the caller's side to the
300// caller. It works while the room is open, also after it has expired or
301// while the realm is paused.
302func WithdrawCoins(cur realm, roomID uint64, denom string, amount int64) {
303	withdraw(cur, roomID, KindCoin, denom, amount)
304}
305
306// WithdrawToken returns amount of a GRC20 token from the caller's side to
307// the caller. Same rules as WithdrawCoins.
308func WithdrawToken(cur realm, roomID uint64, tokenKey string, amount int64) {
309	withdraw(cur, roomID, KindToken, tokenKey, amount)
310}
311
312func withdraw(cur realm, roomID uint64, kind, denom string, amount int64) {
313	who := callerOf(cur)
314	refuseCoins(cur)
315	if amount <= 0 {
316		panic("amount must be positive")
317	}
318	r := mustRoom(roomID)
319	r.assertOpen()
320	mine, _ := r.sideOf(who)
321	mine.sub(kind, denom, amount)
322	r.bump()
323
324	send(cur, who, asset{kind: kind, denom: denom, amount: amount})
325
326	chain.Emit("Withdrawn",
327		"id", idString(r.id),
328		"party", who.String(),
329		"kind", kind,
330		"denom", denom,
331		"amount", strconv.FormatInt(amount, 10),
332		"version", idString(r.version),
333	)
334}
335
336// Lock records that the caller agrees to swap the room exactly as it is at
337// version. It fails if the room has changed since. When the other side
338// already holds a lock on the same version, this call settles the room and
339// returns "settled"; otherwise it returns "locked".
340func Lock(cur realm, roomID uint64, version uint64) string {
341	who := callerOf(cur)
342	refuseCoins(cur)
343	assertNotPaused()
344
345	r := mustRoom(roomID)
346	r.assertLive()
347	mine, theirs := r.sideOf(who)
348	if r.taker.owner == "" {
349		panic("waiting for a counterparty to join")
350	}
351	if version != r.version {
352		panic("the room changed: review version " + idString(r.version) + " and lock again")
353	}
354	if len(r.maker.assets) == 0 || len(r.taker.assets) == 0 {
355		panic("both sides need at least one asset")
356	}
357	r.assertStillVerified()
358	if mine.locked == version {
359		return "locked"
360	}
361	mine.locked = version
362
363	chain.Emit("Locked",
364		"id", idString(r.id),
365		"party", who.String(),
366		"version", idString(version),
367	)
368
369	if theirs.locked == version {
370		r.settle(cur, who)
371		return StatusSettled
372	}
373	return "locked"
374}
375
376// Unlock withdraws the caller's lock on the current version.
377func Unlock(cur realm, roomID uint64) {
378	who := callerOf(cur)
379	refuseCoins(cur)
380	r := mustRoom(roomID)
381	r.assertOpen()
382	mine, _ := r.sideOf(who)
383	if mine.locked != r.version {
384		panic("you have not locked this version")
385	}
386	mine.locked = 0
387	if who == r.maker.owner {
388		r.want = nil // the maker's lock is what an offer stands on
389	}
390
391	chain.Emit("Unlocked", "id", idString(r.id), "party", who.String())
392}
393
394// Cancel closes an open room and returns every deposit to its owner.
395// Either party may cancel at any time before settlement; once the room has
396// expired, anyone may cancel it.
397func Cancel(cur realm, roomID uint64) {
398	who := callerOf(cur)
399	refuseCoins(cur)
400	r := mustRoom(roomID)
401	r.assertOpen()
402	if !r.isParty(who) && !r.expired() {
403		panic("only the two parties can cancel a room before it expires")
404	}
405
406	r.status = StatusCancelled
407	r.closedAt = time.Now().Unix()
408	r.closedBy = who
409	nCancelled++
410
411	for _, a := range r.maker.assets {
412		send(cur, r.maker.owner, a)
413	}
414	if r.taker.owner != "" {
415		for _, a := range r.taker.assets {
416			send(cur, r.taker.owner, a)
417		}
418	}
419
420	chain.Emit("Cancelled", "id", idString(r.id), "by", who.String())
421}
422
423func (r *room) settle(cur realm, by address) {
424	r.status = StatusSettled
425	r.closedAt = time.Now().Unix()
426	r.closedBy = by
427	nSettled++
428
429	for _, a := range r.maker.assets {
430		r.pay(cur, r.taker.owner, a)
431		addVolume(a)
432	}
433	for _, a := range r.taker.assets {
434		r.pay(cur, r.maker.owner, a)
435		addVolume(a)
436	}
437
438	chain.Emit("Settled",
439		"id", idString(r.id),
440		"maker", r.maker.owner.String(),
441		"taker", r.taker.owner.String(),
442		"version", idString(r.version),
443		"feeBps", strconv.FormatUint(r.feeBps, 10),
444	)
445}
446
447// send pays one asset out of this realm's custody.
448func send(cur realm, to address, a asset) {
449	switch a.kind {
450	case KindCoin:
451		bnk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
452		bnk.SendCoins(cur.Address(), to, chain.Coins{{Denom: a.denom, Amount: a.amount}})
453	case KindToken:
454		grc20reg.Transfer(0, cur, a.denom, to, a.amount)
455	case KindNFT:
456		sendNFT(cur, to, a.denom)
457	default:
458		panic("unknown asset kind")
459	}
460}
461
462// assertRoomFor panics if adding amount of an asset would break a limit.
463func (s *side) assertRoomFor(kind, denom string, amount int64) {
464	for _, a := range s.assets {
465		if a.kind == kind && a.denom == denom {
466			if amount > math.MaxInt64-a.amount {
467				panic("amount is too large")
468			}
469			return
470		}
471	}
472	if len(s.assets) >= MaxAssetsPerSide {
473		panic("a side can hold at most 8 different assets")
474	}
475}
476
477func (s *side) add(kind, denom string, amount int64) {
478	s.assertRoomFor(kind, denom, amount)
479	for i := range s.assets {
480		if s.assets[i].kind == kind && s.assets[i].denom == denom {
481			s.assets[i].amount += amount
482			return
483		}
484	}
485	s.assets = append(s.assets, asset{kind: kind, denom: denom, amount: amount})
486}
487
488func (s *side) sub(kind, denom string, amount int64) {
489	for i := range s.assets {
490		if s.assets[i].kind != kind || s.assets[i].denom != denom {
491			continue
492		}
493		if amount > s.assets[i].amount {
494			panic("you have less than that in the room")
495		}
496		s.assets[i].amount -= amount
497		if s.assets[i].amount == 0 {
498			s.assets = append(s.assets[:i], s.assets[i+1:]...)
499		}
500		return
501	}
502	panic("you have not deposited that asset")
503}
504
505// sideOf returns the caller's side and the other side, or panics for
506// anyone who is not one of the two parties.
507func (r *room) sideOf(who address) (*side, *side) {
508	if who == r.maker.owner {
509		return &r.maker, &r.taker
510	}
511	if r.taker.owner != "" && who == r.taker.owner {
512		return &r.taker, &r.maker
513	}
514	panic("only the two parties of this room can do that")
515}
516
517func (r *room) isParty(who address) bool {
518	return who == r.maker.owner || (r.taker.owner != "" && who == r.taker.owner)
519}
520
521func (r *room) expired() bool {
522	return time.Now().Unix() >= r.expiresAt
523}
524
525func (r *room) assertOpen() {
526	if r.status != StatusOpen {
527		panic("this room is " + r.status)
528	}
529}
530
531// bump records a change to the room: the version moves on, so every lock on
532// an earlier version stops applying, and a standing offer is withdrawn.
533func (r *room) bump() {
534	r.version++
535	r.want = nil
536}
537
538// assertLive is assertOpen plus a check that the room can still settle.
539func (r *room) assertLive() {
540	r.assertOpen()
541	if r.expired() {
542		panic("this room has expired: withdraw or cancel to get deposits back")
543	}
544}
545
546// refuseCoins stops a direct call that carries coins to any function other
547// than DepositCoins. Such coins would reach this realm with nothing
548// recording them; failing the call sends them back.
549func refuseCoins(cur realm) {
550	if !cur.IsCurrent() {
551		panic("unauthorized: realm token is not current")
552	}
553	if cur.Previous().IsUserCall() && len(unsafe.OriginSend()) > 0 {
554		panic("this call does not take coins: use DepositCoins")
555	}
556}
557
558// callerOf names the immediate caller: the realm or account that was
559// current when cur was minted for this crossing call. A crossing
560// function's own cur is always current, so the IsCurrent check is belt and
561// braces; it keeps every identity read in the shape reviewers and the gno
562// audit harness look for.
563func callerOf(cur realm) address {
564	if !cur.IsCurrent() {
565		panic("unauthorized: realm token is not current")
566	}
567	return cur.Previous().Address()
568}
569
570func mustRoom(id uint64) *room {
571	v := rooms.Get(roomKey(id))
572	if v == nil {
573		panic("room not found")
574	}
575	return v.(*room)
576}
577
578// index records that who is a party of room id. One growing list per
579// account keeps a returning trader's next room cheap to store.
580func index(who address, id uint64) {
581	key := who.String()
582	var ids []uint64
583	if v := byParty.Get(key); v != nil {
584		ids = v.([]uint64)
585	}
586	byParty.Set(key, append(ids, id))
587}
588
589func addVolume(a asset) {
590	key := a.kind + ":" + a.denom
591	if a.kind == KindNFT {
592		// One entry per collection, not per token: the tree stays small.
593		collection, _, _ := strings.Cut(a.denom, "#")
594		key = a.kind + ":" + collection
595	}
596	total := int64(0)
597	if v := volume.Get(key); v != nil {
598		total = v.(int64)
599	}
600	// Volume is informational; saturate instead of failing a settlement.
601	if a.amount > math.MaxInt64-total {
602		total = math.MaxInt64
603	} else {
604		total += a.amount
605	}
606	volume.Set(key, total)
607}
608
609// roomKey zero-pads ids so the tree iterates in numeric order.
610func roomKey(id uint64) string {
611	s := strconv.FormatUint(id, 10)
612	if len(s) < 20 {
613		s = strings.Repeat("0", 20-len(s)) + s
614	}
615	return s
616}
617
618func idString(id uint64) string {
619	return strconv.FormatUint(id, 10)
620}