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.

board.gno

4.79 Kb · 203 lines
  1// Package board is the public OTC board of Trade Window.
  2//
  3// A listing says what its owner gives and what they want, in their own
  4// words. It holds no assets and promises nothing: a deal happens only when
  5// both parties open a room in gno.land/r/tradewindow/rooms (or wherever that
  6// realm is deployed) and lock the same version of it. Contact details never
  7// belong here; everything in this realm is public forever.
  8package board
  9
 10import (
 11	"chain"
 12	"chain/runtime/unsafe"
 13	"strconv"
 14	"strings"
 15	"time"
 16	"unicode/utf8"
 17
 18	"gno.land/p/nt/avl/v0"
 19)
 20
 21const (
 22	SideBuy  = "buy"
 23	SideSell = "sell"
 24	SideSwap = "swap"
 25
 26	MaxGiveLen = 80
 27	MaxWantLen = 80
 28	MaxNoteLen = 280
 29
 30	DefaultDays = 7
 31	MaxDays     = 30
 32
 33	// MaxActivePerOwner caps open listings per address.
 34	MaxActivePerOwner = 10
 35
 36	day = 24 * 60 * 60
 37)
 38
 39type listing struct {
 40	id        uint64
 41	owner     address
 42	side      string
 43	give      string
 44	want      string
 45	note      string
 46	createdAt int64 // unix seconds of block time
 47	expiresAt int64
 48	closedAt  int64 // 0 while open
 49}
 50
 51var (
 52	listings avl.Tree // padded id -> *listing
 53	byOwner  avl.Tree // address -> []uint64 listing ids, oldest first
 54	lastID   uint64
 55)
 56
 57// Post publishes a listing and returns its id. side is buy, sell or swap;
 58// give and want are short phrases such as "50,000 GNOT"; note is optional.
 59// days is how long the listing stays up: 0 means 7, the most is 30.
 60func Post(cur realm, side, give, want, note string, days int) uint64 {
 61	owner := callerOf(cur)
 62	refuseCoins(cur)
 63
 64	side = strings.TrimSpace(side)
 65	if side != SideBuy && side != SideSell && side != SideSwap {
 66		panic("side must be buy, sell or swap")
 67	}
 68	give = cleanText("give", give, MaxGiveLen, true)
 69	want = cleanText("want", want, MaxWantLen, true)
 70	note = cleanText("note", note, MaxNoteLen, false)
 71	if days == 0 {
 72		days = DefaultDays
 73	}
 74	if days < 1 || days > MaxDays {
 75		panic("a listing stays up between 1 and 30 days")
 76	}
 77
 78	now := time.Now().Unix()
 79	if activeCount(owner, now) >= MaxActivePerOwner {
 80		panic("you already have 10 open listings: close one first")
 81	}
 82
 83	lastID++
 84	l := &listing{
 85		id:        lastID,
 86		owner:     owner,
 87		side:      side,
 88		give:      give,
 89		want:      want,
 90		note:      note,
 91		createdAt: now,
 92		expiresAt: now + int64(days)*day,
 93	}
 94	listings.Set(listingKey(l.id), l)
 95	var ids []uint64
 96	if v := byOwner.Get(owner.String()); v != nil {
 97		ids = v.([]uint64)
 98	}
 99	byOwner.Set(owner.String(), append(ids, l.id))
100
101	chain.Emit("ListingPosted",
102		"id", strconv.FormatUint(l.id, 10),
103		"owner", owner.String(),
104		"side", side,
105	)
106	return l.id
107}
108
109// Close takes a listing down. Only its owner can close it.
110func Close(cur realm, id uint64) {
111	who := callerOf(cur)
112	refuseCoins(cur)
113	l := mustListing(id)
114	if l.owner != who {
115		panic("only the owner can close this listing")
116	}
117	if l.closedAt != 0 {
118		panic("this listing is already closed")
119	}
120	l.closedAt = time.Now().Unix()
121	chain.Emit("ListingClosed", "id", strconv.FormatUint(id, 10))
122}
123
124func (l *listing) open(now int64) bool {
125	return l.closedAt == 0 && now < l.expiresAt
126}
127
128// activeCount counts the owner's open listings. Listings older than
129// MaxDays cannot be open, so the walk stops there.
130func activeCount(owner address, now int64) int {
131	v := byOwner.Get(owner.String())
132	if v == nil {
133		return 0
134	}
135	ids := v.([]uint64)
136	oldest := now - MaxDays*day
137	n := 0
138	for i := len(ids) - 1; i >= 0 && n < MaxActivePerOwner; i-- {
139		l := mustListing(ids[i])
140		if l.createdAt < oldest {
141			break
142		}
143		if l.open(now) {
144			n++
145		}
146	}
147	return n
148}
149
150// cleanText trims s and rejects text that is too long or carries control,
151// bidi or zero-width characters.
152func cleanText(field, s string, max int, required bool) string {
153	s = strings.TrimSpace(s)
154	if required && s == "" {
155		panic(field + " is required")
156	}
157	if !utf8.ValidString(s) {
158		panic(field + " is not valid text")
159	}
160	if utf8.RuneCountInString(s) > max {
161		panic(field + " is longer than " + strconv.Itoa(max) + " characters")
162	}
163	for _, r := range s {
164		if r < 0x20 || r == 0x7f || (r >= 0x80 && r < 0xa0) ||
165			(r >= 0x200b && r <= 0x200f) || (r >= 0x202a && r <= 0x202e) ||
166			(r >= 0x2060 && r <= 0x2069) || r == 0xfeff {
167			panic(field + " contains characters that are not allowed")
168		}
169	}
170	return s
171}
172
173func callerOf(cur realm) address {
174	if !cur.IsCurrent() {
175		panic("unauthorized: realm token is not current")
176	}
177	return cur.Previous().Address()
178}
179
180func refuseCoins(cur realm) {
181	if !cur.IsCurrent() {
182		panic("unauthorized: realm token is not current")
183	}
184	if cur.Previous().IsUserCall() && len(unsafe.OriginSend()) > 0 {
185		panic("the board does not take coins")
186	}
187}
188
189func mustListing(id uint64) *listing {
190	v := listings.Get(listingKey(id))
191	if v == nil {
192		panic("listing not found")
193	}
194	return v.(*listing)
195}
196
197func listingKey(id uint64) string {
198	s := strconv.FormatUint(id, 10)
199	if len(s) < 20 {
200		s = strings.Repeat("0", 20-len(s)) + s
201	}
202	return s
203}