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.

render.gno

6.08 Kb · 185 lines
  1package rooms
  2
  3import (
  4	"strconv"
  5	"strings"
  6	"time"
  7
  8	"gno.land/p/nt/markdown/sanitize/v0"
  9	"gno.land/r/nt/grc20reg/v0"
 10)
 11
 12// Render shows the realm on gnoweb: the home page lists recent rooms, and
 13// room/<id> shows one room. Every value that comes from a caller goes
 14// through sanitize before it reaches the markdown.
 15func Render(path string) string {
 16	path = strings.TrimSpace(path)
 17	if path == "" {
 18		return renderHome()
 19	}
 20	if rest, ok := strings.CutPrefix(path, "room/"); ok {
 21		id, err := strconv.ParseUint(rest, 10, 64)
 22		if err == nil {
 23			if v := rooms.Get(roomKey(id)); v != nil {
 24				return renderRoom(v.(*room), time.Now().Unix())
 25			}
 26		}
 27	}
 28	return "# Not found\n\nNo room at this address.\n"
 29}
 30
 31func renderHome() string {
 32	now := time.Now().Unix()
 33	var b strings.Builder
 34	b.WriteString("# Trade Window rooms\n\n")
 35	b.WriteString("Two parties put assets into a room. Each change raises the room's version. ")
 36	b.WriteString("Both lock the same version, and the second lock swaps everything in one transaction. ")
 37	b.WriteString("Until then either side can withdraw or cancel. ")
 38	b.WriteString("A room can also be an offer: the maker's side and an exact list of what they want, filled by the first allowed account in one transaction.\n\n")
 39	if fee := openingFee(); fee > 0 {
 40		b.WriteString("Service fee on settlement: " + decimal(int64(fee), 2) + "% of every coin and token that crosses, from each side. NFTs, withdrawals and cancellations pay nothing.\n\n")
 41	}
 42	b.WriteString("Rooms opened: " + jsonUint(lastID) +
 43		", settled: " + jsonUint(nSettled) +
 44		", cancelled: " + jsonUint(nCancelled) + ".\n\n")
 45	if paused {
 46		b.WriteString("New activity is paused. Withdraw, unlock and cancel still work.\n\n")
 47	}
 48	if lastID == 0 {
 49		b.WriteString("No rooms yet.\n")
 50		return b.String()
 51	}
 52	b.WriteString("## Latest\n\n")
 53	rooms.ReverseIterateByOffset(0, 20, func(_ string, v any) bool {
 54		r := v.(*room)
 55		b.WriteString("- [Room " + jsonUint(r.id) + "](:room/" + jsonUint(r.id) + "): " +
 56			r.statusLabel(now) + ", " + sideSummary(&r.maker) + " for " + sideSummary(&r.taker) + "\n")
 57		return false
 58	})
 59	return b.String()
 60}
 61
 62func renderRoom(r *room, now int64) string {
 63	var b strings.Builder
 64	b.WriteString("# Room " + jsonUint(r.id) + "\n\n")
 65	b.WriteString("Status: " + r.statusLabel(now) + ", version " + jsonUint(r.version) + ".\n\n")
 66	b.WriteString("Opened " + stamp(r.createdAt))
 67	if r.status == StatusOpen {
 68		b.WriteString(". Can settle until " + stamp(r.expiresAt))
 69	} else if r.closedAt != 0 {
 70		b.WriteString(". Closed " + stamp(r.closedAt))
 71	}
 72	b.WriteString(".")
 73	if r.openMarket {
 74		b.WriteString(" Open market: this room takes any registered asset, verified or not.")
 75	} else {
 76		b.WriteString(" Verified assets only.")
 77	}
 78	if r.feeBps > 0 {
 79		b.WriteString(" Fee on settlement: " + decimal(int64(r.feeBps), 2) + "% of coins and tokens, from each side.")
 80	}
 81	b.WriteString("\n\n")
 82	b.WriteString(renderSide("Maker", &r.maker, r.version))
 83	if len(r.want) > 0 {
 84		b.WriteString("## Offer\n\nThe maker wants exactly this in return; the first allowed account that puts it in completes the trade:\n\n")
 85		for _, a := range r.want {
 86			b.WriteString("- " + sanitize.InlineText(formatAsset(a)) + ", " + sanitize.InlineCode(a.denom) + "\n")
 87		}
 88		b.WriteString("\n")
 89	}
 90	if r.taker.owner == "" && len(r.want) > 0 {
 91		b.WriteString("## Taker\n\nThe seat is open: any account can fill the offer.\n\n")
 92	} else if r.taker.owner == "" {
 93		b.WriteString("## Taker\n\nThe seat is open: any account can join.\n\n")
 94	} else {
 95		b.WriteString(renderSide("Taker", &r.taker, r.version))
 96	}
 97	return b.String()
 98}
 99
