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.

api.gno

6.12 Kb · 189 lines
  1package mequest
  2
  3// JSON views for the website, served through Render("api/...").
  4// Read them with the RPC query vm/qrender, e.g. "<pkgpath>:api/quests".
  5
  6import (
  7	"strconv"
  8	"strings"
  9	"time"
 10
 11	"gno.land/r/sys/users"
 12)
 13
 14func renderAPI(path string) string {
 15	switch {
 16	case path == "stats":
 17		return apiStats()
 18	case path == "quests":
 19		out := make([]string, 0, len(quests))
 20		for _, q := range quests {
 21			out = append(out, questJSON(q, false))
 22		}
 23		return "[" + strings.Join(out, ",") + "]"
 24	case strings.HasPrefix(path, "q/"):
 25		id, err := strconv.Atoi(path[2:])
 26		if err != nil || id < 1 || id > len(quests) {
 27			return "null"
 28		}
 29		return questJSON(quests[id-1], true)
 30	case strings.HasPrefix(path, "p/"):
 31		return passportJSON(address(path[2:]))
 32	case path == "top":
 33		return topJSON()
 34	case path == "feed":
 35		out := []string{}
 36		for i := len(log) - 1; i >= 0; i-- {
 37			out = append(out, "{\"at\":"+i64(log[i].At)+",\"msg\":"+js(log[i].Msg)+"}")
 38		}
 39		return "[" + strings.Join(out, ",") + "]"
 40	case path == "receipts":
 41		out := []string{}
 42		for i := len(receipts) - 1; i >= 0; i-- {
 43			r := receipts[i]
 44			out = append(out, "{\"n\":"+strconv.Itoa(r.N)+",\"quest\":"+strconv.Itoa(r.Quest)+
 45				",\"title\":"+js(quests[r.Quest-1].Title)+",\"who\":"+who(r.Who)+",\"ok\":"+strconv.FormatBool(r.Ok)+
 46				",\"check\":"+js(r.Check)+",\"paid\":"+i64(r.Paid)+",\"rarity\":"+strconv.Itoa(quests[r.Quest-1].Rarity)+
 47				",\"art\":"+js(quests[r.Quest-1].Art)+",\"height\":"+i64(r.Height)+",\"at\":"+i64(r.At)+"}")
 48		}
 49		return "[" + strings.Join(out, ",") + "]"
 50	case path == "projects":
 51		out := []string{}
 52		for a, on := range projects {
 53			if on {
 54				out = append(out, who(a))
 55			}
 56		}
 57		return "{\"admin\":" + js(string(admin)) + ",\"approved\":[" + strings.Join(out, ",") + "]}"
 58	}
 59	return "null"
 60}
 61
 62func apiStats() string {
 63	locked := int64(0)
 64	open := 0
 65	now := time.Now().Unix()
 66	for _, q := range quests {
 67		locked += q.Pool
 68		if now < q.Expires && len(q.Winners) < q.Max {
 69			open++
 70		}
 71	}
 72	return "{\"quests\":" + strconv.Itoa(len(quests)) + ",\"open\":" + strconv.Itoa(open) +
 73		",\"locked\":" + i64(locked) + ",\"paid\":" + i64(paidOut) +
 74		",\"cards\":" + strconv.Itoa(minted) + ",\"players\":" + strconv.Itoa(len(players)) + ",\"joined\":" + strconv.Itoa(joined) +
 75		",\"season\":" + js(Season) + ",\"now\":" + i64(now) + "}"
 76}
 77
 78func questJSON(q *Quest, full bool) string {
 79	s := "{\"id\":" + strconv.Itoa(q.ID) + ",\"title\":" + js(q.Title) + ",\"desc\":" + js(q.Desc) +
 80		",\"art\":" + js(q.Art) + ",\"funder\":" + who(q.Funder) + ",\"rarity\":" + strconv.Itoa(q.Rarity) +
 81		",\"kind\":" + js(q.Kind) + ",\"arg\":" + js(q.Arg) + ",\"pay\":" + js(q.Pay) +
 82		",\"reward\":" + i64(q.Reward) + ",\"pool\":" + i64(q.Pool) + ",\"funded\":" + i64(q.Funded) +
 83		",\"max\":" + strconv.Itoa(q.Max) + ",\"claimed\":" + strconv.Itoa(len(q.Winners)) +
 84		",\"pending\":" + strconv.Itoa(len(q.pending)) + ",\"expires\":" + i64(q.Expires) +
 85		",\"settled\":" + strconv.FormatBool(q.Settled)
 86	if full {
 87		w := []string{}
 88		for i, a := range q.Winners {
 89			w = append(w, "{\"serial\":"+strconv.Itoa(i+1)+",\"who\":"+who(a)+"}")
 90		}
 91		p := []string{}
 92		for a, proof := range q.pending {
 93			p = append(p, "{\"who\":"+who(a)+",\"proof\":"+js(proof)+"}")
 94		}
 95		s += ",\"winners\":[" + strings.Join(w, ",") + "],\"queue\":[" + strings.Join(p, ",") + "]"
 96	}
 97	return s + "}"
 98}
 99
