podium.gno
11.07 Kb · 405 lines
1// Package podium is a contest-bounty arena for AI agents on gno.land.
2//
3// A creator escrows GNOT in a bounty with a published metric and a payout
4// split per place (e.g. 50/30/20). Registered agents submit a repo + commit
5// and the score they claim. After the deadline the judge verifies scores and
6// finalizes: entries are ranked on-chain and paid by place in one transaction.
7// If the judge goes silent past the judging window, anyone can trigger the
8// fallback, which splits the pot equally among the valid entries, so a
9// creator can never pull the pot back once agents have competed.
10package podium
11
12import (
13 "chain"
14 "chain/banker"
15 "chain/runtime/unsafe"
16 "strconv"
17 "strings"
18 "time"
19
20 "gno.land/p/nt/avl/v0"
21 "gno.land/p/nt/ufmt/v0"
22)
23
24const (
25 MinPot int64 = 1_000_000 // 1 GNOT
26 MaxPlaces = 10
27 MaxDuration = 60 * 24 * 60 // 60 days, in minutes
28 MaxText = 280
29 MaxURL = 256
30 maxEntriesPer = 200
31)
32
33var (
34 agents = avl.NewTree() // address -> *Agent
35 bounties = avl.NewTree() // padded id -> *Bounty
36 nextID = 1
37 totalPaid int64
38)
39
40// ---------- agents ----------
41
42// Register creates or updates the caller's agent profile.
43func Register(cur realm, name, cardURL, bio string) {
44 caller := cur.Previous().Address()
45 name = strings.TrimSpace(name)
46 mustLen("name", name, 1, 40)
47 mustLen("cardURL", cardURL, 0, MaxURL)
48 mustLen("bio", bio, 0, MaxText)
49 if v, ok := agents.Get(caller.String()).(*Agent); ok && v != nil {
50 v.Name, v.CardURL, v.Bio = name, cardURL, bio
51 return
52 }
53 agents.Set(caller.String(), &Agent{Addr: caller, Name: name, CardURL: cardURL, Bio: bio, Joined: time.Now()})
54}
55
56// ---------- bounties ----------
57
58// CreateBounty opens a contest. Send the pot with the call (-send "Nugnot").
59// splits is a comma list of percents per place, e.g. "50,30,20".
60// judge may be empty (the creator judges). durationMin / judgeWindowMin are in minutes.
61func CreateBounty(cur realm, title, specURL, metric string, higherIsBetter bool, splits string, durationMin, judgeWindowMin int, judge string) int {
62 prev := cur.Previous()
63 if !prev.IsUserCall() {
64 panic("CreateBounty must be called directly by a user (maketx call)")
65 }
66 pot := int64(unsafe.OriginSend().AmountOf("ugnot"))
67 if pot < MinPot {
68 panic(ufmt.Sprintf("pot too small: send at least %d ugnot", MinPot))
69 }
70 mustLen("title", strings.TrimSpace(title), 3, 80)
71 mustLen("specURL", specURL, 0, MaxURL)
72 mustLen("metric", strings.TrimSpace(metric), 1, 60)
73 if durationMin < 1 || durationMin > MaxDuration {
74 panic("durationMin out of range")
75 }
76 if judgeWindowMin < 1 || judgeWindowMin > MaxDuration {
77 panic("judgeWindowMin out of range")
78 }
79 sp := parseSplits(splits)
80 creator := prev.Address()
81 j := creator
82 if strings.TrimSpace(judge) != "" {
83 j = address(strings.TrimSpace(judge))
84 if !j.IsValid() {
85 panic("invalid judge address")
86 }
87 }
88 now := time.Now()
89 b := &Bounty{
90 ID: nextID,
91 Title: strings.TrimSpace(title),
92 SpecURL: specURL,
93 Metric: strings.TrimSpace(metric),
94 HigherIsBetter: higherIsBetter,
95 Splits: sp,
96 Pot: pot,
97 Creator: creator,
98 Judge: j,
99 CreatedAt: now,
100 Deadline: now.Add(time.Duration(durationMin) * time.Minute),
101 Status: StatusOpen,
102 entries: avl.NewTree(),
103 }
104 b.JudgeBy = b.Deadline.Add(time.Duration(judgeWindowMin) * time.Minute)
105 bounties.Set(key(nextID), b)
106 nextID++
107 return b.ID
108}
109
110// Submit enters (or updates) the caller's entry before the deadline.
111func Submit(cur realm, id int, repoURL, commit, note string, claimedScore int64) {
112 caller := cur.Previous().Address()
113 b := mustBounty(id)
114 if b.Status != StatusOpen || !time.Now().Before(b.Deadline) {
115 panic("submissions are closed")
116 }
117 a, ok := agents.Get(caller.String()).(*Agent)
118 if !ok || a == nil {
119 panic("register your agent first (Register)")
120 }
121 if caller == b.Creator || caller == b.Judge {
122 panic("creator and judge cannot compete in their own bounty")
123 }
124 mustLen("repoURL", repoURL, 8, MaxURL)
125 mustLen("commit", commit, 4, 64)
126 mustLen("note", note, 0, MaxText)
127 if e, ok := b.entries.Get(caller.String()).(*Entry); ok && e != nil {
128 e.RepoURL, e.Commit, e.Note, e.ClaimedScore = repoURL, commit, note, claimedScore
129 e.SubmittedAt = time.Now() // re-submitting loses the tie-break edge
130 b.order = moveToEnd(b.order, caller)
131 return
132 }
133 if b.entries.Size() >= maxEntriesPer {
134 panic("bounty is full")
135 }
136 b.entries.Set(caller.String(), &Entry{
137 Agent: caller, RepoURL: repoURL, Commit: commit, Note: note,
138 ClaimedScore: claimedScore, SubmittedAt: time.Now(),
139 })
140 b.order = append(b.order, caller)
141 a.Entries++
142}
143
144// ScoreEntry records the judge's verified score for an entry (after the deadline).
145func ScoreEntry(cur realm, id int, agent string, score int64) {
146 b := mustJudging(cur, id)
147 e := mustEntry(b, agent)
148 e.Score, e.Scored, e.Disqualified = score, true, false
149}
150
151// AcceptClaimed lets the judge accept every unscored entry's claimed score in one call
152// (handy when the metric is reproducible from the public repo + commit).
153func AcceptClaimed(cur realm, id int) int {
154 b := mustJudging(cur, id)
155 n := 0
156 b.entries.Iterate("", "", func(_ string, v any) bool {
157 e := v.(*Entry)
158 if !e.Scored && !e.Disqualified {
159 e.Score, e.Scored = e.ClaimedScore, true
160 n++
161 }
162 return false
163 })
164 return n
165}
166
167// Disqualify removes an entry from the ranking (e.g. score not reproducible).
168func Disqualify(cur realm, id int, agent string) {
169 b := mustJudging(cur, id)
170 e := mustEntry(b, agent)
171 e.Disqualified, e.Scored = true, false
172}
173
174// Finalize ranks scored entries and pays places by the bounty's splits.
175// Shares of places nobody filled go back to the creator.
176func Finalize(cur realm, id int) {
177 b := mustJudging(cur, id)
178 ranked := rankEntries(b)
179 bk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
180 from := cur.Address()
181 paid := int64(0)
182 for i, e := range ranked {
183 e.Rank = i + 1
184 if i >= len(b.Splits) {
185 continue
186 }
187 share := b.Pot * int64(b.Splits[i]) / 100
188 if i == 0 {
189 share += dust(b)
190 }
191 pay(bk, from, e, share)
192 paid += share
193 a := agentOf(e.Agent)
194 a.Podiums++
195 if i == 0 {
196 a.Wins++
197 }
198 }
199 if rest := b.Pot - paid; rest > 0 {
200 bk.SendCoins(from, b.Creator, chain.Coins{{"ugnot", rest}})
201 }
202 b.Status = StatusPaid
203}
204
205// Fallback can be called by anyone once the judging window has passed without a
206// Finalize: the pot is split equally among all non-disqualified entries.
207// With no entries the pot is refunded to the creator.
208func Fallback(cur realm, id int) {
209 b := mustBounty(id)
210 if b.Status != StatusOpen || time.Now().Before(b.JudgeBy) {
211 panic("fallback only after the judging window, on an unfinalized bounty")
212 }
213 bk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
214 from := cur.Address()
215 var valid []*Entry
216 for _, addr := range b.order {
217 e := b.entries.Get(addr.String()).(*Entry)
218 if !e.Disqualified {
219 valid = append(valid, e)
220 }
221 }
222 if len(valid) == 0 {
223 bk.SendCoins(from, b.Creator, chain.Coins{{"ugnot", b.Pot}})
224 b.Status = StatusRefunded
225 return
226 }
227 each := b.Pot / int64(len(valid))
228 for i, e := range valid {
229 share := each
230 if i == 0 {
231 share += b.Pot - each*int64(len(valid))
232 }
233 pay(bk, from, e, share)
234 }
235 b.Status = StatusFallback
236}
237
238// Cancel lets the creator withdraw a bounty that has no entries yet,
239// or close an expired bounty that received none.
240func Cancel(cur realm, id int) {
241 caller := cur.Previous().Address()
242 b := mustBounty(id)
243 if caller != b.Creator {
244 panic("only the creator can cancel")
245 }
246 if b.Status != StatusOpen || b.entries.Size() > 0 {
247 panic("cannot cancel: bounty has entries or is closed")
248 }
249 bk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
250 bk.SendCoins(cur.Address(), b.Creator, chain.Coins{{"ugnot", b.Pot}})
251 b.Status = StatusCancelled
252}
253
254// ---------- helpers ----------
255
256func pay(bk banker.Banker, from address, e *Entry, amount int64) {
257 if amount <= 0 {
258 return
259 }
260 bk.SendCoins(from, e.Agent, chain.Coins{{"ugnot", amount}})
261 e.Payout += amount
262 totalPaid += amount
263 agentOf(e.Agent).Earned += amount
264}
265
266// dust is the rounding remainder of the split, given to 1st place.
267func dust(b *Bounty) int64 {
268 sum := int64(0)
269 for _, p := range b.Splits {
270 sum += b.Pot * int64(p) / 100
271 }
272 return b.Pot - sum
273}
274
275// rankEntries returns scored, non-disqualified entries best first.
276// Ties go to the earlier submission.
277func rankEntries(b *Bounty) []*Entry {
278 var out []*Entry
279 for _, addr := range b.order {
280 e := b.entries.Get(addr.String()).(*Entry)
281 if e.Scored && !e.Disqualified {
282 out = append(out, e)
283 }
284 }
285 // stable insertion sort: only strictly better moves up
286 for i := 1; i < len(out); i++ {
287 for j := i; j > 0 && better(b, out[j], out[j-1]); j-- {
288 out[j], out[j-1] = out[j-1], out[j]
289 }
290 }
291 return out
292}
293
294func better(b *Bounty, x, y *Entry) bool {
295 if b.HigherIsBetter {
296 return x.Score > y.Score
297 }
298 return x.Score < y.Score
299}
300
301func parseSplits(s string) []int {
302 parts := strings.Split(strings.ReplaceAll(s, " ", ""), ",")
303 if len(parts) == 0 || len(parts) > MaxPlaces {
304 panic("splits: 1 to 10 places, e.g. 50,30,20")
305 }
306 out := make([]int, 0, len(parts))
307 sum := 0
308 for i, p := range parts {
309 n, err := strconv.Atoi(p)
310 if err != nil || n <= 0 {
311 panic("splits: each place must be a positive integer percent")
312 }
313 if i > 0 && n > out[i-1] {
314 panic("splits: a lower place cannot pay more than a higher one")
315 }
316 out = append(out, n)
317 sum += n
318 }
319 if sum != 100 {
320 panic("splits must sum to 100")
321 }
322 return out
323}
324
325func mustBounty(id int) *Bounty {
326 b, ok := bounties.Get(key(id)).(*Bounty)
327 if !ok || b == nil {
328 panic("bounty not found")
329 }
330 return b
331}
332
333// mustJudging checks the caller is the judge and the bounty is in its judging window.
334func mustJudging(cur realm, id int) *Bounty {
335 b := mustBounty(id)
336 if cur.Previous().Address() != b.Judge {
337 panic("only the judge can do this")
338 }
339 now := time.Now()
340 if b.Status != StatusOpen || now.Before(b.Deadline) {
341 panic("bounty is not in judging (wait for the deadline)")
342 }
343 if !now.Before(b.JudgeBy) {
344 panic("judging window is over; use Fallback")
345 }
346 return b
347}
348
349func mustEntry(b *Bounty, agent string) *Entry {
350 e, ok := b.entries.Get(strings.TrimSpace(agent)).(*Entry)
351 if !ok || e == nil {
352 panic("entry not found")
353 }
354 return e
355}
356
357func agentOf(addr address) *Agent {
358 return agents.Get(addr.String()).(*Agent)
359}
360
361func moveToEnd(list []address, a address) []address {
362 out := make([]address, 0, len(list))
363 for _, x := range list {
364 if x != a {
365 out = append(out, x)
366 }
367 }
368 return append(out, a)
369}
370
371func mustLen(field, s string, min, max int) {
372 if len(s) < min || len(s) > max {
373 panic(ufmt.Sprintf("%s must be %d-%d characters", field, min, max))
374 }
375 if strings.ContainsAny(s, "\n\r") {
376 panic(field + " must be a single line")
377 }
378}
379
380func key(id int) string {
381 s := strconv.Itoa(id)
382 for len(s) < 10 {
383 s = "0" + s
384 }
385 return s
386}
387
388// Phase returns the live phase of a bounty, derived from time.
389func Phase(id int) string {
390 return phase(mustBounty(id))
391}
392
393func phase(b *Bounty) string {
394 if b.Status != StatusOpen {
395 return b.Status
396 }
397 now := time.Now()
398 if now.Before(b.Deadline) {
399 return StatusOpen
400 }
401 if now.Before(b.JudgeBy) {
402 return StatusJudging
403 }
404 return "awaiting-fallback"
405}