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.

marketplace.gno

11.86 Kb · 433 lines
  1package agentmarketplace
  2
  3import (
  4	"chain"
  5	"chain/banker"
  6	"chain/runtime/unsafe"
  7	"strconv"
  8	"strings"
  9	"time"
 10
 11	"gno.land/p/nt/avl/v0"
 12)
 13
 14// Tunables.
 15const (
 16	maxAgents      = 1000
 17	maxTasks       = 5000
 18	maxBidsPerTask = 50
 19)
 20
 21var (
 22	nextTaskID = 1
 23	nextBidID  = 1
 24
 25	agents     = avl.NewTree() // owner.String() -> *Agent
 26	tasks      = avl.NewTree() // padID(taskID) -> *Task
 27	bids       = avl.NewTree() // padID(taskID) + "/" + padID(bidID) -> *Bid
 28	bidByAgent = avl.NewTree() // owner + "/" + padID(taskID) -> bidID
 29)
 30
 31// realmURL is this realm's gnoweb path, e.g. /r/demo/agentmarketplace.
 32var realmURL string
 33
 34func init(cur realm) {
 35	realmURL = strings.TrimPrefix(cur.PkgPath(), "gno.land")
 36}
 37
 38// ---------------------------------------------------------------------------
 39// Agent actions. Every crossing function is a signed transaction, so the
 40// caller address is authenticated by the chain itself.
 41
 42// RegisterAgent registers the caller as an agent. name is a display name,
 43// tags is a comma-separated list of specialties, rateKind is "hourly" or
 44// "flat", and rateUgnot is the listed price in ugnot (1 GNOT = 1,000,000 ugnot).
 45// The caller's address is the agent id; an address may register only once.
 46func RegisterAgent(cur realm, name, tags, rateKind string, rateUgnot int64) {
 47	caller := mustUserCall(cur)
 48	if agents.Get(caller.String()) != nil {
 49		panic("this address is already registered as an agent")
 50	}
 51	if agents.Size() >= maxAgents {
 52		panic("the agent registry is full")
 53	}
 54	checkText("name", name, minNameLen, maxNameLen)
 55	canonical := parseTags(tags)
 56	checkRateKind(rateKind)
 57	checkRate(rateUgnot)
 58
 59	a := &Agent{
 60		Owner:        caller,
 61		Name:         name,
 62		Tags:         canonical,
 63		RateKind:     rateKind,
 64		RateUgnot:    rateUgnot,
 65		RegisteredAt: time.Now(),
 66	}
 67	agents.Set(caller.String(), a)
 68	chain.Emit("AgentRegistered",
 69		"agent", caller.String(),
 70		"name", name,
 71		"tags", canonical,
 72		"rateKind", rateKind,
 73		"rateUgnot", strconv.FormatInt(rateUgnot, 10),
 74	)
 75}
 76
 77// UpdateAgent changes the caller's display name, specialties and rate.
 78func UpdateAgent(cur realm, name, tags, rateKind string, rateUgnot int64) {
 79	caller := mustUserCall(cur)
 80	a := mustGetAgent(caller)
 81	checkText("name", name, minNameLen, maxNameLen)
 82	canonical := parseTags(tags)
 83	checkRateKind(rateKind)
 84	checkRate(rateUgnot)
 85	a.Name = name
 86	a.Tags = canonical
 87	a.RateKind = rateKind
 88	a.RateUgnot = rateUgnot
 89	chain.Emit("AgentUpdated",
 90		"agent", caller.String(),
 91		"name", name,
 92		"tags", canonical,
 93		"rateKind", rateKind,
 94		"rateUgnot", strconv.FormatInt(rateUgnot, 10),
 95	)
 96}
 97
 98// ---------------------------------------------------------------------------
 99// Tasks and escrow.
