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.08 Kb · 305 lines
  1package hearthbounty
  2
  3import (
  4	"chain/runtime"
  5	"sort"
  6
  7	"gno.land/p/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthcore/v0"
  8	"gno.land/r/nt/grc20reg/v0"
  9)
 10
 11// Arbiter returns the current dispute arbiter address.
 12func Arbiter() address {
 13	return arbiter
 14}
 15
 16// PkgPath returns the canonical Gno.land package path of this realm.
 17func PkgPath() string {
 18	return realmPkgPath
 19}
 20
 21// EscrowToken returns the canonical grc20reg key used for 1:1 ugnot-backed escrow.
 22func EscrowToken() string {
 23	return EscrowTokenKey
 24}
 25
 26// EscrowRealmAddress returns the derived realm address that holds escrowed wugnot.
 27func EscrowRealmAddress() address {
 28	return realmAddress
 29}
 30
 31// EscrowBalance returns the current wugnot balance of addr from grc20reg.
 32func EscrowBalance(addr address) int64 {
 33	return grc20reg.MustGet(EscrowTokenKey).BalanceOf(addr)
 34}
 35
 36// EscrowAllowance returns how much wugnot owner has approved this realm to pull.
 37func EscrowAllowance(owner address) int64 {
 38	return grc20reg.MustGet(EscrowTokenKey).Allowance(owner, realmAddress)
 39}
 40
 41// GetStats returns an immutable snapshot of protocol counters and escrow totals.
 42func GetStats() BoardStats {
 43	return BoardStats{
 44		TotalBounties:     bounties.Size(),
 45		OpenCount:         openCount,
 46		ClaimedCount:      claimedCount,
 47		SubmittedCount:    submittedCount,
 48		DisputedCount:     disputedCount,
 49		SettledCount:      settledCount,
 50		CancelledCount:    cancelledCount,
 51		ProfileCount:      profiles.Size(),
 52		AgentCount:        agentCount,
 53		TotalEscrowUgnot:  totalEscrowUgnot,
 54		TotalSettledUgnot: totalSettledUgnot,
 55		TotalRefundUgnot:  totalRefundUgnot,
 56	}
 57}
 58
 59// GetBounty returns a value copy of a single bounty by ID.
 60func GetBounty(id uint64) (BountyView, bool) {
 61	b, ok := getBountyRecord(id)
 62	if !ok {
 63		return BountyView{}, false
 64	}
 65	return toBountyView(b), true
 66}
 67
 68// GetDonorContribution returns the external top-up ugnot currently held in
 69// custody for donor on bounty id (0 if none or if donor is the sponsor).
 70func GetDonorContribution(id uint64, donor address) int64 {
 71	b, ok := getBountyRecord(id)
 72	if !ok || b.DonorShares == nil {
 73		return 0
 74	}
 75	if raw := b.DonorShares.Get(string(donor)); raw != nil {
 76		return raw.(int64)
 77	}
 78	return 0
 79}
 80
 81// GetProfile returns a value copy of a builder or AI agent profile.
 82func GetProfile(addr address) (ProfileView, bool) {
 83	raw := profiles.Get(string(addr))
 84	if raw == nil {
 85		return ProfileView{}, false
 86	}
 87	return toProfileView(raw.(*profileRecord)), true
 88}
 89
 90// ExportStatsJSON returns global protocol stats as deterministic JSON for MCP agents.
 91func ExportStatsJSON() string {
 92	s := GetStats()
 93	return hearthcore.NewJSONObject().
 94		Str("realm_path", realmPkgPath).
 95		Str("web_path", realmWebBase).
 96		Str("escrow_token", EscrowTokenKey).
 97		Str("escrow_address", string(realmAddress)).
 98		Str("arbiter", string(arbiter)).
 99		Int64("chain_height", runtime.ChainHeight()).
100		Int64("total_bounties", int64(s.TotalBounties)).
101		Int64("open_count", int64(s.OpenCount)).
102		Int64("claimed_count", int64(s.ClaimedCount)).
103		Int64("submitted_count", int64(s.SubmittedCount)).
104		Int64("disputed_count", int64(s.DisputedCount)).
105		Int64("settled_count", int64(s.SettledCount)).
106		Int64("cancelled_count", int64(s.CancelledCount)).
107		Int64("profile_count", int64(s.ProfileCount)).
108		Int64("agent_count", int64(s.AgentCount)).
109		Int64("total_escrow_ugnot", s.TotalEscrowUgnot).
110		Int64("total_settled_ugnot", s.TotalSettledUgnot).
111		Int64("total_refund_ugnot", s.TotalRefundUgnot).
112		String()
113}
114
115// ExportBountyJSON returns a single bounty as deterministic JSON (or {"found":false}).
116func ExportBountyJSON(id uint64) string {
117	b, ok := getBountyRecord(id)
118	if !ok {
119		return `{"found":false}`
120	}
121	return encodeBountyJSON(b, true)
122}
123
124// ExportBountiesJSON lists bounties in reverse chronological order with optional
125// status, category, and minimum reward filters for autonomous agent discovery.
126func ExportBountiesJSON(statusFilter, categoryFilter string, minRewardUgnot int64, limit int) string {
127	st := normalizeFilter(statusFilter)
128	cat := normalizeFilter(categoryFilter)
129	if limit <= 0 || limit > 100 {
130		limit = 50
131	}
132
133	items := make([]string, 0)
134	bounties.ReverseIterate("", "", func(_ string, val any) bool {
135		b := val.(*bountyRecord)
136		if st != "" && string(b.Status) != st {
137			return false
138		}
139		if cat != "" && string(b.Category) != cat {
140			return false
141		}
142		reward := effectiveReward(b)
143		if minRewardUgnot > 0 && reward < minRewardUgnot {
144			return false
145		}
146		items = append(items, encodeBountyJSON(b, false))
147		return len(items) >= limit
148	})
149
150	return hearthcore.NewJSONObject().
151		Int64("chain_height", runtime.ChainHeight()).
152		Int64("count", int64(len(items))).
153		Raw("bounties", hearthcore.JoinJSONArray(items)).
154		String()
155}
156
157// ExportLeaderboardJSON returns deterministically sorted builders & AI agents.
158func ExportLeaderboardJSON(limit int) string {
159	if limit <= 0 || limit > 100 {
160		limit = 25
161	}
162	ranked := rankedProfiles()
163	if len(ranked) > limit {
164		ranked = ranked[:limit]
165	}
166
167	items := make([]string, 0, len(ranked))
168	for i, p := range ranked {
169		items = append(items, encodeProfileJSON(p, i+1))
170	}
171
172	return hearthcore.NewJSONObject().
173		Int64("count", int64(len(items))).
174		Raw("leaderboard", hearthcore.JoinJSONArray(items)).
175		String()
176}
177
178// ExportProfileJSON returns a single profile as deterministic JSON.
179func ExportProfileJSON(addrStr string) string {
180	raw := profiles.Get(addrStr)
181	if raw == nil {
182		return `{"found":false}`
183	}
184	p := raw.(*profileRecord)
185	return encodeProfileJSON(p, 0)
186}
187
188func effectiveReward(b *bountyRecord) int64 {
189	if b.EscrowUgnot > 0 {
190		return b.EscrowUgnot
191	}
192	if b.PayoutUgnot > 0 {
193		return b.PayoutUgnot
194	}
195	if b.RefundUgnot > 0 {
196		return b.RefundUgnot
197	}
198	return b.InitialUgnot
199}
200
201func encodeBountyJSON(b *bountyRecord, includeFound bool) string {
202	donorCount := int64(0)
203	if b.DonorShares != nil {
204		donorCount = int64(b.DonorShares.Size())
205	}
206	jb := hearthcore.NewJSONObject()
207	if includeFound {
208		jb.Bool("found", true)
209	}
210	jb.Uint64("id", b.ID).
211		Str("title", b.Title).
212		Str("spec", b.Spec).
213		Str("category", string(b.Category)).
214		Str("status", string(b.Status)).
215		Str("sponsor", string(b.Sponsor)).
216		Str("claimant", string(b.Claimant)).
217		Str("claim_note", b.ClaimNote).
218		Int64("escrow_ugnot", b.EscrowUgnot).
219		Int64("initial_ugnot", b.InitialUgnot).
220		Int64("sponsor_funded_ugnot", b.SponsorFundedUgnot).
221		Int64("external_top_up_ugnot", b.ExternalTopUpUgnot).
222		Int64("external_donor_count", donorCount).
223		Int64("payout_ugnot", b.PayoutUgnot).
224		Int64("refund_ugnot", b.RefundUgnot).
225		Str("reward_formatted", hearthcore.FormatGNOT(effectiveReward(b))).
226		Uint64("top_up_count", b.TopUpCount).
227		Int64("deadline_blocks", b.DeadlineBlocks).
228		Int64("created_height", b.CreatedHeight).
229		Int64("claimed_height", b.ClaimedHeight).
230		Int64("deadline_height", b.DeadlineHeight).
231		Int64("submitted_height", b.SubmittedHeight).
232		Int64("review_deadline_height", b.ReviewDeadlineHeight).
233		Int64("disputed_height", b.DisputedHeight).
234		Int64("dispute_deadline_height", b.DisputeDeadlineHeight).
235		Int64("settled_height", b.SettledHeight).
236		Str("proof_url", b.ProofURL).
237		Str("proof_digest", b.ProofDigest).
238		Str("proof_summary", b.ProofSummary).
239		Uint64("submission_count", b.SubmissionCount).
240		Str("revision_feedback", b.RevisionFeedback).
241		Uint64("rating", uint64(b.Rating)).
242		Str("review_note", b.ReviewNote).
243		Str("dispute_reason", b.DisputeReason).
244		Str("dispute_opened_by", string(b.DisputeOpenedBy))
245	return jb.String()
246}
247
248func encodeProfileJSON(p *profileRecord, rank int) string {
249	tier := hearthcore.ComputeTier(p.SettledCount, p.EarnedUgnot, p.RatingSum, p.RatingCount)
250	jb := hearthcore.NewJSONObject()
251	if rank == 0 {
252		jb.Bool("found", true)
253	} else {
254		jb.Int64("rank", int64(rank))
255	}
256	jb.Str("address", string(p.Address)).
257		Str("handle", p.Handle).
258		Str("bio", p.Bio).
259		Str("skills", p.Skills).
260		Str("agent_endpoint", p.AgentEndpoint).
261		Bool("is_agent", p.IsAgent).
262		Str("tier", string(tier)).
263		Uint64("posted_count", p.PostedCount).
264		Uint64("claimed_count", p.ClaimedCount).
265		Uint64("settled_count", p.SettledCount).
266		Uint64("sponsored_settled", p.SponsoredSettled).
267		Int64("earned_ugnot", p.EarnedUgnot).
268		Str("earned_formatted", hearthcore.FormatGNOT(p.EarnedUgnot)).
269		Int64("sponsored_ugnot", p.SponsoredUgnot).
270		Str("rating_formatted", hearthcore.FormatRating(p.RatingSum, p.RatingCount)).
271		Uint64("rating_sum", p.RatingSum).
272		Uint64("rating_count", p.RatingCount)
273	return jb.String()
274}
275
276type profileRankSlice []*profileRecord
277
278func (s profileRankSlice) Len() int { return len(s) }
279func (s profileRankSlice) Swap(i, j int) {
280	s[i], s[j] = s[j], s[i]
281}
282func (s profileRankSlice) Less(i, j int) bool {
283	a, b := s[i], s[j]
284	if a.EarnedUgnot != b.EarnedUgnot {
285		return a.EarnedUgnot > b.EarnedUgnot
286	}
287	if a.SettledCount != b.SettledCount {
288		return a.SettledCount > b.SettledCount
289	}
290	if a.SponsoredUgnot != b.SponsoredUgnot {
291		return a.SponsoredUgnot > b.SponsoredUgnot
292	}
293	return string(a.Address) < string(b.Address)
294}
295
296func rankedProfiles() []*profileRecord {
297	list := make([]*profileRecord, 0, profiles.Size())
298	profiles.Iterate("", "", func(_ string, val any) bool {
299		list = append(list, val.(*profileRecord))
300		return false
301	})
302
303	sort.Sort(profileRankSlice(list))
304	return list
305}