100func renderSide(title string, s *side, version uint64) string {
101	var b strings.Builder
102	b.WriteString("## " + title + "\n\n")
103	b.WriteString(sanitize.InlineCode(s.owner.String()))
104	if s.locked != 0 && s.locked == version {
105		b.WriteString(", locked this version")
106	}
107	b.WriteString("\n\n")
108	if len(s.assets) == 0 {
109		b.WriteString("Nothing deposited.\n\n")
110		return b.String()
111	}
112	for _, a := range s.assets {
113		b.WriteString("- " + sanitize.InlineText(formatAsset(a)) + ", " + sanitize.InlineCode(a.denom) + "\n")
114	}
115	b.WriteString("\n")
116	return b.String()
117}
118
119func sideSummary(s *side) string {
120	if len(s.assets) == 0 {
121		return "nothing"
122	}
123	parts := make([]string, 0, len(s.assets))
124	for _, a := range s.assets {
125		parts = append(parts, sanitize.InlineText(formatAsset(a)))
126	}
127	return strings.Join(parts, " and ")
128}
129
130// wugnotKey is wrapped GNOT in the GRC20 registry. Its token declares 0
131// decimals because one unit is one ugnot, so it is shown in GNOT like the
132// coin, marked as wrapped so the two are never confused.
133const wugnotKey = "gno.land/r/gnoland/wugnot.wugnot"
134
135// formatAsset writes an amount in whole units: GNOT for ugnot and wrapped
136// GNOT, the registry's symbol and decimals for other tokens, the raw denom
137// otherwise.
138func formatAsset(a asset) string {
139	switch {
140	case a.kind == KindCoin && a.denom == "ugnot":
141		return decimal(a.amount, 6) + " GNOT"
142	case a.kind == KindToken && a.denom == wugnotKey:
143		return decimal(a.amount, 6) + " GNOT (wrapped)"
144	case a.kind == KindToken:
145		if tok := grc20reg.Get(a.denom); tok != nil {
146			return decimal(a.amount, tok.GetDecimals()) + " " + tok.GetSymbol()
147		}
148	case a.kind == KindNFT:
149		key, tid, _ := strings.Cut(a.denom, "#")
150		if v := collections.Get(key); v != nil {
151			return "NFT " + v.(*collection).token.GetName() + " #" + tid
152		}
153		return "NFT #" + tid
154	}
155	return strconv.FormatInt(a.amount, 10) + " " + a.denom
156}
157
158// decimal formats amount with the given number of decimals and no
159// trailing zeros.
160func decimal(amount int64, decimals int) string {
161	s := strconv.FormatInt(amount, 10)
162	if decimals <= 0 {
163		return s
164	}
165	if len(s) <= decimals {
166		s = strings.Repeat("0", decimals-len(s)+1) + s
167	}
168	whole, frac := s[:len(s)-decimals], strings.TrimRight(s[len(s)-decimals:], "0")
169	if frac == "" {
170		return whole
171	}
172	return whole + "." + frac
173}
174
175func (r *room) statusLabel(now int64) string {
176	if r.status == StatusOpen && now >= r.expiresAt {
177		return "expired"
178	}
179	return r.status
180}
181
182// stamp writes unix seconds as an RFC 3339 time in UTC.
183func stamp(unix int64) string {
184	return time.Unix(unix, 0).UTC().Format(time.RFC3339)
185}