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.

escrow.gno

20.45 Kb · 670 lines
  1package hearthbounty
  2
  3import (
  4	"chain"
  5	"chain/runtime"
  6	"strconv"
  7	"strings"
  8
  9	"gno.land/p/g1x582angdzrqadgv4382j6y7ju6fj5wll6yuuq4/hearthcore/v0"
 10	"gno.land/p/nt/avl/v0"
 11	"gno.land/r/nt/grc20reg/v0"
 12)
 13
 14type contributorRefund struct {
 15	addr   address
 16	amount int64
 17}
 18
 19// ValidateEscrowToken verifies that a requested settlement token key matches
 20// the canonical 1:1 ugnot-backed wrapped GNOT key registered in grc20reg.
 21func ValidateEscrowToken(tokenKey string) {
 22	if strings.TrimSpace(tokenKey) != EscrowTokenKey {
 23		panic("hearthbounty: only 1:1 ugnot-backed wugnot escrow is accepted")
 24	}
 25}
 26
 27func validateEscrowAmount(amount, minAmount int64) int64 {
 28	if amount < minAmount {
 29		panic("hearthbounty: escrow amount is below minimum required (100000 wugnot)")
 30	}
 31	if amount > MaxEscrowUgnot {
 32		panic("hearthbounty: escrow amount exceeds single-bounty safety ceiling")
 33	}
 34	return amount
 35}
 36
 37// SetArbiter transfers dispute-resolution authority to a new valid Gno address.
 38func SetArbiter(cur realm, next address) {
 39	caller := cur.Previous().Address()
 40	if caller != arbiter {
 41		panic("hearthbounty: only current arbiter may transfer arbiter role")
 42	}
 43	if !next.IsValid() {
 44		panic("hearthbounty: next arbiter address is invalid")
 45	}
 46	arbiter = next
 47	chain.Emit(
 48		"ArbiterUpdated",
 49		"previous", string(caller),
 50		"arbiter", string(next),
 51	)
 52}
 53
 54// RegisterProfile creates or updates a builder or autonomous AI agent profile.
 55// Providing a non-empty agentEndpoint marks the profile as an MCP-capable AI agent.
 56func RegisterProfile(cur realm, handle, bio, skills, agentEndpoint string) {
 57	caller := cur.Previous().Address()
 58	cleanHandle := hearthcore.ValidateText("handle", handle, 2, hearthcore.MaxHandleLen)
 59	cleanBio := hearthcore.ValidateText("bio", bio, 0, hearthcore.MaxBioLen)
 60	cleanSkills := hearthcore.ValidateText("skills", skills, 0, hearthcore.MaxSkillsLen)
 61	cleanEndpoint := hearthcore.ValidateText("agentEndpoint", agentEndpoint, 0, hearthcore.MaxEndpointLen)
 62
 63	p := getOrCreateProfile(caller, runtime.ChainHeight())
 64	wasAgent := p.IsAgent
 65	p.Handle = cleanHandle
 66	p.Bio = cleanBio
 67	p.Skills = cleanSkills
 68	p.AgentEndpoint = cleanEndpoint
 69	p.IsAgent = cleanEndpoint != ""
 70
 71	if !wasAgent && p.IsAgent {
 72		agentCount++
 73	} else if wasAgent && !p.IsAgent {
 74		agentCount--
 75	}
 76
 77	chain.Emit(
 78		"ProfileRegistered",
 79		"address", string(caller),
 80		"handle", cleanHandle,
 81		"is_agent", strconv.FormatBool(p.IsAgent),
 82	)
 83}
 84
 85// PostBounty creates a new micro-bounty funded with pre-approved 1:1 ugnot-backed
 86// wugnot via gno.land/r/nt/grc20reg/v0.
 87// Requires a direct EOA call (AssertOriginCall + cur.Previous().IsUserCall()).
 88func PostBounty(cur realm, title, spec, category string, rewardUgnot int64, deadlineBlocks int64) uint64 {
 89	runtime.AssertOriginCall()
 90	if !cur.Previous().IsUserCall() {
 91		panic("hearthbounty: direct EOA call required to fund escrow")
 92	}
 93
 94	amount := validateEscrowAmount(rewardUgnot, hearthcore.MinRewardUgnot)
 95	cleanTitle := hearthcore.ValidateText("title", title, 4, hearthcore.MaxTitleLen)
 96	cleanSpec := hearthcore.ValidateText("spec", spec, 10, hearthcore.MaxSpecLen)
 97	cat, ok := hearthcore.ParseCategory(category)
 98	if !ok {
 99		panic("hearthbounty: invalid category (use realm, tool, audit, docs, or agent)")
100	}
101	blocks := hearthcore.ValidateDeadlineBlocks(deadlineBlocks)
102
103	sponsor := cur.Previous().Address()
104	// Pull pre-approved wugnot into realm custody before mutating bounty state.
105	// Panics atomically if sponsor balance or allowance is insufficient.
106	grc20reg.TransferFrom(0, cur, EscrowTokenKey, sponsor, cur.Address(), amount)
107
108	height := runtime.ChainHeight()
109	nextID := uint64(bountySeq.Next())
110
111	rec := &bountyRecord{
112		ID:                 nextID,
113		Title:              cleanTitle,
114		Spec:               cleanSpec,
115		Category:           cat,
116		Status:             hearthcore.StatusOpen,
117		Sponsor:            sponsor,
118		EscrowUgnot:        amount,
119		InitialUgnot:       amount,
120		SponsorFundedUgnot: amount,
121		DonorShares:        avl.NewTree(),
122		DeadlineBlocks:     blocks,
123		CreatedHeight:      height,
124	}
125
126	bounties.Set(bountyKey(nextID), rec)
127	openCount++
128	totalEscrowUgnot += amount
129
130	sp := getOrCreateProfile(sponsor, height)
131	sp.PostedCount++
132	sp.SponsoredUgnot += amount
133
134	chain.Emit(
135		"BountyPosted",
136		"id", strconv.FormatUint(nextID, 10),
137		"sponsor", string(sponsor),
138		"category", string(cat),
139		"escrow_token", EscrowTokenKey,
140		"escrow_ugnot", strconv.FormatInt(amount, 10),
141		"deadline_blocks", strconv.FormatInt(blocks, 10),
142	)
143
144	return nextID
145}
146
147// TopUpBounty allows supporters or the sponsor to add pre-approved wugnot
148// (>= 0.10 GNOT) into an Open or Claimed bounty. Per-contributor custody is
149// tracked in an AVL donor ledger so cancellations and dispute splits refund
150// each contributor directly instead of handing external coins to the sponsor.
151func TopUpBounty(cur realm, id uint64, amountUgnot int64) int64 {
152	runtime.AssertOriginCall()
153	if !cur.Previous().IsUserCall() {
154		panic("hearthbounty: direct EOA call required to top up escrow")
155	}
156
157	amount := validateEscrowAmount(amountUgnot, MinTopUpUgnot)
158	donor := cur.Previous().Address()
159	b := validateTopUpTarget(donor, id, amount)
160
161	grc20reg.TransferFrom(0, cur, EscrowTokenKey, donor, cur.Address(), amount)
162
163	if donor == b.Sponsor {
164		b.SponsorFundedUgnot += amount
165	} else {
166		if b.DonorShares == nil {
167			b.DonorShares = avl.NewTree()
168		}
169		key := string(donor)
170		prev := int64(0)
171		if raw := b.DonorShares.Get(key); raw != nil {
172			prev = raw.(int64)
173		}
174		b.DonorShares.Set(key, prev+amount)
175		b.ExternalTopUpUgnot += amount
176	}
177
178	b.EscrowUgnot += amount
179	b.TopUpCount++
180	totalEscrowUgnot += amount
181
182	dp := getOrCreateProfile(donor, runtime.ChainHeight())
183	dp.SponsoredUgnot += amount
184
185	chain.Emit(
186		"BountyToppedUp",
187		"id", strconv.FormatUint(id, 10),
188		"donor", string(donor),
189		"added_ugnot", strconv.FormatInt(amount, 10),
190		"escrow_ugnot", strconv.FormatInt(b.EscrowUgnot, 10),
191	)
192
193	return b.EscrowUgnot
194}
195
196func validateTopUpTarget(donor address, id uint64, amount int64) *bountyRecord {
197	b, ok := getBountyRecord(id)
198	if !ok {
199		panic("hearthbounty: bounty not found")
200	}
201	if b.Status != hearthcore.StatusOpen && b.Status != hearthcore.StatusClaimed {
202		panic("hearthbounty: can only top up open or claimed bounties")
203	}
204	if b.Claimant != "" && donor == b.Claimant {
205		panic("hearthbounty: active claimant cannot top up own claimed bounty")
206	}
207	if b.EscrowUgnot+amount > MaxEscrowUgnot {
208		panic("hearthbounty: escrow total exceeds single-bounty safety ceiling")
209	}
210	if donor != b.Sponsor && b.DonorShares != nil && !b.DonorShares.Has(string(donor)) && b.DonorShares.Size() >= MaxExternalDonors {
211		panic("hearthbounty: external donor cap reached for this bounty")
212	}
213	return b
214}
215
216// ClaimBounty reserves an open bounty for a builder or autonomous AI agent.
217// Sponsors and external escrow contributors cannot claim the bounty they funded.
218func ClaimBounty(cur realm, id uint64, agentNote string) {
219	b, ok := getBountyRecord(id)
220	if !ok {
221		panic("hearthbounty: bounty not found")
222	}
223	if b.Status != hearthcore.StatusOpen {
224		panic("hearthbounty: bounty is not open for claiming")
225	}
226
227	caller := cur.Previous().Address()
228	if caller == b.Sponsor {
229		panic("hearthbounty: sponsor cannot claim own bounty")
230	}
231	if b.DonorShares != nil && b.DonorShares.Has(string(caller)) {
232		panic("hearthbounty: escrow contributor cannot claim own funded bounty")
233	}
234	cleanNote := hearthcore.ValidateText("agentNote", agentNote, 0, hearthcore.MaxNoteLen)
235
236	height := runtime.ChainHeight()
237	transitionStatus(b, hearthcore.StatusClaimed)
238	b.Claimant = caller
239	b.ClaimNote = cleanNote
240	b.ClaimedHeight = height
241	b.DeadlineHeight = height + b.DeadlineBlocks
242
243	hp := getOrCreateProfile(caller, height)
244	hp.ClaimedCount++
245
246	chain.Emit(
247		"BountyClaimed",
248		"id", strconv.FormatUint(id, 10),
249		"claimant", string(caller),
250		"deadline_height", strconv.FormatInt(b.DeadlineHeight, 10),
251	)
252}
253
254// ReleaseExpiredClaim returns a claimed bounty to Open when either the claimant
255// voluntarily steps down or ChainHeight() reaches DeadlineHeight.
256func ReleaseExpiredClaim(cur realm, id uint64) {
257	b, ok := getBountyRecord(id)
258	if !ok {
259		panic("hearthbounty: bounty not found")
260	}
261	if b.Status != hearthcore.StatusClaimed {
262		panic("hearthbounty: bounty is not currently claimed")
263	}
264
265	caller := cur.Previous().Address()
266	height := runtime.ChainHeight()
267	if caller != b.Claimant && height < b.DeadlineHeight {
268		panic("hearthbounty: claim deadline has not expired yet")
269	}
270
271	prevClaimant := b.Claimant
272	if raw := profiles.Get(string(prevClaimant)); raw != nil {
273		p := raw.(*profileRecord)
274		if p.ClaimedCount > 0 {
275			p.ClaimedCount--
276		}
277	}
278
279	transitionStatus(b, hearthcore.StatusOpen)
280	b.Claimant = ""
281	b.ClaimNote = ""
282	b.ClaimedHeight = 0
283	b.DeadlineHeight = 0
284	b.SubmittedHeight = 0
285	b.ReviewDeadlineHeight = 0
286	b.ProofURL = ""
287	b.ProofDigest = ""
288	b.ProofSummary = ""
289	b.RevisionFeedback = ""
290
291	chain.Emit(
292		"ClaimReleased",
293		"id", strconv.FormatUint(id, 10),
294		"previous_claimant", string(prevClaimant),
295		"released_by", string(caller),
296	)
297}
298
299// SubmitProof records an HTTPS deliverable URL, SHA-256 content digest, and
300// implementation summary, opening a deterministic sponsor review window.
301func SubmitProof(cur realm, id uint64, proofURL, proofDigest, summary string) {
302	b, ok := getBountyRecord(id)
303	if !ok {
304		panic("hearthbounty: bounty not found")
305	}
306	if b.Status != hearthcore.StatusClaimed {
307		panic("hearthbounty: bounty must be claimed before submitting proof")
308	}
309
310	caller := cur.Previous().Address()
311	if caller != b.Claimant {
312		panic("hearthbounty: only the active claimant may submit proof")
313	}
314
315	cleanURL := ValidateProofURL(proofURL)
316	cleanDigest := hearthcore.ValidateProofDigest(proofDigest)
317	cleanSummary := hearthcore.ValidateText("summary", summary, 6, hearthcore.MaxNoteLen)
318	height := runtime.ChainHeight()
319
320	transitionStatus(b, hearthcore.StatusSubmitted)
321	b.ProofURL = cleanURL
322	b.ProofDigest = cleanDigest
323	b.ProofSummary = cleanSummary
324	b.SubmittedHeight = height
325	b.ReviewDeadlineHeight = height + b.DeadlineBlocks
326	b.SubmissionCount++
327	b.RevisionFeedback = ""
328
329	chain.Emit(
330		"ProofSubmitted",
331		"id", strconv.FormatUint(id, 10),
332		"claimant", string(caller),
333		"proof_digest", cleanDigest,
334		"review_deadline_height", strconv.FormatInt(b.ReviewDeadlineHeight, 10),
335		"submission_count", strconv.FormatUint(b.SubmissionCount, 10),
336	)
337}
338
339// RequestRevision lets the sponsor send a submitted bounty back to Claimed with
340// actionable feedback and a refreshed claim deadline window.
341func RequestRevision(cur realm, id uint64, feedback string) {
342	b, ok := getBountyRecord(id)
343	if !ok {
344		panic("hearthbounty: bounty not found")
345	}
346	if b.Status != hearthcore.StatusSubmitted {
347		panic("hearthbounty: bounty has no pending submission")
348	}
349
350	caller := cur.Previous().Address()
351	if caller != b.Sponsor {
352		panic("hearthbounty: only the sponsor may request a revision")
353	}
354
355	cleanFeedback := hearthcore.ValidateText("feedback", feedback, 4, hearthcore.MaxNoteLen)
356	transitionStatus(b, hearthcore.StatusClaimed)
357	b.RevisionFeedback = cleanFeedback
358	b.ReviewDeadlineHeight = 0
359	b.DeadlineHeight = runtime.ChainHeight() + b.DeadlineBlocks
360
361	chain.Emit(
362		"RevisionRequested",
363		"id", strconv.FormatUint(id, 10),
364		"sponsor", string(caller),
365		"new_deadline_height", strconv.FormatInt(b.DeadlineHeight, 10),
366	)
367}
368
369// ApproveAndSettle releases the full wugnot escrow to the claimant, records a
370// 1-5 quality rating, and updates on-chain reputation using CEI ordering.
371func ApproveAndSettle(cur realm, id uint64, rating uint8, reviewNote string) {
372	b, ok := getBountyRecord(id)
373	if !ok {
374		panic("hearthbounty: bounty not found")
375	}
376	if b.Status != hearthcore.StatusSubmitted {
377		panic("hearthbounty: bounty is not awaiting approval")
378	}
379
380	caller := cur.Previous().Address()
381	if caller != b.Sponsor {
382		panic("hearthbounty: only the sponsor may approve and settle")
383	}
384
385	validRating := hearthcore.ValidateRating(rating)
386	cleanNote := hearthcore.ValidateText("reviewNote", reviewNote, 0, hearthcore.MaxNoteLen)
387	settleFullToClaimant(cur, b, validRating, cleanNote, "BountySettled")
388}
389
390// ExpireSubmission is callable by anyone once ChainHeight() reaches
391// ReviewDeadlineHeight without sponsor action. It settles 100% of the escrow
392// to the claimant so sponsors cannot hold delivered work hostage forever.
393func ExpireSubmission(cur realm, id uint64) {
394	b, ok := getBountyRecord(id)
395	if !ok {
396		panic("hearthbounty: bounty not found")
397	}
398	if b.Status != hearthcore.StatusSubmitted {
399		panic("hearthbounty: bounty has no pending submission")
400	}
401	if runtime.ChainHeight() < b.ReviewDeadlineHeight {
402		panic("hearthbounty: submission review window has not expired yet")
403	}
404
405	settleFullToClaimant(cur, b, 0, "[Auto-Settled] Sponsor review window expired", "SubmissionExpiredSettled")
406}
407
408func settleFullToClaimant(cur realm, b *bountyRecord, rating uint8, reviewNote, eventName string) {
409	payout := b.EscrowUgnot
410	recipient := b.Claimant
411	height := runtime.ChainHeight()
412
413	// Effects before external token transfer (CEI).
414	b.EscrowUgnot = 0
415	b.SponsorFundedUgnot = 0
416	b.ExternalTopUpUgnot = 0
417	b.DonorShares = avl.NewTree()
418	b.PayoutUgnot = payout
419	b.Rating = rating
420	b.ReviewNote = reviewNote
421	b.SettledHeight = height
422	transitionStatus(b, hearthcore.StatusSettled)
423	totalEscrowUgnot -= payout
424	totalSettledUgnot += payout
425
426	hp := getOrCreateProfile(recipient, height)
427	hp.SettledCount++
428	hp.EarnedUgnot += payout
429	if rating > 0 {
430		hp.RatingSum += uint64(rating)
431		hp.RatingCount++
432	}
433
434	sp := getOrCreateProfile(b.Sponsor, height)
435	sp.SponsoredSettled++
436
437	if payout > 0 {
438		grc20reg.Transfer(0, cur, EscrowTokenKey, recipient, payout)
439	}
440
441	chain.Emit(
442		eventName,
443		"id", strconv.FormatUint(b.ID, 10),
444		"sponsor", string(b.Sponsor),
445		"claimant", string(recipient),
446		"payout_ugnot", strconv.FormatInt(payout, 10),
447		"rating", strconv.Itoa(int(rating)),
448	)
449}
450
451// CancelBounty cancels an Open bounty and refunds each contributor directly.
452// Third-party top-up coins are returned strictly to their original donors,
453// never to the sponsor, and refunded sponsorship credits are reversed.
454func CancelBounty(cur realm, id uint64) {
455	b, ok := getBountyRecord(id)
456	if !ok {
457		panic("hearthbounty: bounty not found")
458	}
459	if b.Status != hearthcore.StatusOpen {
460		panic("hearthbounty: only open bounties can be cancelled")
461	}
462
463	caller := cur.Previous().Address()
464	if caller != b.Sponsor {
465		panic("hearthbounty: only the sponsor may cancel")
466	}
467
468	totalRefund := b.EscrowUgnot
469	sponsorRefund := b.SponsorFundedUgnot
470	externalRefundTotal := int64(0)
471	donorRefunds := make([]contributorRefund, 0)
472	if b.DonorShares != nil {
473		b.DonorShares.Iterate("", "", func(key string, val any) bool {
474			amt := val.(int64)
475			if amt > 0 {
476				donorRefunds = append(donorRefunds, contributorRefund{
477					addr:   address(key),
478					amount: amt,
479				})
480				externalRefundTotal += amt
481			}
482			return false
483		})
484	}
485	if sponsorRefund+externalRefundTotal != totalRefund {
486		panic("hearthbounty: internal escrow custody invariant mismatch")
487	}
488
489	// Effects before interactions (CEI).
490	b.EscrowUgnot = 0
491	b.SponsorFundedUgnot = 0
492	b.ExternalTopUpUgnot = 0
493	b.DonorShares = avl.NewTree()
494	b.RefundUgnot = totalRefund
495	transitionStatus(b, hearthcore.StatusCancelled)
496	totalEscrowUgnot -= totalRefund
497	totalRefundUgnot += totalRefund
498
499	decrementSponsoredCredit(b.Sponsor, sponsorRefund)
500	for _, dr := range donorRefunds {
501		decrementSponsoredCredit(dr.addr, dr.amount)
502	}
503
504	if sponsorRefund > 0 {
505		grc20reg.Transfer(0, cur, EscrowTokenKey, b.Sponsor, sponsorRefund)
506	}
507	for _, dr := range donorRefunds {
508		grc20reg.Transfer(0, cur, EscrowTokenKey, dr.addr, dr.amount)
509	}
510
511	chain.Emit(
512		"BountyCancelled",
513		"id", strconv.FormatUint(id, 10),
514		"sponsor", string(b.Sponsor),
515		"sponsor_refund_ugnot", strconv.FormatInt(sponsorRefund, 10),
516		"external_refund_ugnot", strconv.FormatInt(externalRefundTotal, 10),
517		"refund_ugnot", strconv.FormatInt(totalRefund, 10),
518	)
519}
520
521// OpenDispute escalates a submitted bounty to arbiter review and sets a
522// deterministic dispute resolution timeout.
523func OpenDispute(cur realm, id uint64, reason string) {
524	b, ok := getBountyRecord(id)
525	if !ok {
526		panic("hearthbounty: bounty not found")
527	}
528	if b.Status != hearthcore.StatusSubmitted {
529		panic("hearthbounty: disputes can only be opened on submitted bounties")
530	}
531
532	caller := cur.Previous().Address()
533	if caller != b.Sponsor && caller != b.Claimant {
534		panic("hearthbounty: only sponsor or claimant may open a dispute")
535	}
536
537	cleanReason := hearthcore.ValidateText("reason", reason, 6, hearthcore.MaxNoteLen)
538	height := runtime.ChainHeight()
539	transitionStatus(b, hearthcore.StatusDisputed)
540	b.DisputeReason = cleanReason
541	b.DisputeOpenedBy = caller
542	b.DisputedHeight = height
543	b.DisputeDeadlineHeight = height + b.DeadlineBlocks
544
545	chain.Emit(
546		"DisputeOpened",
547		"id", strconv.FormatUint(id, 10),
548		"opened_by", string(caller),
549		"dispute_deadline_height", strconv.FormatInt(b.DisputeDeadlineHeight, 10),
550		"reason", cleanReason,
551	)
552}
553
554// ResolveDispute settles a disputed bounty using deterministic basis-point math
555// (hunterBps in 0..10000). The arbiter cannot resolve a bounty they are a party
556// to, and any refunded portion is returned pro-rata to sponsor and external donors.
557func ResolveDispute(cur realm, id uint64, hunterBps uint64, resolution string) {
558	caller := cur.Previous().Address()
559	if caller != arbiter {
560		panic("hearthbounty: only the arbiter may resolve disputes")
561	}
562
563	b, ok := getBountyRecord(id)
564	if !ok {
565		panic("hearthbounty: bounty not found")
566	}
567	if b.Status != hearthcore.StatusDisputed {
568		panic("hearthbounty: bounty is not disputed")
569	}
570	if caller == b.Sponsor || caller == b.Claimant {
571		panic("hearthbounty: arbiter cannot resolve a bounty they are party to")
572	}
573
574	cleanResolution := hearthcore.ValidateText("resolution", resolution, 4, hearthcore.MaxNoteLen)
575	settleDisputeSplit(cur, b, hunterBps, "[Arbiter Resolution] "+cleanResolution, caller, "DisputeResolved")
576}
577
578// ExpireDispute is callable by anyone once ChainHeight() reaches
579// DisputeDeadlineHeight without arbiter action. It splits escrow 50/50
580// (5000 bps to claimant, 5000 bps pro-rata back to contributors) so lost or
581// conflicted arbiter keys can never trap escrowed wugnot forever.
582func ExpireDispute(cur realm, id uint64) {
583	b, ok := getBountyRecord(id)
584	if !ok {
585		panic("hearthbounty: bounty not found")
586	}
587	if b.Status != hearthcore.StatusDisputed {
588		panic("hearthbounty: bounty is not disputed")
589	}
590	if runtime.ChainHeight() < b.DisputeDeadlineHeight {
591		panic("hearthbounty: dispute resolution window has not expired yet")
592	}
593
594	caller := cur.Previous().Address()
595	settleDisputeSplit(cur, b, 5000, "[Timeout Split 50/50] Arbiter resolution window expired", caller, "DisputeExpiredSplit")
596}
597
598func settleDisputeSplit(cur realm, b *bountyRecord, hunterBps uint64, reviewNote string, resolver address, eventName string) {
599	escrow := b.EscrowUgnot
600	_, sponsorRefund := hearthcore.ComputeSplit(b.SponsorFundedUgnot, hunterBps)
601
602	donorRefunds := make([]contributorRefund, 0)
603	totalRefunds := sponsorRefund
604	if b.DonorShares != nil {
605		b.DonorShares.Iterate("", "", func(key string, val any) bool {
606			amt := val.(int64)
607			if amt > 0 {
608				_, dRefund := hearthcore.ComputeSplit(amt, hunterBps)
609				if dRefund > 0 {
610					donorRefunds = append(donorRefunds, contributorRefund{
611						addr:   address(key),
612						amount: dRefund,
613					})
614					totalRefunds += dRefund
615				}
616			}
617			return false
618		})
619	}
620	hunterShare := escrow - totalRefunds
621	height := runtime.ChainHeight()
622
623	// Effects before interactions (CEI).
624	b.EscrowUgnot = 0
625	b.SponsorFundedUgnot = 0
626	b.ExternalTopUpUgnot = 0
627	b.DonorShares = avl.NewTree()
628	b.PayoutUgnot = hunterShare
629	b.RefundUgnot = totalRefunds
630	b.ReviewNote = reviewNote
631	b.SettledHeight = height
632	transitionStatus(b, hearthcore.StatusSettled)
633	totalEscrowUgnot -= escrow
634	totalSettledUgnot += hunterShare
635	totalRefundUgnot += totalRefunds
636
637	if hunterShare > 0 {
638		hp := getOrCreateProfile(b.Claimant, height)
639		hp.SettledCount++
640		hp.EarnedUgnot += hunterShare
641	}
642	decrementSponsoredCredit(b.Sponsor, sponsorRefund)
643	for _, dr := range donorRefunds {
644		decrementSponsoredCredit(dr.addr, dr.amount)
645	}
646
647	if hunterShare > 0 {
648		grc20reg.Transfer(0, cur, EscrowTokenKey, b.Claimant, hunterShare)
649	}
650	if sponsorRefund > 0 {
651		grc20reg.Transfer(0, cur, EscrowTokenKey, b.Sponsor, sponsorRefund)
652	}
653	for _, dr := range donorRefunds {
654		grc20reg.Transfer(0, cur, EscrowTokenKey, dr.addr, dr.amount)
655	}
656
657	chain.Emit(
658		eventName,
659		"id", strconv.FormatUint(b.ID, 10),
660		"resolver", string(resolver),
661		"hunter_bps", strconv.FormatUint(hunterBps, 10),
662		"hunter_ugnot", strconv.FormatInt(hunterShare, 10),
663		"sponsor_refund_ugnot", strconv.FormatInt(sponsorRefund, 10),
664		"total_refund_ugnot", strconv.FormatInt(totalRefunds, 10),
665	)
666}
667
668func normalizeFilter(raw string) string {
669	return strings.ToLower(strings.TrimSpace(raw))
670}