100func passportJSON(a address) string {
101	cs := []string{}
102	for _, c := range cards[a] {
103		cs = append(cs, "{\"quest\":"+strconv.Itoa(c.QuestID)+",\"title\":"+js(c.Title)+",\"art\":"+js(c.Art)+
104			",\"rarity\":"+strconv.Itoa(c.Rarity)+",\"serial\":"+strconv.Itoa(c.Serial)+
105			",\"season\":"+js(c.Season)+",\"at\":"+i64(c.At)+"}")
106	}
107	pend := []string{}
108	for _, q := range quests {
109		if _, ok := q.pending[a]; ok {
110			pend = append(pend, strconv.Itoa(q.ID))
111		}
112	}
113	best := BestRarity(a)
114	day := strconv.FormatInt(time.Now().Unix()/daySecs, 10)
115	return "{\"who\":" + who(a) + ",\"rank\":" + js(rankName[best]) + ",\"best\":" + strconv.Itoa(best) +
116		",\"points\":" + i64(points[a]) + ",\"today\":" + strconv.Itoa(daily[string(a)+":"+day]) +
117		",\"dailyCap\":" + strconv.Itoa(DailyCap) + ",\"streak\":" + strconv.Itoa(StreakOf(a)) +
118		",\"checkedToday\":" + strconv.FormatBool(lastDay[a] == time.Now().Unix()/daySecs && streak[a] > 0) +
119		",\"joinRank\":" + strconv.Itoa(joinRank[a]) + ",\"invites\":" + strconv.Itoa(invitesDone[a]) +
120		",\"hasInviter\":" + strconv.FormatBool(inviter[a] != "") + ",\"projects\":" + strconv.Itoa(ProjectsDone(a)) +
121		",\"posted\":" + strconv.Itoa(posted[a]) + ",\"approved\":" + strconv.FormatBool(projects[a] || a == admin) +
122		",\"cards\":[" + strings.Join(cs, ",") + "],\"pending\":[" + strings.Join(pend, ",") + "]}"
123}
124
125func topJSON() string {
126	list := ranked()
127	out := []string{}
128	for i, a := range list {
129		if i == 50 {
130			break
131		}
132		art := ""
133		best := 0
134		for _, c := range cards[a] {
135			if c.Rarity > best {
136				best, art = c.Rarity, c.Art
137			}
138		}
139		out = append(out, "{\"who\":"+who(a)+",\"points\":"+i64(points[a])+",\"best\":"+strconv.Itoa(best)+",\"bestArt\":"+js(art)+
140			",\"cards\":"+strconv.Itoa(len(cards[a]))+"}")
141	}
142	return "[" + strings.Join(out, ",") + "]"
143}
144
145func ranked() []address {
146	list := make([]address, len(players))
147	copy(list, players)
148	for i := 1; i < len(list); i++ {
149		for j := i; j > 0 && points[list[j]] > points[list[j-1]]; j-- {
150			list[j], list[j-1] = list[j-1], list[j]
151		}
152	}
153	return list
154}
155
156// who returns {"addr":..., "name":...}; name is the wallet's unique
157// gno.land username from r/sys/users, or "" if it has none.
158func who(a address) string {
159	name := ""
160	if u := users.ResolveAddress(a); u != nil {
161		name = u.Name()
162	}
163	return "{\"addr\":" + js(string(a)) + ",\"name\":" + js(name) + "}"
164}
165
166func i64(n int64) string { return strconv.FormatInt(n, 10) }
167
168// js quotes a string as a JSON string.
169func js(s string) string {
170	var b strings.Builder
171	b.WriteByte('"')
172	for _, r := range s {
173		switch {
174		case r == '"':
175			b.WriteString("\\\"")
176		case r == '\\':
177			b.WriteString("\\\\")
178		case r == '\n':
179			b.WriteString("\\n")
180		case r < 0x20:
181			h := strconv.FormatInt(int64(r), 16)
182			b.WriteString("\\u" + strings.Repeat("0", 4-len(h)) + h)
183		default:
184			b.WriteRune(r)
185		}
186	}
187	b.WriteByte('"')
188	return b.String()
189}