Playground
gnomod.toml
module = "gno.land/r/g1pzn6rn8q0pfmq4xje4j8086ncnldavyz8skgp3/agentmarketplace" gno = "0.9" [addpkg] creator = "g1pzn6rn8q0pfmq4xje4j8086ncnldavyz8skgp3" height = 1381543 max_deposit = "100000000ugnot"
hashsettle.gno
package agentmarketplace
import (
"chain"
"crypto/sha256"
"encoding/hex"
"strconv"
"time"
)
// PostHashTask is like PostTask, but settlement requires the winning agent
// to reveal a preimage of commitHash (lowercase hex SHA-256 of the expected
// result). If they miss RevealBy, anyone may call TimeoutHashTask to refund
// the poster. The budget is still sent with the call and held in escrow.
func PostHashTask(cur realm, title, description, specialty string, budgetUgnot int64, commitHash string, deadlineSecs int64) int {
caller := mustUserCall(cur)
checkText("title", title, minTitleLen, maxTitleLen)
checkText("description", description, minDescLen, maxDescLen)
spec := checkSpecialty(specialty)
checkBudget(budgetUgnot)
hash := checkCommitHash(commitHash)
checkRevealDeadline(deadlineSecs)
requireExactUgnotSend(budgetUgnot)
if tasks.Size() >= maxTasks {
panic("the task board is full")
}
now := time.Now()
t := &Task{
ID: nextTaskID,
Poster: caller,
Title: title,
Description: description,
Specialty: spec,
BudgetUgnot: budgetUgnot,
Status: StatusOpen,
PostedAt: now,
CommitHash: hash,
RevealBy: now.Add(time.Duration(deadlineSecs) * time.Second),
}
nextTaskID++
tasks.Set(padID(t.ID), t)
chain.Emit("TaskPosted",
"id", strconv.Itoa(t.ID),
"poster", caller.String(),
"specialty", spec,
"budgetUgnot", strconv.FormatInt(budgetUgnot, 10),
"commitHash", hash,
)
return t.ID
}
// RevealAndComplete is the hash-commit settle path: only the winning agent
// may call it, and only if sha256(preimage) matches the posted commit hash.
// On a match, escrow is released exactly as in CompleteTask.
func RevealAndComplete(cur realm, taskID int, preimage string) {
caller := mustUserCall(cur)
t := mustGetTask(taskID)
if t.CommitHash == "" {
panic("this task does not use hash-commit settlement; call CompleteTask")
}
if t.Status != StatusInProgress {
panic("only an in-progress task can be completed")
}
if t.Winner != caller {
panic("only the winning agent can mark this task complete")
}
if t.Settled {
panic("this task has already been settled")
}
if preimage == "" {
panic("preimage must not be empty")
}
got := sha256Hex(preimage)
if got != t.CommitHash {
panic("preimage does not match the commit hash")
}
if !t.RevealBy.IsZero() && time.Now().After(t.RevealBy) {
panic("the reveal deadline has passed; the poster can be refunded with TimeoutHashTask")
}
settleTask(cur, t, "hash")
}
// TimeoutHashTask refunds a hash-commit task to the poster after the
// reveal deadline, if it is still in progress and unpaid. Anyone may call it.
func TimeoutHashTask(cur realm, taskID int) {
mustUserCall(cur)
t := mustGetTask(taskID)
if t.CommitHash == "" {
panic("this task does not use hash-commit settlement")
}
if t.Status != StatusInProgress {
panic("only an in-progress hash task can time out")
}
if t.Settled {
panic("this task has already been settled")
}
if t.RevealBy.IsZero() || !time.Now().After(t.RevealBy) {
panic("the reveal deadline has not passed")
}
t.Status = StatusCancelled
t.Settled = true
chain.Emit("TaskCancelled",
"task", strconv.Itoa(taskID),
"poster", t.Poster.String(),
"refundedUgnot", strconv.FormatInt(t.BudgetUgnot, 10),
"reason", "reveal-timeout",
)
sendUgnot(cur, t.Poster, t.BudgetUgnot)
}
func sha256Hex(s string) string {
sum := sha256.Sum256([]byte(s))
return hex.EncodeToString(sum[:])
}
hashsettle_test.gno
package agentmarketplace
import (
"testing"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
const knownPhrase = "the expected result phrase"
func TestHashCommitHappyPath(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
hash := sha256Hex(knownPhrase)
id := postHash(cur, alice, "Known answer task", "Reveal the phrase I already committed to.", "research", 2000000, hash, 3600)
tk := mustGetTask(id)
uassert.Equal(t, hash, tk.CommitHash)
uassert.False(t, tk.RevealBy.IsZero())
bidID := bid(cur, carol, id, 1500000, "I know it")
accept(cur, alice, id, bidID)
urequire.AbortsWithMessage(t, cur, "this task requires a hash reveal: call RevealAndComplete", func() {
complete(cur, carol, id)
})
urequire.AbortsWithMessage(t, cur, "preimage does not match the commit hash", func() {
reveal(cur, carol, id, "wrong phrase")
})
urequire.AbortsWithMessage(t, cur, "preimage must not be empty", func() {
reveal(cur, carol, id, "")
})
urequire.AbortsWithMessage(t, cur, "only the winning agent can mark this task complete", func() {
reveal(cur, alice, id, knownPhrase)
})
reveal(cur, carol, id, knownPhrase)
tk = mustGetTask(id)
uassert.Equal(t, StatusCompleted, tk.Status)
uassert.True(t, tk.Settled)
uassert.Equal(t, 1, mustGetAgent(carol).Completed)
// poster can rate after a hash settlement just like a normal one
rid := rate(cur, alice, id, 5, "Hash matched")
uassert.Equal(t, 1, rid)
_, trust, _, _ := ScoreOf(carol)
uassert.Equal(t, int64(5000), trust)
}
func TestHashCommitRefusesOrdinaryCompleteAndViceVersa(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
ordinary := settleJob(cur, alice, carol, "Ordinary research", "This task has no commit hash.", "research", 2000000)
urequire.AbortsWithMessage(t, cur, "this task does not use hash-commit settlement; call CompleteTask", func() {
reveal(cur, carol, ordinary, knownPhrase)
})
hash := sha256Hex(knownPhrase)
id := postHash(cur, alice, "Known answer task", "Reveal the phrase I already committed to.", "research", 1000000, hash, 3600)
bidID := bid(cur, carol, id, 1000000, "ready")
accept(cur, alice, id, bidID)
urequire.AbortsWithMessage(t, cur, "this task requires a hash reveal: call RevealAndComplete", func() {
complete(cur, carol, id)
})
}
func TestHashCommitTimeoutRefund(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
hash := sha256Hex(knownPhrase)
id := postHash(cur, alice, "Known answer task", "Reveal the phrase I already committed to.", "research", 2000000, hash, minRevealSecs)
bidID := bid(cur, carol, id, 2000000, "ready")
accept(cur, alice, id, bidID)
urequire.AbortsWithMessage(t, cur, "the reveal deadline has not passed", func() {
timeoutHash(cur, bob, id)
})
// min reveal is 60s; each height is 5s, so 13 heights is past the deadline.
testing.SkipHeights(13)
urequire.AbortsWithMessage(t, cur, "the reveal deadline has passed; the poster can be refunded with TimeoutHashTask", func() {
reveal(cur, carol, id, knownPhrase)
})
timeoutHash(cur, bob, id) // anyone may time it out
tk := mustGetTask(id)
uassert.Equal(t, StatusCancelled, tk.Status)
uassert.True(t, tk.Settled)
urequire.AbortsWithMessage(t, cur, "only an in-progress hash task can time out", func() {
timeoutHash(cur, alice, id)
})
urequire.AbortsWithMessage(t, cur, "only a settled, completed task can be rated", func() {
rate(cur, alice, id, 5, "timed out")
})
}
func TestHashCommitValidation(cur realm, t *testing.T) {
reset()
urequire.AbortsWithMessage(t, cur, "commit hash must be a 64-character hex SHA-256 digest", func() {
postHash(cur, alice, "Known answer task", "Reveal the phrase I already committed to.", "research", 1000000, "abc", 3600)
})
urequire.AbortsWithMessage(t, cur, "commit hash must be a 64-character hex SHA-256 digest", func() {
postHash(cur, alice, "Known answer task", "Reveal the phrase I already committed to.", "research", 1000000, "gg"+sha256Hex(knownPhrase)[2:], 3600)
})
urequire.AbortsWithMessage(t, cur, "reveal deadline must be between 60 seconds and 30 days", func() {
postHash(cur, alice, "Known answer task", "Reveal the phrase I already committed to.", "research", 1000000, sha256Hex(knownPhrase), 59)
})
// uppercase hex is accepted and stored in lowercase
lower := sha256Hex(knownPhrase)
upper := toUpperHex(lower)
id := postHash(cur, alice, "Known answer task", "Reveal the phrase I already committed to.", "research", 1000000, upper, 3600)
uassert.Equal(t, lower, mustGetTask(id).CommitHash)
}
func TestHashCommitOpenCancelStillWorks(cur realm, t *testing.T) {
reset()
id := postHash(cur, alice, "Known answer task", "Reveal the phrase I already committed to.", "research", 2000000, sha256Hex(knownPhrase), 3600)
cancel(cur, alice, id)
uassert.Equal(t, StatusCancelled, mustGetTask(id).Status)
uassert.True(t, mustGetTask(id).Settled)
}
func toUpperHex(s string) string {
out := ""
for _, c := range s {
if c >= 'a' && c <= 'f' {
out += string(c - ('a' - 'A'))
} else {
out += string(c)
}
}
return out
}
marketplace.gno
package agentmarketplace
import (
"chain"
"chain/banker"
"chain/runtime/unsafe"
"strconv"
"strings"
"time"
"gno.land/p/nt/avl/v0"
)
// Tunables.
const (
maxAgents = 1000
maxTasks = 5000
maxBidsPerTask = 50
)
var (
nextTaskID = 1
nextBidID = 1
agents = avl.NewTree() // owner.String() -> *Agent
tasks = avl.NewTree() // padID(taskID) -> *Task
bids = avl.NewTree() // padID(taskID) + "/" + padID(bidID) -> *Bid
bidByAgent = avl.NewTree() // owner + "/" + padID(taskID) -> bidID
)
// realmURL is this realm's gnoweb path, e.g. /r/demo/agentmarketplace.
var realmURL string
func init(cur realm) {
realmURL = strings.TrimPrefix(cur.PkgPath(), "gno.land")
}
// ---------------------------------------------------------------------------
// Agent actions. Every crossing function is a signed transaction, so the
// caller address is authenticated by the chain itself.
// RegisterAgent registers the caller as an agent. name is a display name,
// tags is a comma-separated list of specialties, rateKind is "hourly" or
// "flat", and rateUgnot is the listed price in ugnot (1 GNOT = 1,000,000 ugnot).
// The caller's address is the agent id; an address may register only once.
func RegisterAgent(cur realm, name, tags, rateKind string, rateUgnot int64) {
caller := mustUserCall(cur)
if agents.Get(caller.String()) != nil {
panic("this address is already registered as an agent")
}
if agents.Size() >= maxAgents {
panic("the agent registry is full")
}
checkText("name", name, minNameLen, maxNameLen)
canonical := parseTags(tags)
checkRateKind(rateKind)
checkRate(rateUgnot)
a := &Agent{
Owner: caller,
Name: name,
Tags: canonical,
RateKind: rateKind,
RateUgnot: rateUgnot,
RegisteredAt: time.Now(),
}
agents.Set(caller.String(), a)
chain.Emit("AgentRegistered",
"agent", caller.String(),
"name", name,
"tags", canonical,
"rateKind", rateKind,
"rateUgnot", strconv.FormatInt(rateUgnot, 10),
)
}
// UpdateAgent changes the caller's display name, specialties and rate.
func UpdateAgent(cur realm, name, tags, rateKind string, rateUgnot int64) {
caller := mustUserCall(cur)
a := mustGetAgent(caller)
checkText("name", name, minNameLen, maxNameLen)
canonical := parseTags(tags)
checkRateKind(rateKind)
checkRate(rateUgnot)
a.Name = name
a.Tags = canonical
a.RateKind = rateKind
a.RateUgnot = rateUgnot
chain.Emit("AgentUpdated",
"agent", caller.String(),
"name", name,
"tags", canonical,
"rateKind", rateKind,
"rateUgnot", strconv.FormatInt(rateUgnot, 10),
)
}
// ---------------------------------------------------------------------------
// Tasks and escrow.
// PostTask posts a new open task and escrows the budget. The caller must
// attach exactly budgetUgnot ugnot with the transaction (-send). Only a
// direct user call is accepted, so OriginSend cannot be spoofed by an
// intermediate realm. Returns the new task ID.
func PostTask(cur realm, title, description, specialty string, budgetUgnot int64) int {
caller := mustUserCall(cur)
checkText("title", title, minTitleLen, maxTitleLen)
checkText("description", description, minDescLen, maxDescLen)
spec := checkSpecialty(specialty)
checkBudget(budgetUgnot)
requireExactUgnotSend(budgetUgnot)
if tasks.Size() >= maxTasks {
panic("the task board is full")
}
t := &Task{
ID: nextTaskID,
Poster: caller,
Title: title,
Description: description,
Specialty: spec,
BudgetUgnot: budgetUgnot,
Status: StatusOpen,
PostedAt: time.Now(),
}
nextTaskID++
tasks.Set(padID(t.ID), t)
chain.Emit("TaskPosted",
"id", strconv.Itoa(t.ID),
"poster", caller.String(),
"specialty", spec,
"budgetUgnot", strconv.FormatInt(budgetUgnot, 10),
)
return t.ID
}
// PlaceBid lets a registered agent offer to do an open task. The agent must
// list the task's required specialty. One bid per agent per task; a later
// call updates the amount and note. Returns the bid ID. Agents cannot bid
// on their own tasks.
func PlaceBid(cur realm, taskID int, amountUgnot int64, note string) int {
caller := mustUserCall(cur)
a := mustGetAgent(caller)
t := mustGetTask(taskID)
if t.Status != StatusOpen {
panic("bids are only accepted on open tasks")
}
if t.Poster == caller {
panic("the task poster cannot bid on their own task")
}
if !agentHasSpecialty(a.Tags, t.Specialty) {
panic("this agent does not list the required specialty: " + t.Specialty)
}
if amountUgnot < 1 || amountUgnot > t.BudgetUgnot {
panic("bid amount must be between 1 and the task budget of " + strconv.FormatInt(t.BudgetUgnot, 10) + " ugnot")
}
if note != "" {
checkText("note", note, 1, maxNoteLen)
}
if existing := bidByAgent.Get(caller.String() + "/" + padID(taskID)); existing != nil {
bidID := existing.(int)
b := mustGetBid(taskID, bidID)
b.Amount = amountUgnot
b.Note = note
b.PlacedAt = time.Now()
chain.Emit("BidUpdated",
"task", strconv.Itoa(taskID),
"bid", strconv.Itoa(bidID),
"agent", caller.String(),
"amountUgnot", strconv.FormatInt(amountUgnot, 10),
)
return bidID
}
if taskBidCount(taskID) >= maxBidsPerTask {
panic("this task already has the maximum number of bids")
}
b := &Bid{
ID: nextBidID,
TaskID: taskID,
Agent: caller,
Amount: amountUgnot,
Note: note,
PlacedAt: time.Now(),
}
nextBidID++
bids.Set(bidKey(taskID, b.ID), b)
bidByAgent.Set(caller.String()+"/"+padID(taskID), b.ID)
chain.Emit("BidPlaced",
"task", strconv.Itoa(taskID),
"bid", strconv.Itoa(b.ID),
"agent", caller.String(),
"amountUgnot", strconv.FormatInt(amountUgnot, 10),
)
return b.ID
}
// AcceptBid is called by the task poster to pick a bid. The task moves to
// in-progress and the winning agent is recorded. Escrow stays locked until
// CompleteTask or (only while still open) CancelTask.
func AcceptBid(cur realm, taskID, bidID int) {
caller := mustUserCall(cur)
t := mustGetTask(taskID)
if t.Poster != caller {
panic("only the task poster can accept a bid")
}
if t.Status != StatusOpen {
panic("only an open task can accept a bid")
}
b := mustGetBid(taskID, bidID)
t.Status = StatusInProgress
t.WinningBidID = b.ID
t.Winner = b.Agent
t.AcceptedAt = time.Now()
chain.Emit("BidAccepted",
"task", strconv.Itoa(taskID),
"bid", strconv.Itoa(bidID),
"agent", b.Agent.String(),
"amountUgnot", strconv.FormatInt(b.Amount, 10),
)
}
// CompleteTask is called by the winning agent to mark the work done and
// settle escrow. The winning bid amount is sent to the agent; any leftover
// budget (budget minus bid) is refunded to the poster. State is updated
// before coins move, so a re-entrant call cannot settle twice.
// Hash-commit tasks must use RevealAndComplete instead.
func CompleteTask(cur realm, taskID int) {
caller := mustUserCall(cur)
t := mustGetTask(taskID)
if t.CommitHash != "" {
panic("this task requires a hash reveal: call RevealAndComplete")
}
if t.Status != StatusInProgress {
panic("only an in-progress task can be completed")
}
if t.Winner != caller {
panic("only the winning agent can mark this task complete")
}
if t.Settled {
panic("this task has already been settled")
}
settleTask(cur, t, "open")
}
// settleTask applies the completed-and-paid state and moves coins.
// caller checks must already have been performed.
func settleTask(cur realm, t *Task, method string) {
b := mustGetBid(t.ID, t.WinningBidID)
pay := b.Amount
refund := t.BudgetUgnot - pay
if refund < 0 {
panic("invariant: bid exceeds escrowed budget")
}
// Effects first, then interactions.
t.Status = StatusCompleted
t.Settled = true
t.CompletedAt = time.Now()
if av := agents.Get(t.Winner.String()); av != nil {
a := av.(*Agent)
a.Completed++
a.EarnedUgnot += pay
}
recordPosterPayment(t.Poster, t.Winner, t.BudgetUgnot)
chain.Emit("TaskCompleted",
"task", strconv.Itoa(t.ID),
"agent", t.Winner.String(),
"paidUgnot", strconv.FormatInt(pay, 10),
"refundedUgnot", strconv.FormatInt(refund, 10),
"method", method,
)
sendUgnot(cur, t.Winner, pay)
sendUgnot(cur, t.Poster, refund)
}
// CancelTask is called by the poster of an open task to withdraw it and
// refund the full escrowed budget. In-progress, completed or already
// cancelled tasks cannot be cancelled.
func CancelTask(cur realm, taskID int) {
caller := mustUserCall(cur)
t := mustGetTask(taskID)
if t.Poster != caller {
panic("only the task poster can cancel this task")
}
if t.Status != StatusOpen {
panic("only an open task can be cancelled")
}
if t.Settled {
panic("this task has already been settled")
}
t.Status = StatusCancelled
t.Settled = true
chain.Emit("TaskCancelled",
"task", strconv.Itoa(taskID),
"poster", caller.String(),
"refundedUgnot", strconv.FormatInt(t.BudgetUgnot, 10),
)
sendUgnot(cur, t.Poster, t.BudgetUgnot)
}
// ---------------------------------------------------------------------------
// Read-only helpers (safe to query with vm/qeval).
// AgentCount returns the number of registered agents.
func AgentCount() int { return agents.Size() }
// TaskCount returns the number of tasks ever posted (including settled).
func TaskCount() int { return tasks.Size() }
// Stats returns agents, open tasks, in-progress tasks, completed tasks
// and the ugnot still held in escrow.
func Stats() (int, int, int, int, int64) {
open, prog, done := 0, 0, 0
var escrow int64
tasks.Iterate("", "", func(_ string, v any) bool {
t := v.(*Task)
switch t.Status {
case StatusOpen:
open++
escrow += t.BudgetUgnot
case StatusInProgress:
prog++
escrow += t.BudgetUgnot
case StatusCompleted:
done++
}
return false
})
return agents.Size(), open, prog, done, escrow
}
// AgentSummary returns a one-line text summary, or "" if unknown.
func AgentSummary(owner address) string {
v := agents.Get(owner.String())
if v == nil {
return ""
}
a := v.(*Agent)
return a.Name + " | " + a.Tags + " | " + a.RateKind + " " + fmtUgnot(a.RateUgnot) + " | completed " + strconv.Itoa(a.Completed)
}
// TaskSummary returns a one-line text summary, or "" if unknown.
func TaskSummary(id int) string {
v := tasks.Get(padID(id))
if v == nil {
return ""
}
t := v.(*Task)
return t.Title + " | " + t.Status + " | " + t.Specialty + " | " + fmtUgnot(t.BudgetUgnot)
}
// ---------------------------------------------------------------------------
// internals
func mustUserCall(cur realm) address {
if !cur.IsCurrent() {
panic("spoofed realm")
}
prev := cur.Previous()
if !prev.IsUserCall() {
panic("only a direct user call is accepted")
}
return prev.Address()
}
func mustGetAgent(owner address) *Agent {
v := agents.Get(owner.String())
if v == nil {
panic("no agent is registered at this address")
}
return v.(*Agent)
}
func mustGetTask(id int) *Task {
v := tasks.Get(padID(id))
if v == nil {
panic("task " + strconv.Itoa(id) + " not found")
}
return v.(*Task)
}
func mustGetBid(taskID, bidID int) *Bid {
v := bids.Get(bidKey(taskID, bidID))
if v == nil {
panic("bid " + strconv.Itoa(bidID) + " not found on task " + strconv.Itoa(taskID))
}
return v.(*Bid)
}
func bidKey(taskID, bidID int) string {
return padID(taskID) + "/" + padID(bidID)
}
func taskBidCount(taskID int) int {
count := 0
prefix := padID(taskID) + "/"
bids.Iterate(prefix, prefix+"~", func(_ string, _ any) bool {
count++
return false
})
return count
}
func requireExactUgnotSend(budget int64) {
sent := unsafe.OriginSend()
if len(sent) != 1 || sent[0].Denom != "ugnot" || sent[0].Amount != budget {
got := "nothing"
if len(sent) != 0 {
got = sent.String()
}
panic("must send exactly " + strconv.FormatInt(budget, 10) + "ugnot with this call (got " + got + ")")
}
}
func sendUgnot(cur realm, to address, amount int64) {
if amount <= 0 {
return
}
bk := banker.NewBanker(banker.BankerTypeRealmSend, cur)
bk.SendCoins(cur.Address(), to, chain.Coins{chain.NewCoin("ugnot", amount)})
}
// padID makes IDs sort numerically as avl keys.
func padID(id int) string {
s := strconv.Itoa(id)
for len(s) < 9 {
s = "0" + s
}
return s
}
marketplace_test.gno
package agentmarketplace
import (
"chain"
"chain/banker"
"strings"
"testing"
"gno.land/p/nt/avl/v0"
"gno.land/p/nt/testutils/v0"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
const pkgPath = "gno.land/r/g1pzn6rn8q0pfmq4xje4j8086ncnldavyz8skgp3/agentmarketplace"
var (
alice = testutils.TestAddress("alice")
bob = testutils.TestAddress("bob")
carol = testutils.TestAddress("carol")
dave = testutils.TestAddress("dave")
eve = testutils.TestAddress("eve")
frank = testutils.TestAddress("frank")
)
func reset() {
nextTaskID = 1
nextBidID = 1
nextRatingID = 1
agents = avl.NewTree()
tasks = avl.NewTree()
bids = avl.NewTree()
bidByAgent = avl.NewTree()
ratings = avl.NewTree()
ratingsByAgent = avl.NewTree()
ratingByTask = avl.NewTree()
scores = avl.NewTree()
scoreboard = avl.NewTree()
posterStats = avl.NewTree()
posterAgents = avl.NewTree()
}
func fundRealm(amount int64) {
testing.IssueCoins(chain.PackageAddress(pkgPath), chain.Coins{{Denom: "ugnot", Amount: amount}})
}
// testing.SetRealm attaches to the first non-testing call frame. These
// helpers are crossing functions so that SetRealm and the exported call
// share a frame; a non-crossing wrapper would drop the override when it
// returns.
func register(cur realm, owner address, name, tags, kind string, rate int64) {
testing.SetRealm(testing.NewUserRealm(owner))
testing.SetOriginCaller(owner)
RegisterAgent(cross(cur), name, tags, kind, rate)
}
func update(cur realm, owner address, name, tags, kind string, rate int64) {
testing.SetRealm(testing.NewUserRealm(owner))
testing.SetOriginCaller(owner)
UpdateAgent(cross(cur), name, tags, kind, rate)
}
func post(cur realm, poster address, title, desc, spec string, budget int64) int {
testing.SetRealm(testing.NewUserRealm(poster))
testing.SetOriginCaller(poster)
testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: budget}})
fundRealm(budget)
return PostTask(cross(cur), title, desc, spec, budget)
}
func postWithSend(cur realm, poster address, title, desc, spec string, budget int64, send chain.Coins) int {
testing.SetRealm(testing.NewUserRealm(poster))
testing.SetOriginCaller(poster)
testing.SetOriginSend(send)
return PostTask(cross(cur), title, desc, spec, budget)
}
func bid(cur realm, agent address, taskID int, amount int64, note string) int {
testing.SetRealm(testing.NewUserRealm(agent))
testing.SetOriginCaller(agent)
return PlaceBid(cross(cur), taskID, amount, note)
}
func accept(cur realm, poster address, taskID, bidID int) {
testing.SetRealm(testing.NewUserRealm(poster))
testing.SetOriginCaller(poster)
AcceptBid(cross(cur), taskID, bidID)
}
func complete(cur realm, agent address, taskID int) {
testing.SetRealm(testing.NewUserRealm(agent))
testing.SetOriginCaller(agent)
CompleteTask(cross(cur), taskID)
}
func cancel(cur realm, poster address, taskID int) {
testing.SetRealm(testing.NewUserRealm(poster))
testing.SetOriginCaller(poster)
CancelTask(cross(cur), taskID)
}
func rate(cur realm, poster address, taskID, score int, comment string) int {
testing.SetRealm(testing.NewUserRealm(poster))
testing.SetOriginCaller(poster)
return Rate(cross(cur), taskID, score, comment)
}
func refreshScore(cur realm, caller, agent address) {
testing.SetRealm(testing.NewUserRealm(caller))
testing.SetOriginCaller(caller)
RefreshScore(cross(cur), agent)
}
func postHash(cur realm, poster address, title, desc, spec string, budget int64, hash string, deadlineSecs int64) int {
testing.SetRealm(testing.NewUserRealm(poster))
testing.SetOriginCaller(poster)
testing.SetOriginSend(chain.Coins{{Denom: "ugnot", Amount: budget}})
fundRealm(budget)
return PostHashTask(cross(cur), title, desc, spec, budget, hash, deadlineSecs)
}
func reveal(cur realm, agent address, taskID int, preimage string) {
testing.SetRealm(testing.NewUserRealm(agent))
testing.SetOriginCaller(agent)
RevealAndComplete(cross(cur), taskID, preimage)
}
func timeoutHash(cur realm, caller address, taskID int) {
testing.SetRealm(testing.NewUserRealm(caller))
testing.SetOriginCaller(caller)
TimeoutHashTask(cross(cur), taskID)
}
// settleJob posts a task, accepts a full-budget bid, and settles it.
func settleJob(cur realm, poster, agent address, title, desc, spec string, budget int64) int {
id := post(cur, poster, title, desc, spec, budget)
bidID := bid(cur, agent, id, budget, "ready")
accept(cur, poster, id, bidID)
complete(cur, agent, id)
return id
}
func TestRegisterAgent(cur realm, t *testing.T) {
reset()
register(cur, alice, "Research Bot", "research, writing", RateHourly, 500000)
uassert.Equal(t, 1, AgentCount())
a := mustGetAgent(alice)
uassert.Equal(t, alice, a.Owner)
uassert.Equal(t, "Research Bot", a.Name)
uassert.Equal(t, "research, writing", a.Tags, "tags are lowercased, unique and sorted")
uassert.Equal(t, RateHourly, a.RateKind)
uassert.Equal(t, int64(500000), a.RateUgnot)
uassert.Equal(t, 0, a.Completed)
register(cur, bob, "Code Agent", "Code, review, code", RateFlat, 2000000)
uassert.Equal(t, 2, AgentCount())
uassert.Equal(t, "code, review", mustGetAgent(bob).Tags)
}
func TestRegisterValidation(cur realm, t *testing.T) {
reset()
cases := []struct {
name, tags, kind string
rate int64
want string
}{
{"ab", "code", RateFlat, 1, "name must be 3-48 characters"},
{" lead", "code", RateFlat, 1, "name must not start or end with a space"},
{"bad|pipe", "code", RateFlat, 1, "name contains an unsupported character: only letters, digits, spaces and - . , ( ) ' / + : @ # % & = are allowed"},
{"Bot", "x", RateFlat, 1, "tags must be 2-200 characters"},
{"Bot", "code", "weekly", 1, "rate kind must be one of: hourly, flat"},
{"Bot", "code", RateFlat, 0, "rate must be between 1 and 1000000000000 ugnot"},
}
for _, c := range cases {
urequire.AbortsWithMessage(t, cur, c.want, func() {
register(cur, alice, c.name, c.tags, c.kind, c.rate)
})
}
uassert.Equal(t, 0, AgentCount(), "no invalid agent was stored")
}
func TestRegisterOnce(cur realm, t *testing.T) {
reset()
register(cur, alice, "Research Bot", "research", RateHourly, 1)
urequire.AbortsWithMessage(t, cur, "this address is already registered as an agent", func() {
register(cur, alice, "Other Name", "writing", RateFlat, 2)
})
}
func TestUpdateAgentAccess(cur realm, t *testing.T) {
reset()
register(cur, alice, "Research Bot", "research", RateHourly, 500000)
update(cur, alice, "Alice Research", "research, writing", RateFlat, 750000)
a := mustGetAgent(alice)
uassert.Equal(t, "Alice Research", a.Name)
uassert.Equal(t, "research, writing", a.Tags)
uassert.Equal(t, RateFlat, a.RateKind)
uassert.Equal(t, int64(750000), a.RateUgnot)
urequire.AbortsWithMessage(t, cur, "no agent is registered at this address", func() {
update(cur, bob, "Stolen", "code", RateFlat, 1)
})
}
func TestPostTaskEscrow(cur realm, t *testing.T) {
reset()
id := post(cur, alice, "Summarize a paper", "Write a one-page summary of the attached paper.", "Research", 2000000)
uassert.Equal(t, 1, id)
uassert.Equal(t, 1, TaskCount())
tk := mustGetTask(id)
uassert.Equal(t, alice, tk.Poster)
uassert.Equal(t, StatusOpen, tk.Status)
uassert.Equal(t, "research", tk.Specialty)
uassert.Equal(t, int64(2000000), tk.BudgetUgnot)
uassert.False(t, tk.Settled)
_, open, _, _, escrow := Stats()
uassert.Equal(t, 1, open)
uassert.Equal(t, int64(2000000), escrow)
}
func TestPostTaskSendValidation(cur realm, t *testing.T) {
reset()
title, desc := "Summarize a paper", "Write a one-page summary of the attached paper."
urequire.AbortsWithMessage(t, cur, "must send exactly 2000000ugnot with this call (got nothing)", func() {
postWithSend(cur, alice, title, desc, "research", 2000000, nil)
})
urequire.AbortsWithMessage(t, cur, "must send exactly 2000000ugnot with this call (got 1999999ugnot)", func() {
postWithSend(cur, alice, title, desc, "research", 2000000, chain.Coins{{Denom: "ugnot", Amount: 1999999}})
})
urequire.AbortsWithMessage(t, cur, "must send exactly 2000000ugnot with this call (got 2000000uatom)", func() {
postWithSend(cur, alice, title, desc, "research", 2000000, chain.Coins{{Denom: "uatom", Amount: 2000000}})
})
uassert.Equal(t, 0, TaskCount())
}
func TestPlaceBidRules(cur realm, t *testing.T) {
reset()
id := post(cur, alice, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", 3000000)
urequire.AbortsWithMessage(t, cur, "no agent is registered at this address", func() {
bid(cur, bob, id, 2000000, "I can do this")
})
register(cur, bob, "Code Agent", "code, review", RateFlat, 1000000)
urequire.AbortsWithMessage(t, cur, "this agent does not list the required specialty: research", func() {
bid(cur, bob, id, 2000000, "I can do this")
})
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
register(cur, alice, "Alice Also", "research", RateHourly, 1)
urequire.AbortsWithMessage(t, cur, "the task poster cannot bid on their own task", func() {
bid(cur, alice, id, 1000000, "self bid")
})
bidID := bid(cur, carol, id, 2500000, "I will deliver tomorrow")
uassert.Equal(t, 1, bidID)
uassert.Equal(t, int64(2500000), mustGetBid(id, bidID).Amount)
same := bid(cur, carol, id, 2000000, "Lower offer")
uassert.Equal(t, bidID, same)
uassert.Equal(t, int64(2000000), mustGetBid(id, bidID).Amount)
uassert.Equal(t, "Lower offer", mustGetBid(id, bidID).Note)
urequire.AbortsWithMessage(t, cur, "bid amount must be between 1 and the task budget of 3000000 ugnot", func() {
bid(cur, carol, id, 3000001, "too high")
})
urequire.AbortsWithMessage(t, cur, "task 99 not found", func() {
bid(cur, carol, 99, 1, "")
})
}
func TestAcceptBidAccess(cur realm, t *testing.T) {
reset()
id := post(cur, alice, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", 3000000)
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
bidID := bid(cur, carol, id, 2000000, "ready")
urequire.AbortsWithMessage(t, cur, "only the task poster can accept a bid", func() {
accept(cur, carol, id, bidID)
})
urequire.AbortsWithMessage(t, cur, "only the task poster can accept a bid", func() {
accept(cur, bob, id, bidID)
})
urequire.AbortsWithMessage(t, cur, "bid 99 not found on task 1", func() {
accept(cur, alice, id, 99)
})
accept(cur, alice, id, bidID)
tk := mustGetTask(id)
uassert.Equal(t, StatusInProgress, tk.Status)
uassert.Equal(t, carol, tk.Winner)
uassert.Equal(t, bidID, tk.WinningBidID)
urequire.AbortsWithMessage(t, cur, "only an open task can accept a bid", func() {
accept(cur, alice, id, bidID)
})
register(cur, bob, "Other Research", "research", RateHourly, 1)
urequire.AbortsWithMessage(t, cur, "bids are only accepted on open tasks", func() {
bid(cur, bob, id, 1000000, "late")
})
}
func TestCompleteAndSettle(cur realm, t *testing.T) {
reset()
budget := int64(3000000)
pay := int64(2000000)
id := post(cur, alice, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", budget)
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
bidID := bid(cur, carol, id, pay, "ready")
accept(cur, alice, id, bidID)
urequire.AbortsWithMessage(t, cur, "only the winning agent can mark this task complete", func() {
complete(cur, alice, id)
})
urequire.AbortsWithMessage(t, cur, "only the winning agent can mark this task complete", func() {
complete(cur, bob, id)
})
pkg := chain.PackageAddress(pkgPath)
rb := banker.NewReadonlyBanker()
beforeRealm := rb.GetCoin(pkg, "ugnot")
uassert.Equal(t, budget, beforeRealm, "realm still holds the escrow")
complete(cur, carol, id)
tk := mustGetTask(id)
uassert.Equal(t, StatusCompleted, tk.Status)
uassert.True(t, tk.Settled)
uassert.Equal(t, 1, mustGetAgent(carol).Completed)
uassert.Equal(t, pay, mustGetAgent(carol).EarnedUgnot)
uassert.Equal(t, pay, rb.GetCoin(carol, "ugnot"))
uassert.Equal(t, budget-pay, rb.GetCoin(alice, "ugnot"), "leftover budget refunded to poster")
uassert.Equal(t, int64(0), rb.GetCoin(pkg, "ugnot"), "realm escrow drained")
_, open, prog, done, escrow := Stats()
uassert.Equal(t, 0, open)
uassert.Equal(t, 0, prog)
uassert.Equal(t, 1, done)
uassert.Equal(t, int64(0), escrow)
urequire.AbortsWithMessage(t, cur, "only an in-progress task can be completed", func() {
complete(cur, carol, id)
})
}
func TestCancelRefund(cur realm, t *testing.T) {
reset()
budget := int64(4000000)
id := post(cur, alice, "Review a realm", "Look over an escrow realm for footguns please.", "review", budget)
register(cur, bob, "Code Agent", "code, review", RateFlat, 1000000)
bid(cur, bob, id, 3500000, "I can review this")
urequire.AbortsWithMessage(t, cur, "only the task poster can cancel this task", func() {
cancel(cur, bob, id)
})
cancel(cur, alice, id)
tk := mustGetTask(id)
uassert.Equal(t, StatusCancelled, tk.Status)
uassert.True(t, tk.Settled)
rb := banker.NewReadonlyBanker()
uassert.Equal(t, budget, rb.GetCoin(alice, "ugnot"))
uassert.Equal(t, int64(0), rb.GetCoin(chain.PackageAddress(pkgPath), "ugnot"))
urequire.AbortsWithMessage(t, cur, "only an open task can be cancelled", func() {
cancel(cur, alice, id)
})
urequire.AbortsWithMessage(t, cur, "bids are only accepted on open tasks", func() {
bid(cur, bob, id, 1, "too late")
})
}
func TestCannotCancelAfterAccept(cur realm, t *testing.T) {
reset()
id := post(cur, alice, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", 2000000)
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
bidID := bid(cur, carol, id, 1500000, "ok")
accept(cur, alice, id, bidID)
urequire.AbortsWithMessage(t, cur, "only an open task can be cancelled", func() {
cancel(cur, alice, id)
})
uassert.Equal(t, StatusInProgress, mustGetTask(id).Status)
uassert.False(t, mustGetTask(id).Settled)
}
func TestCompleteOpenTaskRejected(cur realm, t *testing.T) {
reset()
id := post(cur, alice, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", 2000000)
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
urequire.AbortsWithMessage(t, cur, "only an in-progress task can be completed", func() {
complete(cur, carol, id)
})
}
func TestHappyPathSummaries(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
id := post(cur, alice, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", 2000000)
bidID := bid(cur, carol, id, 2000000, "full budget")
accept(cur, alice, id, bidID)
complete(cur, carol, id)
uassert.True(t, strings.Contains(AgentSummary(carol), "Research Bot"))
uassert.True(t, strings.Contains(AgentSummary(carol), "completed 1"))
uassert.True(t, strings.Contains(TaskSummary(id), StatusCompleted))
uassert.Equal(t, "", AgentSummary(bob))
uassert.Equal(t, "", TaskSummary(99))
}
render.gno
package agentmarketplace
import (
"sort"
"strconv"
"strings"
"time"
"gno.land/p/moul/txlink/v0"
)
const pageSize = 10
// Render serves the gnoweb dashboard.
//
// "" summary, leaderboard, agents, open tasks, action forms
// "agents?page=N" every agent, paginated
// "agent/<g1addr>" one agent, score, history, bids
// "tasks?page=N" every task, paginated
// "task/<id>" one task, its bids and action buttons
// "leaderboard?page=N" ranked trust scores
// "about" flow, score math, and limitations
func Render(path string) string {
route, query := path, ""
if i := strings.Index(path, "?"); i >= 0 {
route, query = path[:i], path[i+1:]
}
switch {
case route == "":
return renderHome()
case route == "agents":
return renderAgents(pageParam(query))
case strings.HasPrefix(route, "agent/"):
return renderAgent(strings.TrimPrefix(route, "agent/"))
case route == "tasks":
return renderTasks(pageParam(query))
case strings.HasPrefix(route, "task/"):
id, err := strconv.Atoi(strings.TrimPrefix(route, "task/"))
if err != nil {
return notFound()
}
return renderTask(id)
case route == "leaderboard":
return renderLeaderboard(pageParam(query))
case route == "about":
return renderAbout()
}
return notFound()
}
func renderHome() string {
var b strings.Builder
b.WriteString("# <gno-icon name=\"users\" /> Agent Marketplace\n\n")
b.WriteString("*Hire an on-chain agent, hold the budget in escrow, and rate the work once it settles.* Agents register with specialties and a rate, posters lock ugnot against a task, agents bid, the poster accepts one bid, and the winning agent settles to release payment. After payout, the poster leaves a 1-5 rating.\n\n")
b.WriteString(navBar())
b.WriteString(disclaimer())
nAgents, open, prog, done, escrow := Stats()
b.WriteString("## Board\n\n")
b.WriteString("<gno-columns>\n")
b.WriteString(statCard("users", "Agents", strconv.Itoa(nAgents), "registered workers"))
b.WriteString("<gno-columns-sep>\n")
b.WriteString(statCard("list", "Open tasks", strconv.Itoa(open), strconv.Itoa(prog)+" in progress"))
b.WriteString("<gno-columns-sep>\n")
b.WriteString(statCard("check", "Completed", strconv.Itoa(done), strconv.Itoa(RatingCount())+" ratings"))
b.WriteString("<gno-columns-sep>\n")
b.WriteString(statCard("coins", "In escrow", fmtUgnot(escrow), "held by the realm"))
b.WriteString("</gno-columns>\n\n")
b.WriteString("## Leaderboard\n\n")
b.WriteString(leaderboardTable(0, 5))
if ratedAgentCount() > 5 {
b.WriteString("[Full leaderboard](" + link("leaderboard") + ")\n\n")
} else if ratedAgentCount() > 0 {
b.WriteString("[Leaderboard](" + link("leaderboard") + ")\n\n")
}
b.WriteString("## Agents\n\n")
if agents.Size() == 0 {
b.WriteString("No agents yet. Register one below.\n\n")
} else {
b.WriteString(agentsTable(0, 6))
if agents.Size() > 6 {
b.WriteString("[See all " + strconv.Itoa(agents.Size()) + " agents](" + link("agents") + ")\n\n")
}
}
b.WriteString("## Open tasks\n\n")
b.WriteString(openTasksTable(8))
b.WriteString("[All tasks](" + link("tasks") + ")\n\n")
b.WriteString(registerForm())
b.WriteString(postTaskForm())
return b.String()
}
func renderAgents(page int) string {
var b strings.Builder
b.WriteString("# Agents\n\n")
b.WriteString(navBar())
total := agents.Size()
if total == 0 {
b.WriteString("No agents yet.\n")
return b.String()
}
b.WriteString(agentsTable((page-1)*pageSize, pageSize))
b.WriteString(pager("agents", page, total))
return b.String()
}
func renderAgent(addr string) string {
if !address(addr).IsValid() {
return notFound()
}
owner := address(addr)
v := agents.Get(owner.String())
if v == nil {
return notFound()
}
a := v.(*Agent)
s := liveScore(owner, time.Now())
var b strings.Builder
b.WriteString("# <gno-icon name=\"user\" /> " + a.Name + "\n\n")
b.WriteString(navBar())
b.WriteString("<gno-columns>\n<gno-frame>\n")
b.WriteString("### Profile\n\n")
b.WriteString("- Owner: `" + a.Owner.String() + "`\n")
b.WriteString("- Specialties: **" + a.Tags + "**\n")
b.WriteString("- Rate: **" + fmtUgnot(a.RateUgnot) + "** (" + a.RateKind + ")\n")
b.WriteString("- Registered: " + a.RegisteredAt.UTC().Format("Jan 2, 2006") + "\n\n")
b.WriteString("</gno-frame>\n<gno-columns-sep>\n<gno-frame>\n")
b.WriteString("### Reputation\n\n")
if s.RatedCount == 0 {
b.WriteString("- Trust score: unrated\n")
} else {
b.WriteString("- Trust score: **" + fmtScore(s.TrustMilli) + " / 5** (" + scoreKind(s) + ")\n")
b.WriteString("- Rated jobs: " + strconv.Itoa(s.RatedCount) + "\n")
b.WriteString("- Raw average: " + fmtScore(s.RawMilli) + " / 5\n")
}
b.WriteString("- Completed jobs: " + strconv.Itoa(a.Completed) + "\n")
b.WriteString("- Earned: **" + fmtUgnot(a.EarnedUgnot) + "**\n\n")
b.WriteString("</gno-frame>\n</gno-columns>\n\n")
b.WriteString("## Rating history\n\n")
b.WriteString(ratingsByAgentTable(owner))
b.WriteString("## Update profile\n\n")
b.WriteString("Only this agent's owner can sign this. The button opens a prefilled transaction form.\n\n")
b.WriteString("<gno-button href=\"" + txlink.NewLink("UpdateAgent").AddArgs(
"name", a.Name,
"tags", a.Tags,
"rateKind", a.RateKind,
"rateUgnot", strconv.FormatInt(a.RateUgnot, 10),
).URL() + "\" label=\"Update agent\" variant=\"outline\" />\n\n")
b.WriteString("## Bids\n\n")
b.WriteString(bidsByAgentTable(owner))
return b.String()
}
func renderTasks(page int) string {
var b strings.Builder
b.WriteString("# Tasks\n\n")
b.WriteString(navBar())
total := tasks.Size()
if total == 0 {
b.WriteString("No tasks yet.\n")
return b.String()
}
b.WriteString("| # | Title | Specialty | Budget | Status | Poster |\n")
b.WriteString("|---|---|---|---|---|---|\n")
tasks.ReverseIterateByOffset((page-1)*pageSize, pageSize, func(_ string, v any) bool {
t := v.(*Task)
b.WriteString(taskRow(t))
return false
})
b.WriteString("\n" + pager("tasks", page, total))
return b.String()
}
func renderTask(id int) string {
v := tasks.Get(padID(id))
if v == nil {
return notFound()
}
t := v.(*Task)
var b strings.Builder
b.WriteString("# " + t.Title + "\n\n")
b.WriteString(navBar())
b.WriteString("<gno-columns>\n<gno-frame>\n")
b.WriteString("### Task\n\n")
b.WriteString("- Status: **" + statusLabel(t.Status) + "**\n")
b.WriteString("- Specialty: **" + t.Specialty + "**\n")
b.WriteString("- Budget (escrowed): **" + fmtUgnot(t.BudgetUgnot) + "**\n")
b.WriteString("- Posted: " + t.PostedAt.UTC().Format("Jan 2, 2006") + "\n")
b.WriteString("- Poster: " + posterLink(t.Poster) + "\n")
if t.CommitHash != "" {
b.WriteString("- Settlement: hash-commit `" + t.CommitHash + "`\n")
if !t.RevealBy.IsZero() {
b.WriteString("- Reveal by: " + t.RevealBy.UTC().Format("Jan 2, 2006 15:04 UTC") + "\n")
}
}
b.WriteString("\n")
b.WriteString("</gno-frame>\n<gno-columns-sep>\n<gno-frame>\n")
b.WriteString("### Description\n\n")
b.WriteString(t.Description + "\n\n")
if t.Status == StatusInProgress || t.Status == StatusCompleted {
b.WriteString("Winning agent: [" + agentName(t.Winner) + "](" + link("agent/"+t.Winner.String()) + ") · bid #" + strconv.Itoa(t.WinningBidID) + "\n\n")
}
if t.Settled {
b.WriteString("Escrow has been released.\n\n")
}
b.WriteString("</gno-frame>\n</gno-columns>\n\n")
b.WriteString("## Actions\n\n")
b.WriteString("Each button opens a prefilled transaction form. The chain enforces who may sign it.\n\n")
sid := strconv.Itoa(t.ID)
if t.Status == StatusOpen {
b.WriteString("<gno-button href=\"" + txlink.NewLink("PlaceBid").AddArgs(
"taskID", sid,
"amountUgnot", strconv.FormatInt(t.BudgetUgnot, 10),
"note", "",
).URL() + "\" label=\"Place a bid\" variant=\"info\" />\n")
b.WriteString("<gno-button href=\"" + txlink.NewLink("CancelTask").AddArgs("taskID", sid).URL() + "\" label=\"Cancel and refund\" variant=\"outline\" />\n\n")
}
if t.Status == StatusInProgress {
if t.CommitHash != "" {
b.WriteString("<gno-button href=\"" + txlink.NewLink("RevealAndComplete").AddArgs(
"taskID", sid,
"preimage", "",
).URL() + "\" label=\"Reveal and settle\" variant=\"success\" />\n")
b.WriteString("<gno-button href=\"" + txlink.NewLink("TimeoutHashTask").AddArgs("taskID", sid).URL() + "\" label=\"Timeout and refund\" variant=\"outline\" />\n\n")
} else {
b.WriteString("<gno-button href=\"" + txlink.NewLink("CompleteTask").AddArgs("taskID", sid).URL() + "\" label=\"Complete and settle\" variant=\"success\" />\n\n")
}
}
if t.Status == StatusCompleted && t.Settled {
if ratingByTask.Get(padID(t.ID)) == nil {
b.WriteString("Only the poster can rate, and only once, after escrow has paid out.\n\n")
b.WriteString(rateForm(t.ID))
} else {
b.WriteString(renderTaskRating(t.ID))
}
}
b.WriteString("## Bids\n\n")
b.WriteString(taskBidsTable(t))
return b.String()
}
func renderLeaderboard(page int) string {
var b strings.Builder
b.WriteString("# Leaderboard\n\n")
b.WriteString(navBar())
b.WriteString("Scores are computed live: budget-weighted, 45-day half-life, 20% cap per poster, provisional until 3 rated jobs.\n\n")
total := ratedAgentCount()
if total == 0 {
b.WriteString("No ratings yet. Settle a job and rate the winning agent.\n")
return b.String()
}
b.WriteString(leaderboardTable((page-1)*pageSize, pageSize))
b.WriteString(pager("leaderboard", page, total))
return b.String()
}
func renderAbout() string {
var b strings.Builder
b.WriteString("# About this marketplace\n\n")
b.WriteString(navBar())
b.WriteString(disclaimer())
b.WriteString("## Flow\n\n")
b.WriteString("1. An agent registers a name, specialty tags and an hourly or flat rate. The signing address is the agent id.\n")
b.WriteString("2. A poster publishes a task with a title, description, required specialty and a budget, and **sends exactly that many ugnot** with the call. The realm holds the coins.\n")
b.WriteString("3. Registered agents who list the required specialty bid an amount (at most the budget) and an optional note.\n")
b.WriteString("4. Only the poster can accept one bid. The task becomes in-progress.\n")
b.WriteString("5. Only the winning agent can mark the task complete (`CompleteTask`, or `RevealAndComplete` on a hash-commit task). The realm then pays the bid amount to the agent and refunds any leftover budget to the poster.\n")
b.WriteString("6. After escrow has paid out, only the poster can `Rate` the winning agent, once, with a score from 1 to 5. You cannot rate your own agent.\n")
b.WriteString("7. The poster can cancel an **open** task and get a full refund. Once a bid is accepted, cancel is refused. A hash-commit task that misses its reveal deadline can be refunded with `TimeoutHashTask`.\n\n")
b.WriteString("## How the trust score is computed\n\n")
b.WriteString("Each rating is weighted as `budget × reviewerWeight × 0.5^(age / 45 days)`, using block time for the age. Reviewer weight starts at 1.0 and grows with the number of distinct agents the poster has paid and the GNOT they have settled, capped at 3.0. The agent's trust score is the weighted average of those ratings, shown in milli-stars (1000–5000).\n\n")
b.WriteString("- A score stays **provisional** until the agent has 3 rated jobs, then it is labeled **trusted**.\n")
b.WriteString("- No single poster may contribute more than **20%** of an agent's pre-cap score weight, or **1/N** when fewer than 5 posters have rated that agent (otherwise a hard 20% cap would flatten two honest reviewers to the same ceiling). A sole poster is left uncapped. The cap is measured against the original weight mass, so a 1 ugnot rating cannot rewrite the scale of a well-earned score.\n")
b.WriteString("- `ScoreOf` and this dashboard recompute decay live. `RefreshScore` rewrites the cached scoreboard and emits `ScoreUpdated`.\n\n")
b.WriteString("## Hash-commit settlement (optional)\n\n")
b.WriteString("`PostHashTask` works like `PostTask`, but the poster also sets a SHA-256 commit hash (lowercase hex) of an expected result and a reveal deadline. The winning agent must call `RevealAndComplete` with the preimage before the deadline; a match releases escrow the same way `CompleteTask` does. After the deadline, anyone may call `TimeoutHashTask` to refund the poster. This only fits jobs where the poster already knows the answer.\n\n")
b.WriteString("## What this is not\n\n")
b.WriteString("- Gno has no identity layer. Two funded wallets can still trade escrow and five-star each other; budget weighting, the 20% cap, decay and the provisional label make cheap sock-puppet jobs weak, not impossible.\n")
b.WriteString("- No dispute resolution on an ordinary task: settlement is a single call by the winning agent, with no attester that the work was done.\n")
b.WriteString("- No hardware or identity attestation; anyone with a key can register as an \"agent\".\n")
b.WriteString("- Local / testnet only. Do not lock real value here.\n")
return b.String()
}
func navBar() string {
return "[Home](" + link("") + ") · [Agents](" + link("agents") + ") · [Tasks](" + link("tasks") + ") · [Leaderboard](" + link("leaderboard") + ") · [About](" + link("about") + ")\n\n"
}
func disclaimer() string {
return "<gno-alert type=\"warning\" role=\"status\">\n" +
"**Starter realm, testnet only.** Reputation is a public, budget-weighted score with a 45-day half-life and a 20% cap per poster, but Gno has no identity layer: two funded wallets can still trade and five-star each other. There is no dispute process and no attestation that an agent (or the work) is real. Escrow is real ugnot on the chain you are looking at, so only use funds you can afford to lose on a demo.\n" +
"</gno-alert>\n\n"
}
func statCard(icon, title, value, sub string) string {
return "<gno-frame>\n### <gno-icon name=\"" + icon + "\" /> " + title + "\n\n**" + value + "**\n\n" + sub + "\n\n</gno-frame>\n"
}
func registerForm() string {
return "## Register as an agent\n\n" +
"The address that signs the transaction becomes the agent id.\n\n" +
"<gno-frame>\n" +
"<gno-form exec=\"RegisterAgent\">\n" +
"<gno-input name=\"name\" placeholder=\"Display name, e.g. Research Bot\" />\n" +
"<gno-input name=\"tags\" placeholder=\"Specialties, e.g. research, writing, code\" />\n" +
"<gno-input name=\"rateKind\" type=\"radio\" value=\"hourly\" placeholder=\"Hourly\" checked=\"true\" />\n" +
"<gno-input name=\"rateKind\" type=\"radio\" value=\"flat\" placeholder=\"Flat\" />\n" +
"<gno-input name=\"rateUgnot\" type=\"number\" placeholder=\"Rate in ugnot, e.g. 500000 (0.5 GNOT)\" />\n" +
"</gno-form>\n" +
"</gno-frame>\n\n"
}
func postTaskForm() string {
return "## Post a task\n\n" +
"The transaction **must send exactly the budget in ugnot**. The realm holds it until complete or cancel. Use the sample button for a 2 GNOT research task, or the form plus a matching `-send`.\n\n" +
"<gno-button href=\"" + txlink.NewLink("PostTask").AddArgs(
"title", "Summarize a paper",
"description", "Write a one-page summary of a research paper I will provide.",
"specialty", "research",
"budgetUgnot", "2000000",
).SetSend("2000000ugnot").URL() + "\" label=\"Post a 2 GNOT research task\" variant=\"success\" />\n\n" +
"<gno-frame>\n" +
"<gno-form exec=\"PostTask\">\n" +
"<gno-input name=\"title\" placeholder=\"Title\" />\n" +
"<gno-input name=\"description\" placeholder=\"Description\" />\n" +
"<gno-input name=\"specialty\" placeholder=\"Required specialty, e.g. research\" />\n" +
"<gno-input name=\"budgetUgnot\" type=\"number\" placeholder=\"Budget in ugnot, e.g. 2000000\" />\n" +
"</gno-form>\n" +
"</gno-frame>\n\n"
}
func rateForm(taskID int) string {
sid := strconv.Itoa(taskID)
return "<gno-button href=\"" + txlink.NewLink("Rate").AddArgs(
"taskID", sid,
"score", "5",
"comment", "Great work",
).URL() + "\" label=\"Rate 5 stars\" variant=\"success\" />\n\n" +
"<gno-frame>\n" +
"<gno-form exec=\"Rate\">\n" +
"<gno-input name=\"taskID\" type=\"number\" value=\"" + sid + "\" placeholder=\"Task ID\" />\n" +
"<gno-input name=\"score\" type=\"number\" placeholder=\"Score, 1 to 5\" />\n" +
"<gno-input name=\"comment\" placeholder=\"Optional short comment\" />\n" +
"</gno-form>\n" +
"</gno-frame>\n\n"
}
func renderTaskRating(taskID int) string {
v := ratingByTask.Get(padID(taskID))
if v == nil {
return ""
}
rv := ratings.Get(padID(v.(int)))
if rv == nil {
return ""
}
r := rv.(*Rating)
comment := "—"
if r.Comment != "" {
comment = r.Comment
}
return "### Rating\n\n" +
"- Score: **" + strconv.Itoa(r.Score) + " / 5**\n" +
"- Comment: " + comment + "\n" +
"- Budget weight: " + fmtUgnot(r.BudgetUgnot) + "\n" +
"- Rated: " + r.RatedAt.UTC().Format("Jan 2, 2006") + "\n\n"
}
func agentsTable(offset, limit int) string {
if agents.Size() == 0 {
return "No agents yet.\n\n"
}
var b strings.Builder
b.WriteString("| Agent | Specialties | Rate | Score | Completed | Earned |\n")
b.WriteString("|---|---|---|---|---|---|\n")
now := time.Now()
agents.IterateByOffset(offset, limit, func(_ string, v any) bool {
a := v.(*Agent)
score := "—"
s := liveScore(a.Owner, now)
if s.RatedCount > 0 {
score = fmtScore(s.TrustMilli) + " " + scoreKind(s)
}
b.WriteString("| [" + a.Name + "](" + link("agent/"+a.Owner.String()) + ") | " +
a.Tags + " | " + fmtUgnot(a.RateUgnot) + " / " + a.RateKind + " | " +
score + " | " + strconv.Itoa(a.Completed) + " | " + fmtUgnot(a.EarnedUgnot) + " |\n")
return false
})
b.WriteString("\n")
return b.String()
}
func leaderboardTable(offset, limit int) string {
now := time.Now()
var keys []string
agents.Iterate("", "", func(_ string, v any) bool {
a := v.(*Agent)
s := liveScore(a.Owner, now)
if s.RatedCount == 0 {
return false
}
keys = append(keys, scoreKey(s.TrustMilli, s.RatedCount, a.Owner)+"\t"+a.Owner.String())
return false
})
sort.Strings(keys)
total := len(keys)
if total == 0 {
return "No ratings yet. Settle a job and rate the winning agent.\n\n"
}
if offset < 0 {
offset = 0
}
var b strings.Builder
b.WriteString("| Rank | Agent | Trust | Status | Jobs | Raw avg |\n")
b.WriteString("|---|---|---|---|---|---|\n")
end := offset + limit
if end > total {
end = total
}
rank := offset + 1
for i := offset; i < end; i++ {
parts := strings.Split(keys[i], "\t")
owner := address(parts[len(parts)-1])
s := liveScore(owner, now)
b.WriteString("| " + strconv.Itoa(rank) + " | [" + agentName(owner) + "](" + link("agent/"+owner.String()) + ") | **" +
fmtScore(s.TrustMilli) + "** | " + scoreKind(s) + " | " +
strconv.Itoa(s.RatedCount) + " | " + fmtScore(s.RawMilli) + " |\n")
rank++
}
b.WriteString("\n")
return b.String()
}
func ratedAgentCount() int {
n := 0
agents.Iterate("", "", func(_ string, v any) bool {
a := v.(*Agent)
if liveScore(a.Owner, time.Now()).RatedCount > 0 {
n++
}
return false
})
return n
}
func scoreKind(s *AgentScore) string {
if s.Provisional {
return "provisional"
}
return "trusted"
}
func ratingsByAgentTable(owner address) string {
prefix := owner.String() + "/"
var rows strings.Builder
n := 0
ratingsByAgent.ReverseIterate(prefix, prefix+"~", func(_ string, v any) bool {
r := v.(*Rating)
title := "task #" + strconv.Itoa(r.TaskID)
if tv := tasks.Get(padID(r.TaskID)); tv != nil {
t := tv.(*Task)
title = "[" + t.Title + "](" + link("task/"+strconv.Itoa(t.ID)) + ")"
}
comment := "—"
if r.Comment != "" {
comment = r.Comment
}
rows.WriteString("| " + title + " | " + strconv.Itoa(r.Score) + " / 5 | " +
fmtUgnot(r.BudgetUgnot) + " | " + comment + " | " +
r.RatedAt.UTC().Format("Jan 2, 2006") + " |\n")
n++
return false
})
if n == 0 {
return "No ratings yet.\n\n"
}
return "| Task | Score | Budget | Comment | Date |\n|---|---|---|---|---|\n" + rows.String() + "\n"
}
func openTasksTable(limit int) string {
var b strings.Builder
count := 0
var rows strings.Builder
tasks.ReverseIterate("", "", func(_ string, v any) bool {
t := v.(*Task)
if t.Status != StatusOpen {
return false
}
rows.WriteString(taskRow(t))
count++
return count >= limit
})
if count == 0 {
return "No open tasks right now. Post one below.\n\n"
}
b.WriteString("| # | Title | Specialty | Budget | Status | Poster |\n")
b.WriteString("|---|---|---|---|---|---|\n")
b.WriteString(rows.String())
b.WriteString("\n")
return b.String()
}
func taskRow(t *Task) string {
poster := shortAddr(t.Poster)
if av := agents.Get(t.Poster.String()); av != nil {
poster = "[" + av.(*Agent).Name + "](" + link("agent/"+t.Poster.String()) + ")"
} else {
poster = "`" + poster + "`"
}
return "| " + strconv.Itoa(t.ID) + " | [" + t.Title + "](" + link("task/"+strconv.Itoa(t.ID)) + ") | " +
t.Specialty + " | " + fmtUgnot(t.BudgetUgnot) + " | " + statusLabel(t.Status) + " | " + poster + " |\n"
}
func taskBidsTable(t *Task) string {
prefix := padID(t.ID) + "/"
var rows strings.Builder
n := 0
bids.Iterate(prefix, prefix+"~", func(_ string, v any) bool {
b := v.(*Bid)
name := agentName(b.Agent)
mark := ""
if t.WinningBidID == b.ID {
mark = " **(accepted)**"
}
accept := ""
if t.Status == StatusOpen {
accept = " [Accept](" + txlink.NewLink("AcceptBid").AddArgs(
"taskID", strconv.Itoa(t.ID),
"bidID", strconv.Itoa(b.ID),
).URL() + ")"
}
note := "—"
if b.Note != "" {
note = b.Note
}
rows.WriteString("| #" + strconv.Itoa(b.ID) + " | [" + name + "](" + link("agent/"+b.Agent.String()) + ")" + mark + " | " +
fmtUgnot(b.Amount) + " | " + note + " |" + accept + " |\n")
n++
return false
})
if n == 0 {
return "No bids yet.\n\n"
}
return "| Bid | Agent | Amount | Note | |\n|---|---|---|---|---|\n" + rows.String() + "\n"
}
func bidsByAgentTable(owner address) string {
var rows strings.Builder
n := 0
// Walk bids and keep those from this agent (the board is size-capped).
bids.Iterate("", "", func(_ string, v any) bool {
b := v.(*Bid)
if b.Agent != owner {
return false
}
tv := tasks.Get(padID(b.TaskID))
title := "task #" + strconv.Itoa(b.TaskID)
status := ""
if tv != nil {
t := tv.(*Task)
title = "[" + t.Title + "](" + link("task/"+strconv.Itoa(t.ID)) + ")"
status = statusLabel(t.Status)
}
rows.WriteString("| #" + strconv.Itoa(b.ID) + " | " + title + " | " + fmtUgnot(b.Amount) + " | " + status + " |\n")
n++
return false
})
if n == 0 {
return "This agent has not bid on any tasks yet.\n\n"
}
return "| Bid | Task | Amount | Task status |\n|---|---|---|---|\n" + rows.String() + "\n"
}
func posterLink(addr address) string {
if agents.Get(addr.String()) != nil {
return "[" + agentName(addr) + "](" + link("agent/"+addr.String()) + ")"
}
return "`" + shortAddr(addr) + "`"
}
func agentName(addr address) string {
v := agents.Get(addr.String())
if v == nil {
return shortAddr(addr)
}
return v.(*Agent).Name
}
func statusLabel(s string) string {
switch s {
case StatusOpen:
return "Open"
case StatusInProgress:
return "In progress"
case StatusCompleted:
return "Completed"
case StatusCancelled:
return "Cancelled"
}
return s
}
func pager(route string, page, total int) string {
pages := (total + pageSize - 1) / pageSize
if pages <= 1 {
return ""
}
out := "Page " + strconv.Itoa(page) + " of " + strconv.Itoa(pages)
if page > 1 {
out += " · [Previous](" + link(route+"?page="+strconv.Itoa(page-1)) + ")"
}
if page < pages {
out += " · [Next](" + link(route+"?page="+strconv.Itoa(page+1)) + ")"
}
return out + "\n"
}
func notFound() string {
return "# Not found\n\n" + navBar()
}
func link(sub string) string {
if sub == "" {
return realmURL
}
return realmURL + ":" + sub
}
func pageParam(query string) int {
for _, kv := range strings.Split(query, "&") {
if strings.HasPrefix(kv, "page=") {
p, err := strconv.Atoi(strings.TrimPrefix(kv, "page="))
if err == nil && p >= 1 && p <= 100000 {
return p
}
}
}
return 1
}
func shortAddr(a address) string {
s := a.String()
if len(s) <= 14 {
return s
}
return s[:8] + "…" + s[len(s)-4:]
}
// fmtUgnot renders ugnot as a GNOT amount, e.g. 1500000 -> "1.5 GNOT".
func fmtUgnot(ugnot int64) string {
neg := ugnot < 0
if neg {
ugnot = -ugnot
}
whole := ugnot / ugnotPerGnot
frac := ugnot % ugnotPerGnot
w := strconv.FormatInt(whole, 10)
for i := len(w) - 3; i > 0; i -= 3 {
w = w[:i] + "," + w[i:]
}
out := w
if frac != 0 {
f := strconv.FormatInt(frac, 10)
for len(f) < 6 {
f = "0" + f
}
for len(f) > 0 && f[len(f)-1] == '0' {
f = f[:len(f)-1]
}
out = w + "." + f
}
if neg {
out = "-" + out
}
return out + " GNOT"
}
render_test.gno
package agentmarketplace
import (
"strconv"
"strings"
"testing"
"gno.land/p/nt/uassert/v0"
)
func TestRenderHomeAndPages(cur realm, t *testing.T) {
reset()
realmURL = "/r/g1pzn6rn8q0pfmq4xje4j8086ncnldavyz8skgp3/agentmarketplace"
empty := Render("")
uassert.True(t, strings.Contains(empty, "Agent Marketplace"))
uassert.True(t, strings.Contains(empty, "No agents yet"))
uassert.True(t, strings.Contains(empty, "No open tasks"))
uassert.True(t, strings.Contains(Render("missing"), "Not found"))
register(cur, carol, "Research Bot", "research, writing", RateHourly, 500000)
register(cur, bob, "Code Agent", "code, review", RateFlat, 2000000)
openID := post(cur, alice, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", 3000000)
workID := post(cur, alice, "Review a realm", "Look over an escrow realm for footguns please.", "review", 4000000)
bid(cur, carol, openID, 2500000, "I can summarize this")
bid2 := bid(cur, bob, workID, 3500000, "I can review this")
accept(cur, alice, workID, bid2)
complete(cur, bob, workID)
home := Render("")
uassert.True(t, strings.Contains(home, "Research Bot"))
uassert.True(t, strings.Contains(home, "Code Agent"))
uassert.True(t, strings.Contains(home, "Summarize a paper"))
uassert.True(t, strings.Contains(home, "In escrow"))
uassert.False(t, strings.Contains(home, "Review a realm"), "completed tasks should not appear in the open list")
agentPage := Render("agent/" + carol.String())
uassert.True(t, strings.Contains(agentPage, "Research Bot"))
uassert.True(t, strings.Contains(agentPage, "research, writing"))
uassert.True(t, strings.Contains(agentPage, "Summarize a paper"))
taskPage := Render("task/" + strconv.Itoa(openID))
uassert.True(t, strings.Contains(taskPage, "Summarize a paper"))
uassert.True(t, strings.Contains(taskPage, "I can summarize this"))
uassert.True(t, strings.Contains(taskPage, "Place a bid"))
uassert.True(t, strings.Contains(taskPage, "Cancel and refund"))
donePage := Render("task/" + strconv.Itoa(workID))
uassert.True(t, strings.Contains(donePage, "Completed"))
uassert.True(t, strings.Contains(donePage, "Code Agent"))
uassert.True(t, strings.Contains(donePage, "Escrow has been released"))
uassert.True(t, strings.Contains(donePage, "Rate 5 stars"))
rate(cur, alice, workID, 5, "Great review")
home = Render("")
uassert.True(t, strings.Contains(home, "Leaderboard"))
uassert.True(t, strings.Contains(home, "5.00"))
uassert.True(t, strings.Contains(home, "provisional"))
agentPage = Render("agent/" + bob.String())
uassert.True(t, strings.Contains(agentPage, "5.00"))
uassert.True(t, strings.Contains(agentPage, "Great review"))
uassert.True(t, strings.Contains(agentPage, "Rating history"))
ratedPage := Render("task/" + strconv.Itoa(workID))
uassert.True(t, strings.Contains(ratedPage, "5 / 5"))
uassert.True(t, strings.Contains(ratedPage, "Great review"))
board := Render("leaderboard")
uassert.True(t, strings.Contains(board, "Code Agent"))
uassert.True(t, strings.Contains(board, "5.00"))
uassert.True(t, strings.Contains(board, "provisional"))
about := Render("about")
uassert.True(t, strings.Contains(about, "20%"))
uassert.True(t, strings.Contains(about, "45-day"))
uassert.True(t, strings.Contains(about, "no identity layer"))
uassert.True(t, strings.Contains(about, "Hash-commit"))
uassert.True(t, strings.Contains(Render("agents"), "Research Bot"))
uassert.True(t, strings.Contains(Render("tasks"), "Review a realm"))
}
func TestFmtUgnot(t *testing.T) {
uassert.Equal(t, "0 GNOT", fmtUgnot(0))
uassert.Equal(t, "1 GNOT", fmtUgnot(1000000))
uassert.Equal(t, "1.5 GNOT", fmtUgnot(1500000))
uassert.Equal(t, "0.5 GNOT", fmtUgnot(500000))
uassert.Equal(t, "1,000 GNOT", fmtUgnot(1000000000))
uassert.Equal(t, "-2 GNOT", fmtUgnot(-2000000))
}
reputation.gno
package agentmarketplace
import (
"chain"
"strconv"
"time"
"gno.land/p/nt/avl/v0"
)
// Reputation tunables.
const (
minRatedForTrust = 3
halfLifeDays = 45
posterCapBps = 2000 // 20% target cap; raised to 1/N when fewer posters
weightUnit = 1000 // reviewer weight scale; 1000 = 1.0
decayScale = 1000000
scoreScale = 1000 // milli-stars; 5000 = 5.000
maxRatings = 20000
maxReviewerBonus = 2000 // extra weight cap in weightUnit
)
var (
nextRatingID = 1
ratings = avl.NewTree() // padID(id) -> *Rating
ratingsByAgent = avl.NewTree() // agent + "/" + padID(id) -> *Rating
ratingByTask = avl.NewTree() // padID(taskID) -> ratingID
scores = avl.NewTree() // agent.String() -> *AgentScore
scoreboard = avl.NewTree() // scoreKey -> agent address
posterStats = avl.NewTree() // poster.String() -> *PosterStats
posterAgents = avl.NewTree() // poster + "/" + agent -> true
)
// Rate records the task poster's 1-5 review of a settled job. Only the
// poster may rate, only after escrow has paid out, only once, and never
// their own agent. The score is weighted by the task budget, the poster's
// reviewer weight, a 45-day half-life, and a 20% cap on any one poster's
// influence on the agent.
func Rate(cur realm, taskID, score int, comment string) int {
caller := mustUserCall(cur)
t := mustGetTask(taskID)
if t.Status != StatusCompleted || !t.Settled {
panic("only a settled, completed task can be rated")
}
if t.Poster != caller {
panic("only the task poster can rate this job")
}
if t.Winner == caller {
panic("you cannot rate your own agent")
}
if ratingByTask.Get(padID(taskID)) != nil {
panic("this task has already been rated")
}
checkScore(score)
checkComment(comment)
if ratings.Size() >= maxRatings {
panic("the rating board is full")
}
now := time.Now()
wt := currentReviewerWeight(caller)
r := &Rating{
ID: nextRatingID,
TaskID: taskID,
Agent: t.Winner,
Poster: caller,
Score: score,
Comment: comment,
BudgetUgnot: t.BudgetUgnot,
ReviewerWt: wt,
RatedAt: now,
}
nextRatingID++
ratings.Set(padID(r.ID), r)
ratingsByAgent.Set(r.Agent.String()+"/"+padID(r.ID), r)
ratingByTask.Set(padID(taskID), r.ID)
chain.Emit("RatingCast",
"id", strconv.Itoa(r.ID),
"task", strconv.Itoa(taskID),
"agent", r.Agent.String(),
"poster", caller.String(),
"score", strconv.Itoa(score),
"budgetUgnot", strconv.FormatInt(t.BudgetUgnot, 10),
)
recomputeAndStore(r.Agent, now)
return r.ID
}
// RefreshScore recomputes an agent's trust score at the current block
// time, applying half-life decay. Anyone may call it.
func RefreshScore(cur realm, agent address) {
mustUserCall(cur)
if !agent.IsValid() {
panic("invalid address")
}
recomputeAndStore(agent, time.Now())
}
// ScoreOf returns a live reputation lookup: rating count, trust score in
// milli-stars (1000-5000), unweighted average in milli-stars, and whether
// the score is still provisional (fewer than 3 rated jobs). Unrated agents
// return (0, 0, 0, true).
func ScoreOf(agent address) (int, int64, int64, bool) {
s := liveScore(agent, time.Now())
return s.RatedCount, s.TrustMilli, s.RawMilli, s.Provisional
}
// RatingCount is the number of ratings stored in the realm.
func RatingCount() int { return ratings.Size() }
// ReputationSummary is a one-line text score, or "" if the agent is unrated.
func ReputationSummary(agent address) string {
s := liveScore(agent, time.Now())
if s.RatedCount == 0 {
return ""
}
label := "trusted"
if s.Provisional {
label = "provisional"
}
jobs := strconv.Itoa(s.RatedCount) + " jobs"
if s.RatedCount == 1 {
jobs = "1 job"
}
return fmtScore(s.TrustMilli) + " / 5 (" + label + ", " + jobs + ", raw " + fmtScore(s.RawMilli) + ")"
}
// ---------------------------------------------------------------------------
// internals
type posterBucket struct {
poster address
weight int64
points int64
}
func liveScore(agent address, now time.Time) *AgentScore {
out := &AgentScore{Agent: agent, Provisional: true}
var buckets []posterBucket
var rawSum int64
var last time.Time
prefix := agent.String() + "/"
ratingsByAgent.Iterate(prefix, prefix+"~", func(_ string, v any) bool {
r := v.(*Rating)
out.RatedCount++
rawSum += int64(r.Score)
if last.IsZero() || r.RatedAt.After(last) {
last = r.RatedAt
}
w := ratingWeight(r, now)
if w <= 0 {
return false
}
i := findBucket(buckets, r.Poster)
if i < 0 {
buckets = append(buckets, posterBucket{poster: r.Poster, weight: w, points: w * int64(r.Score)})
} else {
buckets[i].weight += w
buckets[i].points += w * int64(r.Score)
}
return false
})
out.LastRatedAt = last
if out.RatedCount == 0 {
return out
}
out.RawMilli = (rawSum * scoreScale) / int64(out.RatedCount)
out.Provisional = out.RatedCount < minRatedForTrust
capBuckets(buckets)
var denom, sum int64
for _, b := range buckets {
denom += b.weight
sum += b.points
}
if denom > 0 {
out.TrustMilli = (sum * scoreScale) / denom
}
return out
}
func ratingWeight(r *Rating, now time.Time) int64 {
age := now.Sub(r.RatedAt)
if age < 0 {
age = 0
}
// weight = budget * (reviewerWt / 1000) * (decay / 1e6)
w := r.BudgetUgnot
if r.ReviewerWt > 0 {
w = w * r.ReviewerWt / weightUnit
}
d := decayPPM(age)
if d <= 0 {
return 0
}
return w * d / decayScale
}
// decayPPM is 1e6 * 0.5^(age / 45 days), computed in integer math at
// the current block time.
func decayPPM(age time.Duration) int64 {
const halfLife = time.Duration(halfLifeDays) * 24 * time.Hour
if age <= 0 {
return decayScale
}
n := int64(age / halfLife)
if n >= 40 {
return 0
}
ppm := int64(decayScale)
for i := int64(0); i < n; i++ {
ppm /= 2
}
rem := age % halfLife
if rem == 0 || ppm == 0 {
return ppm
}
// 0.5^(rem/halfLife) ≈ 1 - ln2 f + (ln2^2/2) f^2 - (ln2^3/6) f^3
// with f in 1e6 and coefficients in 1e6.
// Convert to seconds first: rem * 1e6 overflows int64 in nanoseconds.
f := int64(rem/time.Second) * decayScale / int64(halfLife/time.Second)
const ln2 = int64(693147)
const c2 = int64(240226)
const c3 = int64(55504)
f2 := f * f / decayScale
f3 := f2 * f / decayScale
adj := decayScale - (ln2*f)/decayScale + (c2*f2)/decayScale - (c3*f3)/decayScale
if adj < decayScale/2 {
adj = decayScale / 2
}
if adj > decayScale {
adj = decayScale
}
return ppm * adj / decayScale
}
func findBucket(bs []posterBucket, poster address) int {
for i, b := range bs {
if b.poster == poster {
return i
}
}
return -1
}
// capBuckets caps one poster's share of the pre-cap weight mass. The
// target is 20%, but the cap is also at least 1/N so two or three honest
// posters are not all flattened to the same ceiling (a hard 20% cap cannot
// be satisfied by five or fewer equal raters). A sole poster is uncapped.
// Measuring against the original total (not leftover "others") keeps a
// 1 ugnot smear from becoming the scale a trusted poster's weight is
// measured against.
func capBuckets(bs []posterBucket) {
if len(bs) < 2 {
return
}
var total int64
for _, b := range bs {
total += b.weight
}
if total <= 0 {
return
}
n := int64(len(bs))
maxBps := int64(posterCapBps)
if inv := 10000 / n; inv > maxBps {
maxBps = inv
}
// maxW = maxBps of the pre-cap total, rounded up
maxW := (total*maxBps + 9999) / 10000
if maxW < 1 {
maxW = 1
}
for i, b := range bs {
if b.weight > maxW {
if b.weight > 0 {
bs[i].points = bs[i].points * maxW / b.weight
}
bs[i].weight = maxW
}
}
}
func currentReviewerWeight(poster address) int64 {
w := int64(weightUnit)
v := posterStats.Get(poster.String())
if v == nil {
return w
}
ps := v.(*PosterStats)
d := int64(ps.DistinctAgents)
if d > 20 {
d = 20
}
w += d * 100
gnot := ps.SettledUgnot / ugnotPerGnot
if gnot > maxReviewerBonus {
gnot = maxReviewerBonus
}
w += gnot
if w > weightUnit+maxReviewerBonus {
w = weightUnit + maxReviewerBonus
}
return w
}
func recordPosterPayment(poster, agent address, budget int64) {
v := posterStats.Get(poster.String())
var ps *PosterStats
if v == nil {
ps = &PosterStats{Owner: poster}
posterStats.Set(poster.String(), ps)
} else {
ps = v.(*PosterStats)
}
key := poster.String() + "/" + agent.String()
if posterAgents.Get(key) == nil {
posterAgents.Set(key, true)
ps.DistinctAgents++
}
ps.SettledJobs++
ps.SettledUgnot += budget
}
func recomputeAndStore(agent address, now time.Time) *AgentScore {
s := liveScore(agent, now)
if prev := scores.Get(agent.String()); prev != nil {
old := prev.(*AgentScore)
scoreboard.Remove(scoreKey(old.TrustMilli, old.RatedCount, agent))
}
if s.RatedCount > 0 {
scores.Set(agent.String(), s)
scoreboard.Set(scoreKey(s.TrustMilli, s.RatedCount, agent), agent)
} else {
scores.Remove(agent.String())
}
chain.Emit("ScoreUpdated",
"agent", agent.String(),
"ratedCount", strconv.Itoa(s.RatedCount),
"trustMilli", strconv.FormatInt(s.TrustMilli, 10),
"rawMilli", strconv.FormatInt(s.RawMilli, 10),
"provisional", strconv.FormatBool(s.Provisional),
)
return s
}
// scoreKey sorts the highest trust first, then the most ratings, then
// lowest address for a stable tie-break.
func scoreKey(trustMilli int64, count int, agent address) string {
const ceiling = int64(9999999)
inv := strconv.FormatInt(ceiling-trustMilli, 10)
for len(inv) < 7 {
inv = "0" + inv
}
c := strconv.Itoa(1000000 - count)
for len(c) < 7 {
c = "0" + c
}
return inv + "/" + c + "/" + agent.String()
}
func fmtScore(milli int64) string {
if milli < 0 {
milli = 0
}
whole := milli / scoreScale
frac := milli % scoreScale
// two decimal places
frac = frac / 10
f := strconv.FormatInt(frac, 10)
for len(f) < 2 {
f = "0" + f
}
return strconv.FormatInt(whole, 10) + "." + f
}
reputation_test.gno
package agentmarketplace
import (
"strconv"
"strings"
"testing"
"time"
"gno.land/p/nt/uassert/v0"
"gno.land/p/nt/urequire/v0"
)
const halfLifeHeights = int64(halfLifeDays * 24 * 3600 / 5) // 45 days at 5s / height
func TestRateAccessControl(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
id := post(cur, alice, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", 2000000)
urequire.AbortsWithMessage(t, cur, "only a settled, completed task can be rated", func() {
rate(cur, alice, id, 5, "too early")
})
bidID := bid(cur, carol, id, 2000000, "ready")
accept(cur, alice, id, bidID)
urequire.AbortsWithMessage(t, cur, "only a settled, completed task can be rated", func() {
rate(cur, alice, id, 5, "still early")
})
complete(cur, carol, id)
urequire.AbortsWithMessage(t, cur, "only the task poster can rate this job", func() {
rate(cur, bob, id, 5, "not my job")
})
urequire.AbortsWithMessage(t, cur, "only the task poster can rate this job", func() {
rate(cur, carol, id, 5, "self?")
})
urequire.AbortsWithMessage(t, cur, "score must be an integer from 1 to 5", func() {
rate(cur, alice, id, 0, "")
})
urequire.AbortsWithMessage(t, cur, "score must be an integer from 1 to 5", func() {
rate(cur, alice, id, 6, "")
})
rid := rate(cur, alice, id, 5, "Excellent summary")
uassert.Equal(t, 1, rid)
uassert.Equal(t, 1, RatingCount())
urequire.AbortsWithMessage(t, cur, "this task has already been rated", func() {
rate(cur, alice, id, 4, "again")
})
uassert.Equal(t, 1, RatingCount())
}
func TestCannotRateOwnAgent(cur realm, t *testing.T) {
reset()
// The usual bid path already refuses a poster bidding on their own task,
// so poke a settled self-deal into state to cover the Rate guard.
tasks.Set(padID(1), &Task{
ID: 1,
Poster: alice,
Title: "Self deal",
Description: "Should not be rateable by the winner.",
Specialty: "research",
BudgetUgnot: 1000000,
Status: StatusCompleted,
Settled: true,
Winner: alice,
})
nextTaskID = 2
urequire.AbortsWithMessage(t, cur, "you cannot rate your own agent", func() {
rate(cur, alice, 1, 5, "nice")
})
uassert.Equal(t, 0, RatingCount())
}
func TestCannotRateCancelled(cur realm, t *testing.T) {
reset()
id := post(cur, alice, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", 2000000)
cancel(cur, alice, id)
urequire.AbortsWithMessage(t, cur, "only a settled, completed task can be rated", func() {
rate(cur, alice, id, 5, "cancelled")
})
}
func TestScoreOfUnratedAndProvisional(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
count, trust, raw, prov := ScoreOf(carol)
uassert.Equal(t, 0, count)
uassert.Equal(t, int64(0), trust)
uassert.Equal(t, int64(0), raw)
uassert.True(t, prov)
uassert.Equal(t, "", ReputationSummary(carol))
// Three 4-star jobs from the same poster: still 4.00, flips to trusted at 3.
for i := 0; i < 3; i++ {
title := "Research job " + strconv.Itoa(i+1)
id := settleJob(cur, alice, carol, title, "A short research brief for this job.", "research", 2000000)
rate(cur, alice, id, 4, "Solid work")
count, trust, raw, prov = ScoreOf(carol)
uassert.Equal(t, i+1, count)
uassert.Equal(t, int64(4000), trust)
uassert.Equal(t, int64(4000), raw)
if i < 2 {
uassert.True(t, prov, "still provisional before 3 jobs")
uassert.True(t, strings.Contains(ReputationSummary(carol), "provisional"))
} else {
uassert.False(t, prov)
uassert.True(t, strings.Contains(ReputationSummary(carol), "trusted"))
}
}
}
func TestBudgetWeighting(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
// Two posters, same first-job reviewer shape, but 5 GNOT at 5 stars vs 1 GNOT at 1 star.
// Without the 20% cap this would sit near 4.33; the cap is tested separately.
idBig := settleJob(cur, alice, carol, "Large research brief", "Write a long research brief for a 5 GNOT budget.", "research", 5000000)
rate(cur, alice, idBig, 5, "Worth it")
idSmall := settleJob(cur, dave, carol, "Tiny research note", "Write a one-line research note for a 1 GNOT budget.", "research", 1000000)
rate(cur, dave, idSmall, 1, "Thin")
count, trust, raw, prov := ScoreOf(carol)
uassert.Equal(t, 2, count)
uassert.True(t, prov)
uassert.Equal(t, int64(3000), raw, "unweighted average of 5 and 1")
// 5 GNOT at 5 stars vs 1 GNOT at 1 star should sit between the raw
// average (3.00) and the uncapped budget mix (~4.33), because the
// large poster is clipped to 20% of the pre-cap weight mass.
uassert.True(t, trust != raw)
uassert.True(t, trust > 3000, "the larger 5-star still counts more")
uassert.True(t, trust < 4300, "the 20% cap should pull this below the uncapped mix")
}
func TestPosterCapTwentyPercent(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
// Five posters: one 10 GNOT 5-star and four 1 GNOT 1-stars. The cap is
// 20% (N>=5), so the large poster is clipped to 20% of the pre-cap
// mass and cannot bury the rest. Uncapped would be ~3.86; capped ~2.65.
idBig := settleJob(cur, alice, carol, "Large research brief", "Write a long research brief for a 10 GNOT budget.", "research", 10000000)
rate(cur, alice, idBig, 5, "Loved it")
smallPosters := []address{dave, eve, frank, bob}
for i, p := range smallPosters {
id := settleJob(cur, p, carol, "Tiny research note "+strconv.Itoa(i+1), "Write a one-line research note for 1 GNOT.", "research", 1000000)
rate(cur, p, id, 1, "Nope")
}
count, trust, raw, _ := ScoreOf(carol)
uassert.Equal(t, 5, count)
uassert.Equal(t, int64(1800), raw, "unweighted average of 5,1,1,1,1")
uassert.True(t, trust >= 2550 && trust <= 2800, "capped trust should be near 2.65, got "+fmtScore(trust))
uassert.True(t, trust > raw, "budget still gives the 5-star more weight than the raw average")
}
func TestSolePosterUncapped(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
id := settleJob(cur, alice, carol, "Solo research brief", "Only one poster rates this agent.", "research", 10000000)
rate(cur, alice, id, 5, "Only review")
_, trust, raw, prov := ScoreOf(carol)
uassert.Equal(t, int64(5000), trust)
uassert.Equal(t, int64(5000), raw)
uassert.True(t, prov)
}
func TestHalfLifeDecay(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
// Same poster, same budget: a 5-star ages one half-life, then a fresh
// 1-star arrives. One poster is uncapped, so decay alone should give
// (0.5*5 + 1*1) / 1.5 = 2.333.
idOld := settleJob(cur, alice, carol, "Older research brief", "This 5-star should lose half its weight.", "research", 2000000)
rate(cur, alice, idOld, 5, "Strong start")
_, trust, _, _ := ScoreOf(carol)
uassert.Equal(t, int64(5000), trust)
testing.SkipHeights(halfLifeHeights)
idNew := settleJob(cur, alice, carol, "Newer research brief", "This 1-star is fresh and should weigh twice the old 5.", "research", 2000000)
rate(cur, alice, idNew, 1, "Weak follow-up")
count, trust, raw, _ := ScoreOf(carol)
uassert.Equal(t, 2, count)
uassert.Equal(t, int64(3000), raw)
// (0.5*5 + 1*1) / 1.5 = 2.333...; allow a little slack if reviewer
// weights differ by a few GNOT of settled volume.
uassert.True(t, trust >= 2300 && trust <= 2400, "decayed mix should be near 2.33, got "+fmtScore(trust))
}
func TestDecayDoesNotChangeSingleRatingAverage(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
id := settleJob(cur, alice, carol, "Solo research brief", "A single rating should stay 5.00 as it decays.", "research", 2000000)
rate(cur, alice, id, 5, "Still five")
testing.SkipHeights(halfLifeHeights)
_, trust, raw, _ := ScoreOf(carol)
uassert.Equal(t, int64(5000), trust, "weight cancels in a single-rating average")
uassert.Equal(t, int64(5000), raw)
}
func TestRefreshScore(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
idOld := settleJob(cur, alice, carol, "Older research brief", "This 5-star will age one half-life.", "research", 2000000)
rate(cur, alice, idOld, 5, "Strong start")
testing.SkipHeights(halfLifeHeights)
idNew := settleJob(cur, alice, carol, "Newer research brief", "Fresh 1-star after the skip.", "research", 2000000)
rate(cur, alice, idNew, 1, "Weak follow-up")
_, live, _, _ := ScoreOf(carol)
refreshScore(cur, bob, carol) // anyone may refresh
cached := scores.Get(carol.String()).(*AgentScore)
uassert.Equal(t, live, cached.TrustMilli)
uassert.True(t, live >= 2300 && live <= 2400)
}
func TestSockPuppetBarelyMovesScore(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
// Trusted 4.00 from three 2 GNOT jobs, then a 1 ugnot 1-star smear.
for i := 0; i < 3; i++ {
id := settleJob(cur, alice, carol, "Baseline job "+strconv.Itoa(i+1), "A 2 GNOT research brief for the baseline.", "research", 2000000)
rate(cur, alice, id, 4, "Baseline")
}
_, before, _, prov := ScoreOf(carol)
uassert.Equal(t, int64(4000), before)
uassert.False(t, prov)
idSock := settleJob(cur, dave, carol, "Sock puppet job", "A 1 ugnot smear that should barely move the score.", "research", 1)
rate(cur, dave, idSock, 1, "Smear")
count, after, raw, stillTrusted := ScoreOf(carol)
uassert.Equal(t, 4, count)
uassert.False(t, stillTrusted)
uassert.True(t, raw < 4000, "raw average should dip")
// Trust must stay very close to 4.00 — well above 3.90.
uassert.True(t, after >= 3900 && after <= 4000, "1 ugnot smear should barely move 4.00, got "+fmtScore(after))
}
func TestFiveStarClimbsLeaderboard(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
register(cur, bob, "Code Agent", "code, review", RateFlat, 2000000)
register(cur, eve, "Writing Bot", "writing", RateFlat, 1500000)
register(cur, frank, "Data Agent", "data, research", RateHourly, 800000)
for i := 0; i < 3; i++ {
id := settleJob(cur, alice, carol, "Baseline job "+strconv.Itoa(i+1), "A 2 GNOT research brief for the baseline.", "research", 2000000)
rate(cur, alice, id, 4, "Baseline")
}
board := Render("leaderboard")
uassert.True(t, strings.Contains(board, "Research Bot"))
uassert.True(t, indexOf(board, "Research Bot") < indexOf(board, "Code Agent") || !strings.Contains(board, "Code Agent"))
id := settleJob(cur, alice, bob, "Review a realm", "Review an escrow realm and write up the findings.", "review", 3000000)
rate(cur, alice, id, 5, "Outstanding")
_, bobTrust, _, bobProv := ScoreOf(bob)
_, carolTrust, _, carolProv := ScoreOf(carol)
uassert.Equal(t, int64(5000), bobTrust)
uassert.True(t, bobProv, "one job stays provisional")
uassert.Equal(t, int64(4000), carolTrust)
uassert.False(t, carolProv)
uassert.True(t, bobTrust > carolTrust)
board = Render("leaderboard")
uassert.True(t, indexOf(board, "Code Agent") < indexOf(board, "Research Bot"), "5-star agent should rank above the trusted 4.00")
uassert.True(t, strings.Contains(board, "provisional"))
uassert.True(t, strings.Contains(board, "trusted"))
}
func TestScoreOfAndSummaryLookup(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
id := settleJob(cur, alice, carol, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", 2000000)
rate(cur, alice, id, 5, "Nice")
count, trust, raw, prov := ScoreOf(carol)
uassert.Equal(t, 1, count)
uassert.Equal(t, int64(5000), trust)
uassert.Equal(t, int64(5000), raw)
uassert.True(t, prov)
sum := ReputationSummary(carol)
uassert.True(t, strings.Contains(sum, "5.00"))
uassert.True(t, strings.Contains(sum, "provisional"))
uassert.True(t, strings.Contains(sum, "1 job"))
}
func TestDecayPPM(t *testing.T) {
half := time.Duration(halfLifeDays) * 24 * time.Hour
uassert.Equal(t, int64(decayScale), decayPPM(0))
uassert.Equal(t, int64(decayScale), decayPPM(-time.Hour))
uassert.Equal(t, int64(500000), decayPPM(half))
uassert.Equal(t, int64(250000), decayPPM(2*half))
uassert.Equal(t, int64(0), decayPPM(40*half))
mid := decayPPM(half / 2)
uassert.True(t, mid >= 700000 && mid <= 710000, "sqrt(1/2) is about 0.707, got "+strconv.Itoa(int(mid)))
}
func TestFmtScore(t *testing.T) {
uassert.Equal(t, "0.00", fmtScore(0))
uassert.Equal(t, "4.00", fmtScore(4000))
uassert.Equal(t, "5.00", fmtScore(5000))
uassert.Equal(t, "2.33", fmtScore(2333))
uassert.Equal(t, "1.80", fmtScore(1800))
}
func TestPosterStatsRecordedOnSettle(cur realm, t *testing.T) {
reset()
register(cur, carol, "Research Bot", "research", RateHourly, 500000)
register(cur, bob, "Code Agent", "code, review", RateFlat, 1000000)
settleJob(cur, alice, carol, "Summarize a paper", "Write a one-page summary of the attached paper.", "research", 2000000)
settleJob(cur, alice, bob, "Review a realm", "Look over an escrow realm for footguns please.", "review", 3000000)
ps := posterStats.Get(alice.String()).(*PosterStats)
uassert.Equal(t, 2, ps.SettledJobs)
uassert.Equal(t, int64(5000000), ps.SettledUgnot)
uassert.Equal(t, 2, ps.DistinctAgents)
uassert.True(t, currentReviewerWeight(alice) > weightUnit)
}
func indexOf(s, sub string) int {
i := strings.Index(s, sub)
if i < 0 {
return 1 << 30
}
return i
}
types.gno
package agentmarketplace
import "time"
// Rate kinds for an agent's listed price.
const (
RateHourly = "hourly"
RateFlat = "flat"
)
// Task statuses. The escrowed ugnot is held while the task is open or
// in-progress, then released exactly once on complete or cancel.
const (
StatusOpen = "open"
StatusInProgress = "in-progress"
StatusCompleted = "completed"
StatusCancelled = "cancelled"
)
// Agent is a registered worker. The caller's address is the agent id
// and owner; one address can register at most one agent.
type Agent struct {
Owner address
Name string
Tags string // canonical, comma-space separated specialties
RateKind string
RateUgnot int64
RegisteredAt time.Time
Completed int
EarnedUgnot int64
}
// Task is a job posted with an ugnot budget held in escrow by the realm.
type Task struct {
ID int
Poster address
Title string
Description string
Specialty string // required specialty tag
BudgetUgnot int64
Status string
PostedAt time.Time
WinningBidID int
Winner address
AcceptedAt time.Time
CompletedAt time.Time
Settled bool // true after payout or refund; prevents double settlement
// Optional hash-commit settlement. Empty CommitHash means the winning
// agent may call CompleteTask as usual. When set, they must reveal a
// preimage of this SHA-256 (lowercase hex) before RevealBy.
CommitHash string
RevealBy time.Time
}
// Bid is one agent's offer on an open task.
type Bid struct {
ID int
TaskID int
Agent address
Amount int64 // ugnot, must be > 0 and <= the task budget
Note string
PlacedAt time.Time
}
// Rating is one poster's 1-5 review of a settled job.
type Rating struct {
ID int
TaskID int
Agent address
Poster address
Score int // 1-5
Comment string
BudgetUgnot int64 // snapshot of the task budget, used as weight
ReviewerWt int64 // snapshot of reviewer weight (1000 = 1.0)
RatedAt time.Time
}
// AgentScore is a cached view of an agent's reputation, rebuilt on Rate
// and RefreshScore. Queries and Render recompute decay live from ratings.
type AgentScore struct {
Agent address
RatedCount int
TrustMilli int64 // 1000-5000, 0 if unrated
RawMilli int64
Provisional bool
LastRatedAt time.Time
}
// PosterStats tracks a poster's history, used to grow reviewer weight.
type PosterStats struct {
Owner address
SettledJobs int
SettledUgnot int64
DistinctAgents int
}
validate.gno
package agentmarketplace
import (
"sort"
"strconv"
"strings"
)
// Input limits.
const (
minNameLen = 3
maxNameLen = 48
minTitleLen = 3
maxTitleLen = 80
minDescLen = 3
maxDescLen = 280
maxNoteLen = 80
minTagLen = 2
maxTagLen = 24
maxTags = 8
maxTagsInputLen = 200
maxRateUgnot = 1000000000000 // 1,000,000 GNOT
minBudgetUgnot = 1
maxBudgetUgnot = 1000000000000
ugnotPerGnot = 1000000
minScore = 1
maxScore = 5
maxCommentLen = 120
commitHashLen = 64
minRevealSecs = 60
maxRevealSecs = 30 * 24 * 60 * 60
)
// isSafeChar is the character whitelist for every free-text field. It keeps
// user-supplied strings from injecting markdown, HTML, gnoweb tags or
// table pipes into Render output, and keeps them single-line.
func isSafeChar(c rune) bool {
switch {
case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', c >= '0' && c <= '9':
return true
}
switch c {
case ' ', '-', '.', ',', '(', ')', '\'', '/', '+', ':', '@', '#', '%', '&', '=':
return true
}
return false
}
// checkText validates a free-text field and panics with a readable message.
func checkText(field, s string, minLen, maxLen int) {
if len(s) < minLen || len(s) > maxLen {
panic(field + " must be " + strconv.Itoa(minLen) + "-" + strconv.Itoa(maxLen) + " characters")
}
if s[0] == ' ' || s[len(s)-1] == ' ' {
panic(field + " must not start or end with a space")
}
for _, c := range s {
if !isSafeChar(c) {
panic(field + " contains an unsupported character: only letters, digits, spaces and - . , ( ) ' / + : @ # % & = are allowed")
}
}
}
func checkRateKind(kind string) {
switch kind {
case RateHourly, RateFlat:
return
}
panic("rate kind must be one of: hourly, flat")
}
func checkRate(rate int64) {
if rate < 1 || rate > maxRateUgnot {
panic("rate must be between 1 and " + strconv.FormatInt(maxRateUgnot, 10) + " ugnot")
}
}
func checkBudget(budget int64) {
if budget < minBudgetUgnot || budget > maxBudgetUgnot {
panic("budget must be between " + strconv.FormatInt(minBudgetUgnot, 10) + " and " + strconv.FormatInt(maxBudgetUgnot, 10) + " ugnot")
}
}
// checkSpecialty validates a single required specialty tag.
func checkSpecialty(tag string) string {
normalized := strings.ToLower(strings.TrimSpace(tag))
checkTag("specialty", normalized)
return normalized
}
func checkTag(field, tag string) {
if len(tag) < minTagLen || len(tag) > maxTagLen {
panic(field + " must be " + strconv.Itoa(minTagLen) + "-" + strconv.Itoa(maxTagLen) + " characters")
}
if strings.Contains(tag, ",") {
panic(field + " must be a single tag, not a comma-separated list")
}
if tag[0] == ' ' || tag[len(tag)-1] == ' ' {
panic(field + " must not start or end with a space")
}
for _, c := range tag {
if !isSafeChar(c) {
panic(field + " contains an unsupported character: only letters, digits, spaces and - . , ( ) ' / + : @ # % & = are allowed")
}
}
}
// parseTags canonicalizes a comma-separated specialty list: lowercased,
// trimmed, unique, sorted, joined with ", ".
func parseTags(raw string) string {
checkText("tags", raw, minTagLen, maxTagsInputLen)
parts := strings.Split(raw, ",")
var tags []string
for _, p := range parts {
tag := strings.ToLower(strings.TrimSpace(p))
if tag == "" {
continue
}
checkTag("tag", tag)
if containsTag(tags, tag) {
continue
}
tags = append(tags, tag)
if len(tags) > maxTags {
panic("an agent can list at most " + strconv.Itoa(maxTags) + " specialty tags")
}
}
if len(tags) == 0 {
panic("tags must list at least one specialty")
}
sort.Strings(tags)
return strings.Join(tags, ", ")
}
func containsTag(tags []string, tag string) bool {
for _, t := range tags {
if t == tag {
return true
}
}
return false
}
func agentHasSpecialty(agentTags, specialty string) bool {
for _, t := range strings.Split(agentTags, ", ") {
if t == specialty {
return true
}
}
return false
}
func checkScore(score int) {
if score < minScore || score > maxScore {
panic("score must be an integer from 1 to 5")
}
}
func checkComment(comment string) {
if comment == "" {
return
}
checkText("comment", comment, 1, maxCommentLen)
}
func checkCommitHash(h string) string {
h = strings.ToLower(h)
if len(h) != commitHashLen {
panic("commit hash must be a 64-character hex SHA-256 digest")
}
for _, c := range h {
if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) {
panic("commit hash must be a 64-character hex SHA-256 digest")
}
}
return h
}
func checkRevealDeadline(secs int64) {
if secs < minRevealSecs || secs > maxRevealSecs {
panic("reveal deadline must be between 60 seconds and 30 days")
}
}