100
101// PostTask posts a new open task and escrows the budget. The caller must
102// attach exactly budgetUgnot ugnot with the transaction (-send). Only a
103// direct user call is accepted, so OriginSend cannot be spoofed by an
104// intermediate realm. Returns the new task ID.
105func PostTask(cur realm, title, description, specialty string, budgetUgnot int64) int {
106	caller := mustUserCall(cur)
107	checkText("title", title, minTitleLen, maxTitleLen)
108	checkText("description", description, minDescLen, maxDescLen)
109	spec := checkSpecialty(specialty)
110	checkBudget(budgetUgnot)
111	requireExactUgnotSend(budgetUgnot)
112	if tasks.Size() >= maxTasks {
113		panic("the task board is full")
114	}
115
116	t := &Task{
117		ID:          nextTaskID,
118		Poster:      caller,
119		Title:       title,
120		Description: description,
121		Specialty:   spec,
122		BudgetUgnot: budgetUgnot,
123		Status:      StatusOpen,
124		PostedAt:    time.Now(),
125	}
126	nextTaskID++
127	tasks.Set(padID(t.ID), t)
128	chain.Emit("TaskPosted",
129		"id", strconv.Itoa(t.ID),
130		"poster", caller.String(),
131		"specialty", spec,
132		"budgetUgnot", strconv.FormatInt(budgetUgnot, 10),
133	)
134	return t.ID
135}
136
137// PlaceBid lets a registered agent offer to do an open task. The agent must
138// list the task's required specialty. One bid per agent per task; a later
139// call updates the amount and note. Returns the bid ID. Agents cannot bid
140// on their own tasks.
141func PlaceBid(cur realm, taskID int, amountUgnot int64, note string) int {
142	caller := mustUserCall(cur)
143	a := mustGetAgent(caller)
144	t := mustGetTask(taskID)
145	if t.Status != StatusOpen {
146		panic("bids are only accepted on open tasks")
147	}
148	if t.Poster == caller {
149		panic("the task poster cannot bid on their own task")
150	}
151	if !agentHasSpecialty(a.Tags, t.Specialty) {
152		panic("this agent does not list the required specialty: " + t.Specialty)
153	}
154	if amountUgnot < 1 || amountUgnot > t.BudgetUgnot {
155		panic("bid amount must be between 1 and the task budget of " + strconv.FormatInt(t.BudgetUgnot, 10) + " ugnot")
156	}
157	if note != "" {
158		checkText("note", note, 1, maxNoteLen)
159	}
160
161	if existing := bidByAgent.Get(caller.String() + "/" + padID(taskID)); existing != nil {
162		bidID := existing.(int)
163		b := mustGetBid(taskID, bidID)
164		b.Amount = amountUgnot
165		b.Note = note
166		b.PlacedAt = time.Now()
167		chain.Emit("BidUpdated",
168			"task", strconv.Itoa(taskID),
169			"bid", strconv.Itoa(bidID),
170			"agent", caller.String(),
171			"amountUgnot", strconv.FormatInt(amountUgnot, 10),
172		)
173		return bidID
174	}
175	if taskBidCount(taskID) >= maxBidsPerTask {
176		panic("this task already has the maximum number of bids")
177	}
178
179	b := &Bid{
180		ID:       nextBidID,
181		TaskID:   taskID,
182		Agent:    caller,
183		Amount:   amountUgnot,
184		Note:     note,
185		PlacedAt: time.Now(),
186	}
187	nextBidID++
188	bids.Set(bidKey(taskID, b.ID), b)
189	bidByAgent.Set(caller.String()+"/"+padID(taskID), b.ID)
190	chain.Emit("BidPlaced",
191		"task", strconv.Itoa(taskID),
192		"bid", strconv.Itoa(b.ID),
193		"agent", caller.String(),
194		"amountUgnot", strconv.FormatInt(amountUgnot, 10),
195	)
196	return b.ID
197}
198
199// AcceptBid is called by the task poster to pick a bid. The task moves to
200// in-progress and the winning agent is recorded. Escrow stays locked until
201// CompleteTask or (only while still open) CancelTask.
202func AcceptBid(cur realm, taskID, bidID int) {
203	caller := mustUserCall(cur)
204	t := mustGetTask(taskID)
205	if t.Poster != caller {
206		panic("only the task poster can accept a bid")
207	}
208	if t.Status != StatusOpen {
209		panic("only an open task can accept a bid")
210	}
211	b := mustGetBid(taskID, bidID)
212	t.Status = StatusInProgress
213	t.WinningBidID = b.ID
214	t.Winner = b.Agent
215	t.AcceptedAt = time.Now()
216	chain.Emit("BidAccepted",
217		"task", strconv.Itoa(taskID),
218		"bid", strconv.Itoa(bidID),
219		"agent", b.Agent.String(),
220		"amountUgnot", strconv.FormatInt(b.Amount, 10),
221	)
222}
223
224// CompleteTask is called by the winning agent to mark the work done and
225// settle escrow. The winning bid amount is sent to the agent; any leftover
226// budget (budget minus bid) is refunded to the poster. State is updated
227// before coins move, so a re-entrant call cannot settle twice.
228// Hash-commit tasks must use RevealAndComplete instead.
229func CompleteTask(cur realm, taskID int) {
230	caller := mustUserCall(cur)
231	t := mustGetTask(taskID)
232	if t.CommitHash != "" {
233		panic("this task requires a hash reveal: call RevealAndComplete")
234	}
235	if t.Status != StatusInProgress {
236		panic("only an in-progress task can be completed")
237	}
238	if t.Winner != caller {
239		panic("only the winning agent can mark this task complete")
240	}
241	if t.Settled {
242		panic("this task has already been settled")
243	}
244	settleTask(cur, t, "open")
245}
246
247// settleTask applies the completed-and-paid state and moves coins.
248// caller checks must already have been performed.
249func settleTask(cur realm, t *Task, method string) {
250	b := mustGetBid(t.ID, t.WinningBidID)
251	pay := b.Amount
252	refund := t.BudgetUgnot - pay
253	if refund < 0 {
254		panic("invariant: bid exceeds escrowed budget")
255	}
256
257	// Effects first, then interactions.
258	t.Status = StatusCompleted
259	t.Settled = true
260	t.CompletedAt = time.Now()
261	if av := agents.Get(t.Winner.String()); av != nil {
262		a := av.(*Agent)
263		a.Completed++
264		a.EarnedUgnot += pay
265	}
266	recordPosterPayment(t.Poster, t.Winner, t.BudgetUgnot)
267	chain.Emit("TaskCompleted",
268		"task", strconv.Itoa(t.ID),
269		"agent", t.Winner.String(),
270		"paidUgnot", strconv.FormatInt(pay, 10),
271		"refundedUgnot", strconv.FormatInt(refund, 10),
272		"method", method,
273	)
274	sendUgnot(cur, t.Winner, pay)
275	sendUgnot(cur, t.Poster, refund)
276}
277
278// CancelTask is called by the poster of an open task to withdraw it and
279// refund the full escrowed budget. In-progress, completed or already
280// cancelled tasks cannot be cancelled.
281func CancelTask(cur realm, taskID int) {
282	caller := mustUserCall(cur)
283	t := mustGetTask(taskID)
284	if t.Poster != caller {
285		panic("only the task poster can cancel this task")
286	}
287	if t.Status != StatusOpen {
288		panic("only an open task can be cancelled")
289	}
290	if t.Settled {
291		panic("this task has already been settled")
292	}
293
294	t.Status = StatusCancelled
295	t.Settled = true
296	chain.Emit("TaskCancelled",
297		"task", strconv.Itoa(taskID),
298		"poster", caller.String(),
299		"refundedUgnot", strconv.FormatInt(t.BudgetUgnot, 10),
300	)
301	sendUgnot(cur, t.Poster, t.BudgetUgnot)
302}
303
304// ---------------------------------------------------------------------------
305// Read-only helpers (safe to query with vm/qeval).
306
307// AgentCount returns the number of registered agents.
308func AgentCount() int { return agents.Size() }
309
310// TaskCount returns the number of tasks ever posted (including settled).
311func TaskCount() int { return tasks.Size() }
312
313// Stats returns agents, open tasks, in-progress tasks, completed tasks
314// and the ugnot still held in escrow.
315func Stats() (int, int, int, int, int64) {
316	open, prog, done := 0, 0, 0
317	var escrow int64
318	tasks.Iterate("", "", func(_ string, v any) bool {
319		t := v.(*Task)
320		switch t.Status {
321		case StatusOpen:
322			open++
323			escrow += t.BudgetUgnot
324		case StatusInProgress:
325			prog++
326			escrow += t.BudgetUgnot
327		case StatusCompleted:
328			done++
329		}
330		return false
331	})
332	return agents.Size(), open, prog, done, escrow
333}
334
335// AgentSummary returns a one-line text summary, or "" if unknown.
336func AgentSummary(owner address) string {
337	v := agents.Get(owner.String())
338	if v == nil {
339		return ""
340	}
341	a := v.(*Agent)
342	return a.Name + " | " + a.Tags + " | " + a.RateKind + " " + fmtUgnot(a.RateUgnot) + " | completed " + strconv.Itoa(a.Completed)
343}
344
345// TaskSummary returns a one-line text summary, or "" if unknown.
346func TaskSummary(id int) string {
347	v := tasks.Get(padID(id))
348	if v == nil {
349		return ""
350	}
351	t := v.(*Task)
352	return t.Title + " | " + t.Status + " | " + t.Specialty + " | " + fmtUgnot(t.BudgetUgnot)
353}
354
355// ---------------------------------------------------------------------------
356// internals
357
358func mustUserCall(cur realm) address {
359	if !cur.IsCurrent() {
360		panic("spoofed realm")
361	}
362	prev := cur.Previous()
363	if !prev.IsUserCall() {
364		panic("only a direct user call is accepted")
365	}
366	return prev.Address()
367}
368
369func mustGetAgent(owner address) *Agent {
370	v := agents.Get(owner.String())
371	if v == nil {
372		panic("no agent is registered at this address")
373	}
374	return v.(*Agent)
375}
376
377func mustGetTask(id int) *Task {
378	v := tasks.Get(padID(id))
379	if v == nil {
380		panic("task " + strconv.Itoa(id) + " not found")
381	}
382	return v.(*Task)
383}
384
385func mustGetBid(taskID, bidID int) *Bid {
386	v := bids.Get(bidKey(taskID, bidID))
387	if v == nil {
388		panic("bid " + strconv.Itoa(bidID) + " not found on task " + strconv.Itoa(taskID))
389	}
390	return v.(*Bid)
391}
392
393func bidKey(taskID, bidID int) string {
394	return padID(taskID) + "/" + padID(bidID)
395}
396
397func taskBidCount(taskID int) int {
398	count := 0
399	prefix := padID(taskID) + "/"
400	bids.Iterate(prefix, prefix+"~", func(_ string, _ any) bool {
401		count++
402		return false
403	})
404	return count
405}
406
407func requireExactUgnotSend(budget int64) {
408	sent := unsafe.OriginSend()
409	if len(sent) != 1 || sent[0].Denom != "ugnot" || sent[0].Amount != budget {
410		got := "nothing"
411		if len(sent) != 0 {
412			got = sent.String()
413		}
414		panic("must send exactly " + strconv.FormatInt(budget, 10) + "ugnot with this call (got " + got + ")")
415	}
416}
417
418func sendUgnot(cur realm, to address, amount int64) {
419	if amount <= 0 {
420		return
421	}
422	bk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
423	bk.SendCoins(cur.Address(), to, chain.Coins{chain.NewCoin("ugnot", amount)})
424}
425
426// padID makes IDs sort numerically as avl keys.
427func padID(id int) string {
428	s := strconv.Itoa(id)
429	for len(s) < 9 {
430		s = "0" + s
431	}
432	return s
433}