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

12.05 Kb · 464 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	maxListLimit = 50
 27)
 28
 29type Book struct {
 30	ID               int
 31	Owner            address
 32	Title            string
 33	Edition          string
 34	Link             string
 35	RewardPerErratum int64
 36	OwnerFunds       int64
 37	SponsorFunds     int64
 38	Owed             int64
 39	Open             bool
 40	CreatedAt        int64
 41}
 42
 43type Erratum struct {
 44	ID          int
 45	BookID      int
 46	Finder      address
 47	Location    string
 48	Text        string
 49	Status      string
 50	DuplicateOf int
 51	SubmittedAt int64
 52	ReviewedAt  int64
 53	Paid        int64
 54	Owed        int64
 55	Note        string
 56}
 57
 58// Each book indexes all reports and each status by submission ID.
 59type bookRecord struct {
 60	book        Book
 61	all         avl.Tree
 62	pending     avl.Tree
 63	accepted    avl.Tree
 64	rejected    avl.Tree
 65	duplicate   avl.Tree
 66	byLocation  avl.Tree
 67	sponsors    avl.Tree
 68	owedReports avl.Tree
 69	nextOwedID  int
 70}
 71
 72func (record *bookRecord) reports(status string) *avl.Tree {
 73	switch status {
 74	case "":
 75		return &record.all
 76	case Pending:
 77		return &record.pending
 78	case Accepted:
 79		return &record.accepted
 80	case Rejected:
 81		return &record.rejected
 82	case Duplicate:
 83		return &record.duplicate
 84	}
 85	return nil
 86}
 87
 88type finderRecord struct {
 89	paid    int64
 90	owed    int64
 91	credits avl.Tree
 92	unpaid  avl.Tree
 93}
 94
 95type FinderSummary struct {
 96	Credits       int
 97	UnpaidCredits int
 98	Paid          int64
 99	Owed          int64
100}
101
102var (
103	books        = avl.NewTree()
104	errataByID   = avl.NewTree()
105	finders      = avl.NewTree()
106	nextBookID   int
107	nextReportID int
108	realmURL     string
109)
110
111func init(cur realm) {
112	realmURL = strings.TrimPrefix(cur.PkgPath(), "gno.land") + ":"
113}
114
115func idKey(id int) string {
116	digits := strconv.Itoa(id)
117	return strings.Repeat("0", idKeyWidth-len(digits)) + digits
118}
119
120func advanceID(counter *int) int {
121	if *counter == maxAmount {
122		panic(errIDLimit)
123	}
124	*counter += 1
125	return *counter
126}
127
128func bookByID(id int) *bookRecord {
129	if id <= 0 {
130		return nil
131	}
132	book, _ := books.Get(idKey(id)).(*bookRecord)
133	return book
134}
135
136func reportByID(id int) *Erratum {
137	if id <= 0 {
138		return nil
139	}
140	report, _ := errataByID.Get(idKey(id)).(*Erratum)
141	return report
142}
143
144func requireBook(id int) *bookRecord {
145	record := bookByID(id)
146	if record == nil {
147		panic(errBookMissing)
148	}
149	return record
150}
151
152func requireOwner(record *bookRecord, caller address) {
153	if record.book.Owner != caller {
154		panic(errOwnerOnly)
155	}
156}
157
158func requireReview(id int, caller address) (*bookRecord, *Erratum) {
159	report := reportByID(id)
160	if report == nil {
161		panic(errErratumMiss)
162	}
163	record := requireBook(report.BookID)
164	requireOwner(record, caller)
165	if report.Status != Pending {
166		panic(errPendingOnly)
167	}
168	return record, report
169}
170
171func callerAddress(cur realm) address {
172	if !cur.IsCurrent() {
173		panic(errCurrentRealm)
174	}
175	return cur.Previous().Address()
176}
177
178// Gno v1.8.0 exposes the inbound coin envelope through unsafe.OriginSend.
179// The Gno Security Guide requires IsUserCall before reading it.
180// https://docs.gno.land/resources/gno-security-guide/#55-isuser-for-payment-guards
181func inboundUgnot(cur realm) int64 {
182	if !cur.Previous().IsUserCall() {
183		panic(errDirectCall)
184	}
185	coins := unsafe.OriginSend()
186	if len(coins) == 0 {
187		return 0
188	}
189	if len(coins) != 1 || coins[0].Denom != "ugnot" {
190		panic(errPaymentDenom)
191	}
192	if coins[0].Amount <= 0 {
193		panic(errPayment)
194	}
195	return coins[0].Amount
196}
197
198func rejectCoins(cur realm) {
199	if cur.Previous().IsUserCall() && len(unsafe.OriginSend()) != 0 {
200		panic(errRejectCoins)
201	}
202}
203
204func addAmount(total, amount int64) int64 {
205	if amount > maxAmount-total {
206		panic(errOverflow)
207	}
208	return total + amount
209}
210
211func sendUgnot(cur realm, to address, amount int64) {
212	b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
213	b.SendCoins(cur.Address(), to, chain.NewCoins(chain.NewCoin("ugnot", amount)))
214}
215
216func requiredText(field, text string, max int) string {
217	trimmed := strings.TrimSpace(text)
218	if trimmed == "" || !utf8.ValidString(text) || utf8.RuneCountInString(text) > max {
219		panic(field + " must contain 1 to " + strconv.Itoa(max) + " characters")
220	}
221	return trimmed
222}
223
224func reviewNote(note string) string {
225	if strings.TrimSpace(note) == "" {
226		return ""
227	}
228	return requiredText("review note", note, 300)
229}
230
231// CreateBook registers an open book and optionally credits inbound reward escrow.
232func CreateBook(cur realm, title, edition, link string, rewardPerErratum int64) int {
233	owner := callerAddress(cur)
234	ownerFunds := inboundUgnot(cur)
235	title = requiredText("title", title, 120)
236	edition = requiredText("edition", edition, 120)
237	link = requiredText("link", link, 300)
238	if sanitize.URL(link) == "" {
239		panic("unsupported book link")
240	}
241	if rewardPerErratum < 0 {
242		panic("reward cannot be negative")
243	}
244	id := advanceID(&nextBookID)
245	books.Set(idKey(id), &bookRecord{book: Book{
246		ID: id, Owner: owner, Title: title, Edition: edition, Link: link,
247		RewardPerErratum: rewardPerErratum, OwnerFunds: ownerFunds, Open: true, CreatedAt: runtime.ChainHeight(),
248	}})
249	chain.Emit("BookCreated", "book", strconv.Itoa(id), "owner", owner.String(),
250		"reward", strconv.FormatInt(rewardPerErratum, 10), "owner_funds", strconv.FormatInt(ownerFunds, 10))
251	return id
252}
253
254// Submit records a report. Reports are public and permanent on-chain.
255func Submit(cur realm, bookID int, location, text string) int {
256	finder := callerAddress(cur)
257	rejectCoins(cur)
258	record := requireBook(bookID)
259	if !record.book.Open {
260		panic(errClosed)
261	}
262	location = requiredText("location", location, 120)
263	text = requiredText("text", text, 1000)
264	id := advanceID(&nextReportID)
265	key := idKey(id)
266	errataByID.Set(key, &Erratum{
267		ID: id, BookID: bookID, Finder: finder, Location: location, Text: text,
268		Status: Pending, SubmittedAt: runtime.ChainHeight(),
269	})
270	record.all.Set(key, id)
271	record.pending.Set(key, id)
272	atLocation, _ := record.byLocation.Get(location).(*avl.Tree)
273	if atLocation == nil {
274		atLocation = avl.NewTree()
275		record.byLocation.Set(location, atLocation)
276	}
277	atLocation.Set(key, id)
278	chain.Emit("ErratumSubmitted", "book", strconv.Itoa(bookID), "erratum", strconv.Itoa(id),
279		"finder", finder.String())
280	return id
281}
282
283func review(record *bookRecord, report *Erratum, status, note string) {
284	key := idKey(report.ID)
285	record.pending.Remove(key)
286	atLocation := record.byLocation.Get(report.Location).(*avl.Tree)
287	atLocation.Remove(key)
288	if atLocation.Size() == 0 {
289		record.byLocation.Remove(report.Location)
290	}
291	record.reports(status).Set(key, report.ID)
292	report.Status = status
293	report.ReviewedAt = runtime.ChainHeight()
294	report.Note = note
295}
296
297// Accept credits the finder and queues the reward for settlement from the book funds.
298func Accept(cur realm, erratumID int, note string) {
299	owner := callerAddress(cur)
300	rejectCoins(cur)
301	record, report := requireReview(erratumID, owner)
302	if !record.book.Open {
303		panic(errClosedAccept)
304	}
305	atLocation := record.byLocation.Get(report.Location).(*avl.Tree)
306	_, first := atLocation.GetByIndex(0)
307	if first.(int) != report.ID {
308		panic(errEarlierPending)
309	}
310	review(record, report, Accepted, reviewNote(note))
311
312	addr := report.Finder.String()
313	finder, ok := finders.Get(addr).(*finderRecord)
314	if !ok {
315		finder = &finderRecord{}
316		finders.Set(addr, finder)
317	}
318	key := idKey(erratumID)
319	if reward := record.book.RewardPerErratum; reward > 0 && report.Finder != owner {
320		finder.credits.Set(key, erratumID)
321		record.queueReward(report, finder, reward)
322		settleRewards(cur, record)
323	} else {
324		finder.unpaid.Set(key, erratumID)
325	}
326	chain.Emit("ErratumAccepted", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(erratumID),
327		"finder", addr, "paid", strconv.FormatInt(report.Paid, 10), "owed", strconv.FormatInt(report.Owed, 10))
328}
329
330// Reject closes a pending submission without finder credit.
331func Reject(cur realm, erratumID int, note string) {
332	caller := callerAddress(cur)
333	rejectCoins(cur)
334	record, report := requireReview(erratumID, caller)
335	review(record, report, Rejected, reviewNote(note))
336	chain.Emit("ErratumRejected", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(erratumID))
337}
338
339// MarkDuplicate links a pending report to an earlier pending or accepted report in the same book.
340func MarkDuplicate(cur realm, erratumID, originalID int) {
341	caller := callerAddress(cur)
342	rejectCoins(cur)
343	record, report := requireReview(erratumID, caller)
344	original := reportByID(originalID)
345	if original == nil || original.BookID != report.BookID || original.ID >= report.ID ||
346		(original.Status != Pending && original.Status != Accepted) {
347		panic(errDuplicate)
348	}
349	report.DuplicateOf = originalID
350	review(record, report, Duplicate, "")
351	chain.Emit("ErratumMarkedDuplicate", "book", strconv.Itoa(report.BookID), "erratum", strconv.Itoa(erratumID),
352		"original", strconv.Itoa(originalID))
353}
354
355// SetBookOpen controls submissions and acceptance. Closing opens sponsor refunds after debts settle.
356func SetBookOpen(cur realm, bookID int, open bool) {
357	caller := callerAddress(cur)
358	rejectCoins(cur)
359	record := requireBook(bookID)
360	requireOwner(record, caller)
361	if open && !record.book.Open && record.book.SponsorFunds > 0 {
362		panic(errSponsorRefundsPending)
363	}
364	record.book.Open = open
365	if !open {
366		settleRewards(cur, record)
367	}
368	chain.Emit("BookOpenChanged", "book", strconv.Itoa(bookID), "open", strconv.FormatBool(open))
369}
370
371func GetBook(id int) (Book, bool) {
372	if record := bookByID(id); record != nil {
373		return record.book, true
374	}
375	return Book{}, false
376}
377
378func pageLimit(size, offset, limit int) int {
379	if offset < 0 || limit <= 0 || offset >= size {
380		return 0
381	}
382	if limit > maxListLimit {
383		limit = maxListLimit
384	}
385	if remaining := size - offset; limit > remaining {
386		limit = remaining
387	}
388	return limit
389}
390
391func ListBooks(offset, limit int) []Book {
392	var result []Book
393	if limit = pageLimit(books.Size(), offset, limit); limit == 0 {
394		return result
395	}
396	books.IterateByOffset(offset, limit, func(_ string, value any) bool {
397		result = append(result, value.(*bookRecord).book)
398		return false
399	})
400	return result
401}
402
403func GetErratum(id int) (Erratum, bool) {
404	if report := reportByID(id); report != nil {
405		return *report, true
406	}
407	return Erratum{}, false
408}
409
410func listReports(tree *avl.Tree, offset, limit int) []Erratum {
411	var result []Erratum
412	if tree == nil {
413		return result
414	}
415	if limit = pageLimit(tree.Size(), offset, limit); limit == 0 {
416		return result
417	}
418	tree.IterateByOffset(offset, limit, func(_ string, value any) bool {
419		report, _ := GetErratum(value.(int))
420		result = append(result, report)
421		return false
422	})
423	return result
424}
425
426// ListErrata returns reports in submission order. An empty status selects all reports.
427func ListErrata(bookID int, status string, offset, limit int) []Erratum {
428	if record := bookByID(bookID); record != nil {
429		return listReports(record.reports(status), offset, limit)
430	}
431	return nil
432}
433
434func acceptedEntries(reports []Erratum) []errata.Entry {
435	var entries []errata.Entry
436	for _, report := range reports {
437		entries = append(entries, errata.Entry{
438			Location: report.Location, Text: report.Text, Finder: report.Finder.String(),
439			FoundAt: report.SubmittedAt, Paid: report.Paid, Link: finderURL(report.Finder),
440		})
441	}
442	return entries
443}
444
445// AcceptedEntries returns the first 50 accepted reports in submission order.
446func AcceptedEntries(bookID int) []errata.Entry {
447	return AcceptedEntriesPage(bookID, 0, maxListLimit)
448}
449
450// AcceptedEntriesPage is the integration API for rendering accepted reports.
451// Limits are capped at 50 entries per page.
452func AcceptedEntriesPage(bookID, offset, limit int) []errata.Entry {
453	return acceptedEntries(ListErrata(bookID, Accepted, offset, limit))
454}
455
456func FinderStats(addr address) FinderSummary {
457	if finder, ok := finders.Get(addr.String()).(*finderRecord); ok {
458		return FinderSummary{
459			Credits: finder.credits.Size(), UnpaidCredits: finder.unpaid.Size(),
460			Paid: finder.paid, Owed: finder.owed,
461		}
462	}
463	return FinderSummary{}
464}