Playground
board.gno
// Package board is the public OTC board of Trade Window.
//
// A listing says what its owner gives and what they want, in their own
// words. It holds no assets and promises nothing: a deal happens only when
// both parties open a room in gno.land/r/tradewindow/rooms (or wherever that
// realm is deployed) and lock the same version of it. Contact details never
// belong here; everything in this realm is public forever.
package board
import (
"chain"
"chain/runtime/unsafe"
"strconv"
"strings"
"time"
"unicode/utf8"
"gno.land/p/nt/avl/v0"
)
const (
SideBuy = "buy"
SideSell = "sell"
SideSwap = "swap"
MaxGiveLen = 80
MaxWantLen = 80
MaxNoteLen = 280
DefaultDays = 7
MaxDays = 30
// MaxActivePerOwner caps open listings per address.
MaxActivePerOwner = 10
day = 24 * 60 * 60
)
type listing struct {
id uint64
owner address
side string
give string
want string
note string
createdAt int64 // unix seconds of block time
expiresAt int64
closedAt int64 // 0 while open
}
var (
listings avl.Tree // padded id -> *listing
byOwner avl.Tree // address -> []uint64 listing ids, oldest first
lastID uint64
)
// Post publishes a listing and returns its id. side is buy, sell or swap;
// give and want are short phrases such as "50,000 GNOT"; note is optional.
// days is how long the listing stays up: 0 means 7, the most is 30.
func Post(cur realm, side, give, want, note string, days int) uint64 {
owner := callerOf(cur)
refuseCoins(cur)
side = strings.TrimSpace(side)
if side != SideBuy && side != SideSell && side != SideSwap {
panic("side must be buy, sell or swap")
}
give = cleanText("give", give, MaxGiveLen, true)
want = cleanText("want", want, MaxWantLen, true)
note = cleanText("note", note, MaxNoteLen, false)
if days == 0 {
days = DefaultDays
}
if days < 1 || days > MaxDays {
panic("a listing stays up between 1 and 30 days")
}
now := time.Now().Unix()
if activeCount(owner, now) >= MaxActivePerOwner {
panic("you already have 10 open listings: close one first")
}
lastID++
l := &listing{
id: lastID,
owner: owner,
side: side,
give: give,
want: want,
note: note,
createdAt: now,
expiresAt: now + int64(days)*day,
}
listings.Set(listingKey(l.id), l)
var ids []uint64
if v := byOwner.Get(owner.String()); v != nil {
ids = v.([]uint64)
}
byOwner.Set(owner.String(), append(ids, l.id))
chain.Emit("ListingPosted",
"id", strconv.FormatUint(l.id, 10),
"owner", owner.String(),
"side", side,
)
return l.id
}
// Close takes a listing down. Only its owner can close it.
func Close(cur realm, id uint64) {
who := callerOf(cur)
refuseCoins(cur)
l := mustListing(id)
if l.owner != who {
panic("only the owner can close this listing")
}
if l.closedAt != 0 {
panic("this listing is already closed")
}
l.closedAt = time.Now().Unix()
chain.Emit("ListingClosed", "id", strconv.FormatUint(id, 10))
}
func (l *listing) open(now int64) bool {
return l.closedAt == 0 && now < l.expiresAt
}
// activeCount counts the owner's open listings. Listings older than
// MaxDays cannot be open, so the walk stops there.
func activeCount(owner address, now int64) int {
v := byOwner.Get(owner.String())
if v == nil {
return 0
}
ids := v.([]uint64)
oldest := now - MaxDays*day
n := 0
for i := len(ids) - 1; i >= 0 && n < MaxActivePerOwner; i-- {
l := mustListing(ids[i])
if l.createdAt < oldest {
break
}
if l.open(now) {
n++
}
}
return n
}
// cleanText trims s and rejects text that is too long or carries control,
// bidi or zero-width characters.
func cleanText(field, s string, max int, required bool) string {
s = strings.TrimSpace(s)
if required && s == "" {
panic(field + " is required")
}
if !utf8.ValidString(s) {
panic(field + " is not valid text")
}
if utf8.RuneCountInString(s) > max {
panic(field + " is longer than " + strconv.Itoa(max) + " characters")
}
for _, r := range s {
if r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0) ||
(r >= 0x200b && r <= 0x200f) || (r >= 0x202a && r <= 0x202e) ||
(r >= 0x2060 && r <= 0x2069) || r == 0xfeff {
panic(field + " contains characters that are not allowed")
}
}
return s
}
func callerOf(cur realm) address {
if !cur.IsCurrent() {
panic("unauthorized: realm token is not current")
}
return cur.Previous().Address()
}
func refuseCoins(cur realm) {
if !cur.IsCurrent() {
panic("unauthorized: realm token is not current")
}
if cur.Previous().IsUserCall() && len(unsafe.OriginSend()) > 0 {
panic("the board does not take coins")
}
}
func mustListing(id uint64) *listing {
v := listings.Get(listingKey(id))
if v == nil {
panic("listing not found")
}
return v.(*listing)
}
func listingKey(id uint64) string {
s := strconv.FormatUint(id, 10)
if len(s) < 20 {
s = strings.Repeat("0", 20-len(s)) + s
}
return s
}
gnomod.toml
module = "gno.land/r/nym-tradewindow001/board" gno = "0.9" [addpkg] creator = "g1hsxx0r86afsrwxkf38kqq5zursfrgjmp35fcvy" height = 1429482 max_deposit = "5000000ugnot"
json.gno
package board
import (
"strconv"
"strings"
)
// jsonString quotes s as a JSON string. Everything outside printable ASCII
// is written as a \u escape, so the output is plain ASCII.
func jsonString(s string) string {
var b strings.Builder
b.WriteByte('"')
for _, r := range s {
switch {
case r == '"':
b.WriteString(`\"`)
case r == '\\':
b.WriteString(`\\`)
case r >= 0x20 && r < 0x7f:
b.WriteRune(r)
case r > 0xffff:
r -= 0x10000
writeU16(&b, 0xd800+(r>>10))
writeU16(&b, 0xdc00+(r&0x3ff))
default:
writeU16(&b, r)
}
}
b.WriteByte('"')
return b.String()
}
func writeU16(b *strings.Builder, r rune) {
const hex = "0123456789abcdef"
b.WriteString(`\u`)
b.WriteByte(hex[(r>>12)&0xf])
b.WriteByte(hex[(r>>8)&0xf])
b.WriteByte(hex[(r>>4)&0xf])
b.WriteByte(hex[r&0xf])
}
func jsonUint(v uint64) string {
return strconv.FormatUint(v, 10)
}
func jsonInt(v int64) string {
return strconv.FormatInt(v, 10)
}
func jsonBool(v bool) string {
if v {
return "true"
}
return "false"
}
// jsonObject joins already-encoded key/value pairs.
func jsonObject(pairs ...string) string {
if len(pairs)%2 != 0 {
panic("jsonObject needs key/value pairs")
}
var b strings.Builder
b.WriteByte('{')
for i := 0; i < len(pairs); i += 2 {
if i > 0 {
b.WriteByte(',')
}
b.WriteString(jsonString(pairs[i]))
b.WriteByte(':')
b.WriteString(pairs[i+1])
}
b.WriteByte('}')
return b.String()
}
func jsonArray(items []string) string {
return "[" + strings.Join(items, ",") + "]"
}
query.gno
package board
import (
"strconv"
"strings"
"time"
"gno.land/p/nt/markdown/sanitize/v0"
)
const maxPage = 50
// ListingJSON returns one listing, or null.
func ListingJSON(id uint64) string {
v := listings.Get(listingKey(id))
if v == nil {
return "null"
}
return v.(*listing).json(time.Now().Unix())
}
// OpenJSON lists open listings, newest first. side filters by buy, sell or
// swap; "" means all.
func OpenJSON(side string, offset, limit int) string {
offset, limit = page(offset, limit)
now := time.Now().Unix()
items := []string{}
skipped := 0
more := false
oldest := now - MaxDays*day
listings.ReverseIterate("", "", func(_ string, v any) bool {
l := v.(*listing)
if l.createdAt < oldest {
return true // nothing older can still be open
}
if !l.open(now) || (side != "" && l.side != side) {
return false
}
if skipped < offset {
skipped++
return false
}
if len(items) == limit {
more = true
return true
}
items = append(items, l.json(now))
return false
})
return jsonObject(
"listings", jsonArray(items),
"more", jsonBool(more),
"total", jsonUint(lastID),
"now", jsonInt(now),
)
}
// ListingsOfJSON lists every listing of one owner, newest first.
func ListingsOfJSON(owner string, offset, limit int) string {
offset, limit = page(offset, limit)
now := time.Now().Unix()
items := []string{}
var ids []uint64
if v := byOwner.Get(strings.TrimSpace(owner)); v != nil {
ids = v.([]uint64)
}
more := false
for i := len(ids) - 1 - offset; i >= 0; i-- {
if len(items) == limit {
more = true
break
}
items = append(items, mustListing(ids[i]).json(now))
}
return jsonObject(
"listings", jsonArray(items),
"more", jsonBool(more),
"now", jsonInt(now),
)
}
// json describes the listing at block time now (unix seconds).
func (l *listing) json(now int64) string {
return jsonObject(
"id", jsonUint(l.id),
"owner", jsonString(l.owner.String()),
"side", jsonString(l.side),
"give", jsonString(l.give),
"want", jsonString(l.want),
"note", jsonString(l.note),
"open", jsonBool(l.open(now)),
"createdAt", jsonInt(l.createdAt),
"expiresAt", jsonInt(l.expiresAt),
"closedAt", jsonInt(l.closedAt),
)
}
func page(offset, limit int) (int, int) {
if offset < 0 {
offset = 0
}
if limit <= 0 || limit > maxPage {
limit = maxPage
}
return offset, limit
}
// Render shows open listings on gnoweb, and one listing at listing/<id>.
func Render(path string) string {
now := time.Now().Unix()
path = strings.TrimSpace(path)
if rest, ok := strings.CutPrefix(path, "listing/"); ok {
if id, err := strconv.ParseUint(rest, 10, 64); err == nil {
if v := listings.Get(listingKey(id)); v != nil {
return renderListing(v.(*listing), now)
}
}
return "# Not found\n\nNo listing at this address.\n"
}
if path != "" {
return "# Not found\n\nNo listing at this address.\n"
}
var b strings.Builder
b.WriteString("# Trade Window board\n\n")
b.WriteString("Public listings: what someone gives and what they want. ")
b.WriteString("A listing moves nothing; deals settle in a trade room.\n\n")
n := 0
oldest := now - MaxDays*day
listings.ReverseIterate("", "", func(_ string, v any) bool {
l := v.(*listing)
if l.createdAt < oldest {
return true
}
if !l.open(now) {
return false
}
b.WriteString("- [" + sideLabel(l.side) + "](:listing/" + jsonUint(l.id) + "): " +
sanitize.InlineText(l.give) + " for " + sanitize.InlineText(l.want) + "\n")
n++
return n >= 30
})
if n == 0 {
b.WriteString("No open listings.\n")
}
return b.String()
}
func renderListing(l *listing, now int64) string {
var b strings.Builder
b.WriteString("# " + sideLabel(l.side) + ": " + sanitize.InlineText(l.give) + "\n\n")
b.WriteString("Wants: " + sanitize.InlineText(l.want) + "\n\n")
if l.note != "" {
b.WriteString(sanitize.InlineText(l.note) + "\n\n")
}
b.WriteString("Posted by " + sanitize.InlineCode(l.owner.String()) + " on " +
date(l.createdAt) + ". ")
if l.open(now) {
b.WriteString("Open until " + date(l.expiresAt) + ".\n")
} else {
b.WriteString("Closed.\n")
}
return b.String()
}
func sideLabel(side string) string {
switch side {
case SideBuy:
return "Buying"
case SideSell:
return "Selling"
default:
return "Swapping"
}
}
// date writes unix seconds as a UTC calendar date.
func date(unix int64) string {
return time.Unix(unix, 0).UTC().Format("2006-01-02")
}