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.

query.gno

9.36 Kb · 343 lines
  1package rooms
  2
  3import (
  4	"strings"
  5	"time"
  6
  7	"gno.land/p/nt/grc20/v0"
  8	"gno.land/p/nt/grc721/v0"
  9	"gno.land/r/nt/grc20reg/v0"
 10)
 11
 12// Read-only views for clients. Each returns a JSON document as a string so
 13// a frontend can read it with one vm/qeval query. Amounts are strings
 14// because int64 does not fit a JavaScript number. Times are unix seconds;
 15// "now" is the block time the answer was computed at.
 16
 17const maxPage = 50
 18
 19// Address returns this realm's address: the spender to approve before
 20// DepositToken, and the account that holds deposits.
 21func Address() string {
 22	return self.String()
 23}
 24
 25// RoomJSON returns one room, or null when it does not exist.
 26func RoomJSON(id uint64) string {
 27	v := rooms.Get(roomKey(id))
 28	if v == nil {
 29		return "null"
 30	}
 31	return v.(*room).json(time.Now().Unix())
 32}
 33
 34// RoomsOfJSON lists the rooms where addr is maker or taker, newest first.
 35func RoomsOfJSON(addr string, offset, limit int) string {
 36	offset, limit = page(offset, limit)
 37	now := time.Now().Unix()
 38	items := []string{}
 39	var ids []uint64
 40	if v := byParty.Get(strings.TrimSpace(addr)); v != nil {
 41		ids = v.([]uint64)
 42	}
 43	more := false
 44	for i := len(ids) - 1 - offset; i >= 0; i-- {
 45		if len(items) == limit {
 46			more = true
 47			break
 48		}
 49		items = append(items, mustRoom(ids[i]).json(now))
 50	}
 51	return jsonObject(
 52		"rooms", jsonArray(items),
 53		"more", jsonBool(more),
 54		"now", jsonInt(now),
 55	)
 56}
 57
 58// LatestJSON lists all rooms, newest first.
 59func LatestJSON(offset, limit int) string {
 60	offset, limit = page(offset, limit)
 61	now := time.Now().Unix()
 62	items := []string{}
 63	rooms.ReverseIterateByOffset(offset, limit, func(_ string, v any) bool {
 64		items = append(items, v.(*room).json(now))
 65		return false
 66	})
 67	return jsonObject(
 68		"rooms", jsonArray(items),
 69		"total", jsonUint(lastID),
 70		"now", jsonInt(now),
 71	)
 72}
 73
 74// StatsJSON returns counters and the settled volume per asset.
 75func StatsJSON() string {
 76	vol := []string{}
 77	volume.Iterate("", "", func(key string, v any) bool {
 78		kind, denom, _ := strings.Cut(key, ":")
 79		vol = append(vol, jsonObject(
 80			"kind", jsonString(kind),
 81			"denom", jsonString(denom),
 82			"amount", jsonString(jsonInt(v.(int64))),
 83		))
 84		return false
 85	})
 86	collected := []string{}
 87	fees.Iterate("", "", func(key string, v any) bool {
 88		kind, denom, _ := strings.Cut(key, ":")
 89		collected = append(collected, jsonObject(
 90			"kind", jsonString(kind),
 91			"denom", jsonString(denom),
 92			"amount", jsonString(jsonInt(v.(int64))),
 93		))
 94		return false
 95	})
 96	return jsonObject(
 97		"rooms", jsonUint(lastID),
 98		"settled", jsonUint(nSettled),
 99		"cancelled", jsonUint(nCancelled),
100		"volume", jsonArray(vol),
101		"fees", jsonArray(collected),
102		"feeBps", jsonUint(openingFee()),
103		"treasury", jsonString(treasury.String()),
104		"paused", jsonBool(paused),
105		"address", jsonString(self.String()),
106		"now", jsonInt(time.Now().Unix()),
107	)
108}
109
110// TokensJSON lists GRC20 tokens from the registry that rooms accept.
111func TokensJSON(offset, limit int) string {
112	offset, limit = page(offset, limit)
113	items := []string{}
114	grc20reg.GetRegistry().IterateByOffset(offset, limit, func(key string, v any) bool {
115		items = append(items, tokenJSON(key, v.(*grc20.Token)))
116		return false
117	})
118	return jsonObject("tokens", jsonArray(items))
119}
120
121// TokenJSON describes one registered token and, when owner is given, the
122// owner's balance and current allowance to this realm.
123func TokenJSON(key string, owner string) string {
124	tok := grc20reg.Get(key)
125	if tok == nil {
126		return "null"
127	}
128	if owner == "" {
129		return tokenJSON(key, tok)
130	}
131	who := address(owner)
132	if !who.IsValid() {
133		return "null"
134	}
135	return jsonObject(
136		"key", jsonString(key),
137		"name", jsonString(tok.GetName()),
138		"symbol", jsonString(tok.GetSymbol()),
139		"decimals", jsonInt(int64(tok.GetDecimals())),
140		"balance", jsonString(jsonInt(tok.BalanceOf(who))),
141		"allowance", jsonString(jsonInt(tok.Allowance(who, self))),
142	)
143}
144
145// BalancesJSON lists the registered GRC20 tokens that owner holds, with the
146// balance and the allowance to this realm: a wallet's inventory in one
147// query. A page covers limit registry entries (at most 50); read on while
148// "more" is true.
149func BalancesJSON(owner string, offset, limit int) string {
150	offset, limit = page(offset, limit)
151	who := address(strings.TrimSpace(owner))
152	if !who.IsValid() {
153		return "null"
154	}
155	reg := grc20reg.GetRegistry()
156	items := []string{}
157	seen := 0
158	reg.IterateByOffset(offset, limit, func(key string, v any) bool {
159		seen++
160		tok := v.(*grc20.Token)
161		if bal := tok.BalanceOf(who); bal > 0 {
162			items = append(items, jsonObject(
163				"key", jsonString(key),
164				"name", jsonString(tok.GetName()),
165				"symbol", jsonString(tok.GetSymbol()),
166				"decimals", jsonInt(int64(tok.GetDecimals())),
167				"balance", jsonString(jsonInt(bal)),
168				"allowance", jsonString(jsonInt(tok.Allowance(who, self))),
169			))
170		}
171		return false
172	})
173	return jsonObject(
174		"tokens", jsonArray(items),
175		"more", jsonBool(offset+seen < reg.Size()),
176	)
177}
178
179// CollectionsJSON lists the GRC721 collections registered with rooms.
180func CollectionsJSON(offset, limit int) string {
181	offset, limit = page(offset, limit)
182	items := []string{}
183	collections.IterateByOffset(offset, limit, func(key string, v any) bool {
184		col := v.(*collection)
185		items = append(items, jsonObject(
186			"key", jsonString(key),
187			"name", jsonString(col.token.GetName()),
188			"symbol", jsonString(col.token.GetSymbol()),
189			"listed", jsonBool(col.list != nil),
190			"verified", jsonBool(IsVerified(KindNFT, key)),
191		))
192		return false
193	})
194	return jsonObject(
195		"collections", jsonArray(items),
196		"more", jsonBool(offset+len(items) < collections.Size()),
197	)
198}
199
200// NFTJSON describes one NFT of a registered collection: who owns it, and
201// whether this realm is approved to move it. null when the collection is
202// not registered or the token does not exist.
203func NFTJSON(collectionKey string, tokenID string) string {
204	v := collections.Get(collectionKey)
205	if v == nil {
206		return "null"
207	}
208	col := v.(*collection)
209	tid := grc721.TokenID(tokenID)
210	owner, err := col.token.OwnerOf(tid)
211	if err != nil {
212		return "null"
213	}
214	approved := col.token.IsApprovedForAll(owner, self)
215	if to, err := col.token.GetApproved(tid); err == nil && to == self {
216		approved = true
217	}
218	return jsonObject(
219		"key", jsonString(collectionKey),
220		"name", jsonString(col.token.GetName()),
221		"symbol", jsonString(col.token.GetSymbol()),
222		"tokenId", jsonString(tokenID),
223		"owner", jsonString(owner.String()),
224		"approved", jsonBool(approved),
225	)
226}
227
228// maxOwnedPerCollection bounds one OwnedJSON page.
229const maxOwnedPerCollection = 20
230
231// OwnedJSON lists the NFTs owner holds in registered collections that can
232// be listed (those registered with their enumerable view), at most 20 per
233// collection, and whether this realm is approved for each. A page covers
234// limit collections; read on while "more" is true.
235func OwnedJSON(owner string, offset, limit int) string {
236	offset, limit = page(offset, limit)
237	who := address(strings.TrimSpace(owner))
238	if !who.IsValid() {
239		return "null"
240	}
241	items := []string{}
242	seen := 0
243	collections.IterateByOffset(offset, limit, func(key string, v any) bool {
244		seen++
245		col := v.(*collection)
246		if col.list == nil {
247			return false
248		}
249		n, err := col.token.BalanceOf(who)
250		if err != nil || n <= 0 {
251			return false
252		}
253		if n > maxOwnedPerCollection {
254			n = maxOwnedPerCollection
255		}
256		operator := col.token.IsApprovedForAll(who, self)
257		for i := int64(0); i < n; i++ {
258			tid, err := col.list.TokenOfOwnerByIndex(who, i)
259			if err != nil {
260				break
261			}
262			approved := operator
263			if !approved {
264				if to, err := col.token.GetApproved(tid); err == nil && to == self {
265					approved = true
266				}
267			}
268			items = append(items, jsonObject(
269				"key", jsonString(key),
270				"name", jsonString(col.token.GetName()),
271				"symbol", jsonString(col.token.GetSymbol()),
272				"tokenId", jsonString(string(tid)),
273				"approved", jsonBool(approved),
274			))
275		}
276		return false
277	})
278	return jsonObject(
279		"nfts", jsonArray(items),
280		"more", jsonBool(offset+seen < collections.Size()),
281	)
282}
283
284func tokenJSON(key string, tok *grc20.Token) string {
285	return jsonObject(
286		"key", jsonString(key),
287		"name", jsonString(tok.GetName()),
288		"symbol", jsonString(tok.GetSymbol()),
289		"decimals", jsonInt(int64(tok.GetDecimals())),
290		"verified", jsonBool(IsVerified(KindToken, key)),
291	)
292}
293
294// json describes the room at block time now (unix seconds).
295func (r *room) json(now int64) string {
296	return jsonObject(
297		"id", jsonUint(r.id),
298		"status", jsonString(r.status),
299		"expired", jsonBool(r.status == StatusOpen && now >= r.expiresAt),
300		"version", jsonUint(r.version),
301		"openSeat", jsonBool(r.openSeat),
302		"openMarket", jsonBool(r.openMarket),
303		"createdAt", jsonInt(r.createdAt),
304		"expiresAt", jsonInt(r.expiresAt),
305		"closedAt", jsonInt(r.closedAt),
306		"closedBy", jsonString(r.closedBy.String()),
307		"maker", r.maker.json(),
308		"taker", r.taker.json(),
309		"want", assetsJSON(r.want),
310		"feeBps", jsonUint(r.feeBps),
311		"now", jsonInt(now),
312	)
313}
314
315func assetsJSON(list []asset) string {
316	items := make([]string, 0, len(list))
317	for _, a := range list {
318		items = append(items, jsonObject(
319			"kind", jsonString(a.kind),
320			"denom", jsonString(a.denom),
321			"amount", jsonString(jsonInt(a.amount)),
322		))
323	}
324	return jsonArray(items)
325}
326
327func (s *side) json() string {
328	return jsonObject(
329		"address", jsonString(s.owner.String()),
330		"locked", jsonUint(s.locked),
331		"assets", assetsJSON(s.assets),
332	)
333}
334
335func page(offset, limit int) (int, int) {
336	if offset < 0 {
337		offset = 0
338	}
339	if limit <= 0 || limit > maxPage {
340		limit = maxPage
341	}
342	return offset, limit
343}