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.

erratabank.gno

11.23 Kb · 428 lines
  1// Package erratabank records corrections, finder credit and book reward escrow.
  2package erratabank
  3
  4import (
  5	"chain"
  6	"chain/banker"
  7	"chain/runtime"
  8	"chain/runtime/unsafe"
  9	"strconv"
 10	"strings"
 11	"unicode/utf8"
 12
 13	"gno.land/p/g132vz03ycpaagtef4jmxjakstkppgyc5wn3r807/errata/v0"
 14	"gno.land/p/nt/avl/v0"
 15	"gno.land/p/nt/markdown/sanitize/v0"
 16)
 17
 18const (
 19	Pending   = "Pending"
 20	Accepted  = "Accepted"
 21	Rejected  = "Rejected"
 22	Duplicate = "Duplicate"
 23
 24	maxAmount  = 1<<63 - 1
 25	idKeyWidth = 19
 26)
 27
 28type Book struct {
 29	ID               int
 30	Owner            address
 31	Title            string
 32	Edition          string
 33	Link             string
 34	RewardPerErratum int64
 35	Escrow           int64
 36	Open             bool
 37	CreatedAt        int64
 38}
 39
 40type Erratum struct {
 41	ID          int
 42	BookID      int
 43	Finder      address
 44	Location    string
 45	Text        string
 46	Status      string
 47	DuplicateOf int
 48	SubmittedAt int64
 49	ReviewedAt  int64
 50	Paid        int64
 51	Note        string
 52}
 53
 54// Each book indexes all reports and each status by submission ID.
 55type bookRecord struct {
 56	book      Book
 57	all       avl.Tree
 58	pending   avl.Tree
 59	accepted  avl.Tree
 60	rejected  avl.Tree
 61	duplicate avl.Tree
 62}
 63
 64func (record *bookRecord) reports(status string) *avl.Tree {
 65	switch status {
 66	case "":
 67		return &record.all
 68	case Pending:
 69		return &record.pending
 70	case Accepted:
 71		return &record.accepted
 72	case Rejected:
 73		return &record.rejected
 74	case Duplicate:
 75		return &record.duplicate
 76	}
 77	return nil
 78}
 79
 80type finderRecord struct {
 81	paid int64
 82	ids  avl.Tree
 83}
 84
 85var (
 86	books         = avl.NewTree()
 87	errataByID    = avl.NewTree()
 88	finders       = avl.NewTree()
 89	nextErratumID int
 90	realmURL      string
 91)
 92
 93func init(cur realm) {
 94	realmURL = strings.TrimPrefix(cur.PkgPath(), "gno.land") + ":"
 95}
 96
 97func idKey(id int) string {
 98	digits := strconv.Itoa(id)
 99	return strings.Repeat("0", idKeyWidth-len(digits)) + digits
100}
101
102func bookByID(id int) *bookRecord {
103	if id <= 0 {
104		return nil
105	}
106	book, _ := books.Get(idKey(id)).(*bookRecord)
107	return book
108}
109
110func reportByID(id int) *Erratum {
111	if id <= 0 {
112		return nil
113	}
114	report, _ := errataByID.Get(idKey(id)).(*Erratum)
115	return report
116}
117
118func requireBook(id int) *bookRecord {
119	record := bookByID(id)
120	if record == nil {
121		panic(errBookMissing)
122	}
123	return record
124}
125
126func requireOwner(record *bookRecord, caller address) {
127	if record.book.Owner != caller {
128		panic(errOwnerOnly)
129	}
130}
131
132func requireReview(id int, caller address) (*bookRecord, *Erratum) {
133	report := reportByID(id)
134	if report == nil {
135		panic(errErratumMiss)
136	}
137	record := requireBook(report.BookID)
138	requireOwner(record, caller)
139	if report.Status != Pending {
140		panic(errPendingOnly)
141	}
142	return record, report
143}
144
145func callerAddress(cur realm) address {
146	if !cur.IsCurrent() {
147		panic(errCurrentRealm)
148	}
149	return cur.Previous().Address()
150}
151
152// A direct MsgCall credits this realm with the transaction's send before execution.
153func inboundUgnot(cur realm) int64 {
154	if !cur.Previous().IsUserCall() {
155		panic(errDirectCall)
156	}
157	coins := unsafe.OriginSend()
158	if len(coins) == 0 {
159		return 0
160	}
161	if len(coins) != 1 || coins[0].Denom != "ugnot" {
162		panic(errPaymentDenom)
163	}
164	if coins[0].Amount <= 0 {
165		panic(errPayment)
166	}
167	return coins[0].Amount
168}
169
170func rejectCoins(cur realm) {
171	if cur.Previous().IsUserCall() && len(unsafe.OriginSend()) != 0 {
172		panic(errRejectCoins)
173	}
174}
175
176func addAmount(total, amount int64) int64 {
177	if amount > maxAmount-total {
178		panic(errOverflow)
179	}
180	return total + amount
181}
182
183func sendUgnot(cur realm, to address, amount int64) {
184	b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
185	b.SendCoins(cur.Address(), to, chain.NewCoins(chain.NewCoin("ugnot", amount)))
186}
187
188func requiredText(field, text string, max int) string {
189	trimmed := strings.TrimSpace(text)
190	if trimmed == "" || !utf8.ValidString(text) || utf8.RuneCountInString(text) > max {
191		panic(field + " must contain 1 to " + strconv.Itoa(max) + " characters")
192	}
193	return trimmed
194}
195
196func reviewNote(note string) string {
197	if strings.TrimSpace(note) == "" {
198		return ""
199	}
200	return requiredText("review note", note, 300)
201}
202
203// CreateBook registers an open book and optionally credits inbound reward escrow.
204func CreateBook(cur realm, title, edition, link string, rewardPerErratum int64) int {
205	owner := callerAddress(cur)
206	escrow := inboundUgnot(cur)
207	title = requiredText("title", title, 120)
208	edition = requiredText("edition", edition, 120)
209	link = requiredText("link", link, 300)
210	if sanitize.URL(link) == "" {
211		panic("unsupported book link")
212	}
213	if rewardPerErratum < 0 {
214		panic("reward cannot be negative")
215	}
216	id := books.Size() + 1
217	books.Set(idKey(id), &bookRecord{book: Book{
218		ID: id, Owner: owner, Title: title, Edition: edition, Link: link,
219		RewardPerErratum: rewardPerErratum, Escrow: escrow, Open: true, CreatedAt: runtime.ChainHeight(),
220	}})
221	chain.Emit("BookCreated", "book", strconv.Itoa(id), "owner", owner.String(),
222		"reward", strconv.FormatInt(rewardPerErratum, 10), "escrow", strconv.FormatInt(escrow, 10))
223	return id
224}
225
226// FundBook credits a book with ugnot supplied by any direct caller.
227func FundBook(cur realm, bookID int) {
228	caller := callerAddress(cur)
229	amount := inboundUgnot(cur)
230	if amount == 0 {
231		panic(errPayment)
232	}
233	record := requireBook(bookID)
234	record.book.Escrow = addAmount(record.book.Escrow, amount)
235	chain.Emit("BookFunded", "book", strconv.Itoa(bookID), "funder", caller.String(),
236		"amount", strconv.FormatInt(amount, 10))
237}
238
239// Submit records a report. Increasing IDs break ties within a block.
240func Submit(cur realm, bookID int, location, text string) int {
241	finder := callerAddress(cur)
242	rejectCoins(cur)
243	record := requireBook(bookID)
244	if !record.book.Open {
245		panic(errClosed)
246	}
247	if finder == record.book.Owner {
248		panic(errSelfSubmit)
249	}
250	location = requiredText("location", location, 120)
251	text = requiredText("text", text, 1000)
252	nextErratumID++
253	id := nextErratumID
254	key := idKey(id)
255	errataByID.Set(key, &Erratum{
256		ID: id, BookID: bookID, Finder: finder, Location: location, Text: text,
257		Status: Pending, SubmittedAt: runtime.ChainHeight(),
258	})
259	record.all.Set(key, id)
260	record.pending.Set(key, id)
261	chain.Emit("ErratumSubmitted", "book", strconv.Itoa(bookID), "erratum", strconv.Itoa(id),
262		"finder", finder.String())
263	return id
264}
265
266func review(record *bookRecord, report *Erratum, status, note string) {
267	key := idKey(report.ID)
268	record.pending.Remove(key)
269	record.reports(status).Set(key, report.ID)
270	report.Status = status
271	report.ReviewedAt = runtime.ChainHeight()
272	report.Note = note
273}
274
275// Accept credits the finder and pays the full reward when escrow covers it.
276func Accept(cur realm, erratumID int, note string) {
277	owner := callerAddress(cur)
278	rejectCoins(cur)
279	record, report := requireReview(erratumID, owner)
280	review(record, report, Accepted, reviewNote(note))
281
282	addr := report.Finder.String()
283	finder, ok := finders.Get(addr).(*finderRecord)
284	if !ok {
285		finder = &finderRecord{}
286		finders.Set(addr, finder)
287	}
288	finder.ids.Set(idKey(erratumID), erratumID)
289	reward := record.book.RewardPerErratum
290	if reward > 0 && record.book.Escrow >= reward {
291		record.book.Escrow -= reward
292		report.Paid = reward
293		finder.paid = addAmount(finder.paid, reward)
294		sendUgnot(cur, report.Finder, reward)
295	}
296	chain.Emit("ErratumAccepted", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(erratumID),
297		"finder", addr, "paid", strconv.FormatInt(report.Paid, 10))
298}
299
300// Reject closes a pending submission without finder credit.
301func Reject(cur realm, erratumID int, note string) {
302	caller := callerAddress(cur)
303	rejectCoins(cur)
304	record, report := requireReview(erratumID, caller)
305	review(record, report, Rejected, reviewNote(note))
306	chain.Emit("ErratumRejected", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(erratumID))
307}
308
309// MarkDuplicate links a pending report to an earlier accepted report in the same book.
310func MarkDuplicate(cur realm, erratumID, originalID int) {
311	caller := callerAddress(cur)
312	rejectCoins(cur)
313	record, report := requireReview(erratumID, caller)
314	original := reportByID(originalID)
315	if original == nil || original.BookID != report.BookID || original.ID >= report.ID ||
316		original.Status != Accepted {
317		panic(errDuplicate)
318	}
319	report.DuplicateOf = originalID
320	review(record, report, Duplicate, "")
321	chain.Emit("ErratumMarkedDuplicate", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(erratumID),
322		"original", strconv.Itoa(originalID))
323}
324
325// SetBookOpen controls new submissions. Existing submissions remain reviewable.
326func SetBookOpen(cur realm, bookID int, open bool) {
327	caller := callerAddress(cur)
328	rejectCoins(cur)
329	record := requireBook(bookID)
330	requireOwner(record, caller)
331	record.book.Open = open
332	chain.Emit("BookOpenChanged", "book", strconv.Itoa(bookID), "open", strconv.FormatBool(open))
333}
334
335// Withdraw returns unused escrow to the book owner.
336func Withdraw(cur realm, bookID int, amount int64) {
337	caller := callerAddress(cur)
338	rejectCoins(cur)
339	record := requireBook(bookID)
340	requireOwner(record, caller)
341	if amount <= 0 || amount > record.book.Escrow {
342		panic(errWithdraw)
343	}
344	record.book.Escrow -= amount
345	sendUgnot(cur, caller, amount)
346	chain.Emit("BookWithdrawn", "book", strconv.Itoa(bookID), "owner", caller.String(),
347		"amount", strconv.FormatInt(amount, 10))
348}
349
350func GetBook(id int) (Book, bool) {
351	if record := bookByID(id); record != nil {
352		return record.book, true
353	}
354	return Book{}, false
355}
356
357func ListBooks(offset, limit int) []Book {
358	var result []Book
359	if offset < 0 || limit <= 0 || offset >= books.Size() {
360		return result
361	}
362	if remaining := books.Size() - offset; limit > remaining {
363		limit = remaining
364	}
365	books.IterateByOffset(offset, limit, func(_ string, value any) bool {
366		result = append(result, value.(*bookRecord).book)
367		return false
368	})
369	return result
370}
371
372func GetErratum(id int) (Erratum, bool) {
373	if report := reportByID(id); report != nil {
374		return *report, true
375	}
376	return Erratum{}, false
377}
378
379func listReports(tree *avl.Tree, offset, limit int) []Erratum {
380	var result []Erratum
381	if tree == nil || offset < 0 || limit <= 0 || offset >= tree.Size() {
382		return result
383	}
384	if remaining := tree.Size() - offset; limit > remaining {
385		limit = remaining
386	}
387	tree.IterateByOffset(offset, limit, func(_ string, value any) bool {
388		report, _ := GetErratum(value.(int))
389		result = append(result, report)
390		return false
391	})
392	return result
393}
394
395// ListErrata returns reports in submission order. An empty status selects all reports.
396func ListErrata(bookID int, status string, offset, limit int) []Erratum {
397	if record := bookByID(bookID); record != nil {
398		return listReports(record.reports(status), offset, limit)
399	}
400	return nil
401}
402
403func acceptedEntries(reports []Erratum) []errata.Entry {
404	var entries []errata.Entry
405	for _, report := range reports {
406		entries = append(entries, errata.Entry{
407			Location: report.Location, Text: report.Text, Finder: report.Finder.String(),
408			FoundAt: report.SubmittedAt, Paid: report.Paid, Link: finderURL(report.Finder),
409		})
410	}
411	return entries
412}
413
414func AcceptedEntries(bookID int) []errata.Entry {
415	return AcceptedEntriesPage(bookID, 0, int(maxAmount))
416}
417
418// AcceptedEntriesPage supports integrations that render a bounded page.
419func AcceptedEntriesPage(bookID, offset, limit int) []errata.Entry {
420	return acceptedEntries(ListErrata(bookID, Accepted, offset, limit))
421}
422
423func FinderStats(addr address) (accepted int, paid int64) {
424	if finder, ok := finders.Get(addr.String()).(*finderRecord); ok {
425		return finder.ids.Size(), finder.paid
426	}
427	return 0, 0
428}