Playground
api.gno
package mequest
// JSON views for the website, served through Render("api/...").
// Read them with the RPC query vm/qrender, e.g. "<pkgpath>:api/quests".
import (
"strconv"
"strings"
"time"
"gno.land/r/sys/users"
)
func renderAPI(path string) string {
switch {
case path == "stats":
return apiStats()
case path == "quests":
out := make([]string, 0, len(quests))
for _, q := range quests {
out = append(out, questJSON(q, false))
}
return "[" + strings.Join(out, ",") + "]"
case strings.HasPrefix(path, "q/"):
id, err := strconv.Atoi(path[2:])
if err != nil || id < 1 || id > len(quests) {
return "null"
}
return questJSON(quests[id-1], true)
case strings.HasPrefix(path, "p/"):
return passportJSON(address(path[2:]))
case path == "top":
return topJSON()
case path == "feed":
out := []string{}
for i := len(log) - 1; i >= 0; i-- {
out = append(out, "{\"at\":"+i64(log[i].At)+",\"msg\":"+js(log[i].Msg)+"}")
}
return "[" + strings.Join(out, ",") + "]"
case path == "receipts":
out := []string{}
for i := len(receipts) - 1; i >= 0; i-- {
r := receipts[i]
out = append(out, "{\"n\":"+strconv.Itoa(r.N)+",\"quest\":"+strconv.Itoa(r.Quest)+
",\"title\":"+js(quests[r.Quest-1].Title)+",\"who\":"+who(r.Who)+",\"ok\":"+strconv.FormatBool(r.Ok)+
",\"check\":"+js(r.Check)+",\"paid\":"+i64(r.Paid)+",\"rarity\":"+strconv.Itoa(quests[r.Quest-1].Rarity)+
",\"art\":"+js(quests[r.Quest-1].Art)+",\"height\":"+i64(r.Height)+",\"at\":"+i64(r.At)+"}")
}
return "[" + strings.Join(out, ",") + "]"
case path == "projects":
out := []string{}
for a, on := range projects {
if on {
out = append(out, who(a))
}
}
return "{\"admin\":" + js(string(admin)) + ",\"approved\":[" + strings.Join(out, ",") + "]}"
}
return "null"
}
func apiStats() string {
locked := int64(0)
open := 0
now := time.Now().Unix()
for _, q := range quests {
locked += q.Pool
if now < q.Expires && len(q.Winners) < q.Max {
open++
}
}
return "{\"quests\":" + strconv.Itoa(len(quests)) + ",\"open\":" + strconv.Itoa(open) +
",\"locked\":" + i64(locked) + ",\"paid\":" + i64(paidOut) +
",\"cards\":" + strconv.Itoa(minted) + ",\"players\":" + strconv.Itoa(len(players)) + ",\"joined\":" + strconv.Itoa(joined) +
",\"season\":" + js(Season) + ",\"now\":" + i64(now) + "}"
}
func questJSON(q *Quest, full bool) string {
s := "{\"id\":" + strconv.Itoa(q.ID) + ",\"title\":" + js(q.Title) + ",\"desc\":" + js(q.Desc) +
",\"art\":" + js(q.Art) + ",\"funder\":" + who(q.Funder) + ",\"rarity\":" + strconv.Itoa(q.Rarity) +
",\"kind\":" + js(q.Kind) + ",\"arg\":" + js(q.Arg) + ",\"pay\":" + js(q.Pay) +
",\"reward\":" + i64(q.Reward) + ",\"pool\":" + i64(q.Pool) + ",\"funded\":" + i64(q.Funded) +
",\"max\":" + strconv.Itoa(q.Max) + ",\"claimed\":" + strconv.Itoa(len(q.Winners)) +
",\"pending\":" + strconv.Itoa(len(q.pending)) + ",\"expires\":" + i64(q.Expires) +
",\"settled\":" + strconv.FormatBool(q.Settled)
if full {
w := []string{}
for i, a := range q.Winners {
w = append(w, "{\"serial\":"+strconv.Itoa(i+1)+",\"who\":"+who(a)+"}")
}
p := []string{}
for a, proof := range q.pending {
p = append(p, "{\"who\":"+who(a)+",\"proof\":"+js(proof)+"}")
}
s += ",\"winners\":[" + strings.Join(w, ",") + "],\"queue\":[" + strings.Join(p, ",") + "]"
}
return s + "}"
}
func passportJSON(a address) string {
cs := []string{}
for _, c := range cards[a] {
cs = append(cs, "{\"quest\":"+strconv.Itoa(c.QuestID)+",\"title\":"+js(c.Title)+",\"art\":"+js(c.Art)+
",\"rarity\":"+strconv.Itoa(c.Rarity)+",\"serial\":"+strconv.Itoa(c.Serial)+
",\"season\":"+js(c.Season)+",\"at\":"+i64(c.At)+"}")
}
pend := []string{}
for _, q := range quests {
if _, ok := q.pending[a]; ok {
pend = append(pend, strconv.Itoa(q.ID))
}
}
best := BestRarity(a)
day := strconv.FormatInt(time.Now().Unix()/daySecs, 10)
return "{\"who\":" + who(a) + ",\"rank\":" + js(rankName[best]) + ",\"best\":" + strconv.Itoa(best) +
",\"points\":" + i64(points[a]) + ",\"today\":" + strconv.Itoa(daily[string(a)+":"+day]) +
",\"dailyCap\":" + strconv.Itoa(DailyCap) + ",\"streak\":" + strconv.Itoa(StreakOf(a)) +
",\"checkedToday\":" + strconv.FormatBool(lastDay[a] == time.Now().Unix()/daySecs && streak[a] > 0) +
",\"joinRank\":" + strconv.Itoa(joinRank[a]) + ",\"invites\":" + strconv.Itoa(invitesDone[a]) +
",\"hasInviter\":" + strconv.FormatBool(inviter[a] != "") + ",\"projects\":" + strconv.Itoa(ProjectsDone(a)) +
",\"posted\":" + strconv.Itoa(posted[a]) + ",\"approved\":" + strconv.FormatBool(projects[a] || a == admin) +
",\"cards\":[" + strings.Join(cs, ",") + "],\"pending\":[" + strings.Join(pend, ",") + "]}"
}
func topJSON() string {
list := ranked()
out := []string{}
for i, a := range list {
if i == 50 {
break
}
art := ""
best := 0
for _, c := range cards[a] {
if c.Rarity > best {
best, art = c.Rarity, c.Art
}
}
out = append(out, "{\"who\":"+who(a)+",\"points\":"+i64(points[a])+",\"best\":"+strconv.Itoa(best)+",\"bestArt\":"+js(art)+
",\"cards\":"+strconv.Itoa(len(cards[a]))+"}")
}
return "[" + strings.Join(out, ",") + "]"
}
func ranked() []address {
list := make([]address, len(players))
copy(list, players)
for i := 1; i < len(list); i++ {
for j := i; j > 0 && points[list[j]] > points[list[j-1]]; j-- {
list[j], list[j-1] = list[j-1], list[j]
}
}
return list
}
// who returns {"addr":..., "name":...}; name is the wallet's unique
// gno.land username from r/sys/users, or "" if it has none.
func who(a address) string {
name := ""
if u := users.ResolveAddress(a); u != nil {
name = u.Name()
}
return "{\"addr\":" + js(string(a)) + ",\"name\":" + js(name) + "}"
}
func i64(n int64) string { return strconv.FormatInt(n, 10) }
// js quotes a string as a JSON string.
func js(s string) string {
var b strings.Builder
b.WriteByte('"')
for _, r := range s {
switch {
case r == '"':
b.WriteString("\\\"")
case r == '\\':
b.WriteString("\\\\")
case r == '\n':
b.WriteString("\\n")
case r < 0x20:
h := strconv.FormatInt(int64(r), 16)
b.WriteString("\\u" + strings.Repeat("0", 4-len(h)) + h)
default:
b.WriteRune(r)
}
}
b.WriteByte('"')
return b.String()
}
checks.gno
package mequest
// Self-verifying checks. Every rule here is public code: the board runs it
// on the caller's wallet and only pays when it returns no reason.
import (
"chain/banker"
"chain/runtime/unsafe"
"strconv"
"strings"
"time"
"gno.land/r/sys/users"
)
const (
KindCheckin = "checkin" // check-in streak of at least Arg days (1 = first check-in)
KindEarly = "early" // among the first Arg wallets to join MeQuest
KindInvites = "invites" // at least Arg invited friends earned a card
KindProjects = "projects" // cards from at least Arg different projects
KindCards = "cards" // own at least Arg cards
KindPosted = "posted" // funded at least Arg quests as a project
KindMyRealm = "myrealm" // your own realm (gno.land/r/<your addr>/...) calls ProveRealm
KindGrant = "grant" // given by the quest funder (e.g. season top 3)
)
var (
joinRank = map[address]int{}
joined int
streak = map[address]int{}
lastDay = map[address]int64{}
inviter = map[address]address{}
invitesDone = map[address]int{}
posted = map[address]int{}
)
func validKind(kind, arg string) string {
switch kind {
case KindManual, KindPush, KindMyRealm, KindGrant, KindName:
return ""
case KindHold:
if n, err := strconv.ParseInt(arg, 10, 64); err != nil || n < 1 {
return "hold quests need a ugnot amount as arg"
}
return ""
case KindCard:
for _, part := range strings.Split(arg, ",") {
if n, err := strconv.Atoi(strings.TrimSpace(part)); err != nil || n < 1 || n > len(quests) {
return "card quests need existing quest ids as arg, like 1,2,3"
}
}
return ""
case KindCheckin, KindEarly, KindInvites, KindProjects, KindCards, KindPosted:
if n, err := strconv.Atoi(arg); err != nil || n < 1 {
return "this kind needs a number as arg"
}
return ""
}
return "bad kind"
}
// verifyReason runs the quest's own check. "" means the wallet passes.
func verifyReason(q *Quest, user address) string {
n, _ := strconv.Atoi(q.Arg)
switch q.Kind {
case KindHold:
min, _ := strconv.ParseInt(q.Arg, 10, 64)
if banker.NewReadonlyBanker().GetCoin(user, "ugnot") < min {
return "check failed: hold at least " + gnot(min)
}
case KindName:
if users.ResolveAddress(user) == nil {
return "check failed: register a gno.land username first"
}
case KindCard:
for _, part := range strings.Split(q.Arg, ",") {
id, _ := strconv.Atoi(strings.TrimSpace(part))
if !HasCard(user, id) {
return "check failed: you need the card from quest #" + strconv.Itoa(id) + " first"
}
}
case KindCheckin:
if s := StreakOf(user); s < n {
return "check failed: check-in streak is " + strconv.Itoa(s) + ", needs " + q.Arg
}
case KindEarly:
r := joinRank[user]
if r == 0 {
return "check failed: you haven't joined yet, check in first"
}
if r > n {
return "check failed: you joined as wallet #" + strconv.Itoa(r) + ", only the first " + q.Arg + " get this"
}
case KindInvites:
if invitesDone[user] < n {
return "check failed: " + strconv.Itoa(invitesDone[user]) + " invited friends earned a card, needs " + q.Arg
}
case KindProjects:
if p := ProjectsDone(user); p < n {
return "check failed: cards from " + strconv.Itoa(p) + " projects, needs " + q.Arg
}
case KindCards:
if len(cards[user]) < n {
return "check failed: you own " + strconv.Itoa(len(cards[user])) + " cards, needs " + q.Arg
}
case KindPosted:
if posted[user] < n {
return "check failed: post a funded quest first"
}
case KindManual:
return "this quest needs a proof: use Submit"
case KindPush:
return "finish this quest on the partner app: " + q.Arg
case KindMyRealm:
return "deploy your own realm and have it call ProveRealm"
case KindGrant:
return "this card is given by the project"
}
return ""
}
// gateReason checks board rules shared by every payout.
func gateReason(q *Quest, user address) string {
if time.Now().Unix() >= q.Expires {
return "quest expired"
}
if q.won[user] {
return "already claimed: one win per wallet"
}
if q.Rarity == Legendary && BestRarity(user) < Epic {
return "Legendary needs an Epic card first"
}
if len(q.Winners) >= q.Max {
return "all winner slots are taken"
}
day := strconv.FormatInt(time.Now().Unix()/daySecs, 10)
if daily[string(user)+":"+day] >= DailyCap {
return "daily cap reached: 10 claims per day"
}
return ""
}
// CanClaim is a free read-only dry run of Claim: "ok" or the reason it would fail.
func CanClaim(wallet address, id int) string {
if id < 1 || id > len(quests) {
return "quest not found"
}
q := quests[id-1]
if r := gateReason(q, wallet); r != "" {
return r
}
if r := verifyReason(q, wallet); r != "" {
return r
}
return "ok"
}
// CheckIn records today's check-in and grows your streak.
func CheckIn(cur realm) int {
requireWallet(cur)
user := cur.Previous().Address()
today := time.Now().Unix() / daySecs
last, seen := lastDay[user]
if seen && last == today {
panic("already checked in today")
}
if seen && last == today-1 {
streak[user]++
} else {
streak[user] = 1
}
lastDay[user] = today
touch(user)
return streak[user]
}
// StreakOf returns the live streak (0 if a day was missed).
func StreakOf(wallet address) int {
last, seen := lastDay[wallet]
if !seen || time.Now().Unix()/daySecs-last > 1 {
return 0
}
return streak[wallet]
}
// SetInviter links you to the friend who invited you. Once, before your first card.
func SetInviter(cur realm, friend address) {
requireWallet(cur)
user := cur.Previous().Address()
if friend == user || !friend.IsValid() {
panic("invalid inviter")
}
if _, ok := inviter[user]; ok {
panic("inviter already set")
}
if len(cards[user]) > 0 {
panic("set your inviter before your first card")
}
inviter[user] = friend
touch(user)
}
// ProveRealm must be called by a realm deployed under the caller's own
// address: gno.land/r/<your g1 address>/anything. That path proves you built it.
func ProveRealm(cur realm, id int) {
q := mustQuest(id)
if q.Kind != KindMyRealm {
panic("not a first-realm quest")
}
user := unsafe.OriginCaller()
prev := cur.Previous()
if !prev.IsCode() || !strings.HasPrefix(prev.PkgPath(), "gno.land/r/"+string(user)+"/") {
panic("call this from a realm under gno.land/r/" + string(user) + "/")
}
award(cur, q, user)
}
// Grant gives a grant-kind card. Quest funder only (e.g. Season Champion).
func Grant(cur realm, id int, wallet address) {
q := mustQuest(id)
if q.Kind != KindGrant {
panic("not a grant quest")
}
if c := cur.Previous().Address(); c != q.Funder && c != admin {
panic("only the quest funder can grant")
}
award(cur, q, wallet)
}
func ProjectsDone(wallet address) int {
seen := map[address]bool{}
for _, c := range cards[wallet] {
seen[quests[c.QuestID-1].Funder] = true
}
return len(seen)
}
func JoinRank(wallet address) int { return joinRank[wallet] }
func InvitesDone(wallet address) int { return invitesDone[wallet] }
func InviterOf(wallet address) address { return inviter[wallet] }
func touch(a address) {
if joinRank[a] == 0 {
joined++
joinRank[a] = joined
}
}
// checkLabel is the short proof line shown on a receipt.
func checkLabel(q *Quest) string {
switch q.Kind {
case KindHold:
if mustInt64(q.Arg) < 1000 {
return "holds GNOT → true"
}
return "balance >= " + gnot(mustInt64(q.Arg)) + " → true"
case KindName:
return "users.ResolveAddress → found"
case KindCard:
return "owns cards " + q.Arg + " → true"
case KindCheckin:
return "streak >= " + q.Arg + " → true"
case KindEarly:
return "join rank <= " + q.Arg + " → true"
case KindInvites:
return "invited friends >= " + q.Arg + " → true"
case KindProjects:
return "projects done >= " + q.Arg + " → true"
case KindCards:
return "cards owned >= " + q.Arg + " → true"
case KindPosted:
return "quests posted >= " + q.Arg + " → true"
case KindManual:
return "project review → approved"
case KindPush:
parts := strings.Split(q.Arg, "/")
return "reported by the " + parts[len(parts)-1] + " realm"
case KindMyRealm:
return "caller realm path → yours"
case KindGrant:
return "granted by project"
}
return "verified"
}
func mustInt64(s string) int64 {
n, _ := strconv.ParseInt(s, 10, 64)
return n
}
gnomod.toml
module = "gno.land/r/g1hwcp3aah5ehwq7zvz74c4x5nzewtgz2qmwjj0l/mequest" gno = "0.9" [addpkg] creator = "g1hwcp3aah5ehwq7zvz74c4x5nzewtgz2qmwjj0l" height = 1363409 max_deposit = "100000000ugnot"
gnostudio.gno
// This file is automatically generated and contains metadata about this // package deployment. It serves as a marker that this package was deployed // using Gno Studio (or Gno Playground) and may be used by tools for analytics, verification, // and ecosystem features. // // This file does not affect package execution and should not be modified. package mequest
mequest.gno
// Package mequest is MeQuest: quests that verify themselves.
//
// Projects lock GNOT rewards in this realm when they create a quest.
// Coins can only leave through a verified claim, a split settle, or a
// refund of the unclaimed remainder to the funder after expiry.
// Winners get a soulbound rarity card (Common/Rare/Epic/Legendary).
package mequest
import (
"chain"
"chain/banker"
"chain/runtime"
"chain/runtime/unsafe"
"strconv"
"strings"
"time"
)
// ---------- rules ----------
const (
Common = 1
Rare = 2
Epic = 3
Legendary = 4
KindManual = "manual" // project reviews a proof
KindPush = "push" // partner realm calls Complete
KindHold = "hold" // wallet holds at least Arg ugnot
KindName = "name" // wallet has a registered gno.land username
KindCard = "card" // wallet owns the card from quest Arg (quest chain)
PayFixed = "fixed" // style A: Reward per winner, paid on claim
PaySplit = "split" // style B: pool split equally after expiry
DailyCap = 10
Season = "S1"
daySecs = 86400
)
var (
admin address = "g1hwcp3aah5ehwq7zvz74c4x5nzewtgz2qmwjj0l"
supplyCap = map[int]int{Common: 0, Rare: 500, Epic: 100, Legendary: 10} // 0 = unlimited
cardPts = map[int]int64{Common: 10, Rare: 50, Epic: 200, Legendary: 1000}
rarityName = map[int]string{Common: "Common", Rare: "Rare", Epic: "Epic", Legendary: "Legendary"}
rankName = map[int]string{0: "Newcomer", Common: "Rookie", Rare: "Explorer", Epic: "Pathfinder", Legendary: "Legend"}
)
// ---------- state ----------
type Card struct {
QuestID int
Title string
Art string
Rarity int
Serial int
Season string
At int64
}
type Quest struct {
ID int
Title string
Desc string
Art string // card art key used by the website
Funder address
Rarity int
Kind string
Arg string // hold: min ugnot; push: partner pkg path
Pay string
Reward int64 // fixed: ugnot per winner
Pool int64 // ugnot still locked for this quest
Funded int64
Max int
Expires int64
Settled bool
Winners []address
won map[address]bool
pending map[address]string
}
var (
quests []*Quest
cards = map[address][]Card{}
points = map[address]int64{}
daily = map[string]int{}
projects = map[address]bool{}
players []address
log []event
paidOut int64
minted int
)
// receipt is a public case file for every payout or rejection.
type receipt struct {
N int
Quest int
Who address
Ok bool
Check string
Paid int64
Height int64
At int64
}
var receipts []receipt
func addReceipt(q *Quest, who address, ok bool, check string, paid int64) {
receipts = append(receipts, receipt{len(receipts) + 1, q.ID, who, ok, check, paid, runtime.ChainHeight(), time.Now().Unix()})
if len(receipts) > 100 {
receipts = receipts[len(receipts)-100:]
}
}
type event struct {
At int64
Msg string
}
// ---------- projects ----------
// CreateQuest locks the sent ugnot as the quest pool. Send coins with the tx.
func CreateQuest(cur realm, title, desc, art string, rarity int, kind, arg, pay string, max int, days int) int {
requireWallet(cur)
funder := cur.Previous().Address()
if rarity < Common || rarity > Legendary {
panic("bad rarity")
}
if rarity >= Epic && !projects[funder] && funder != admin {
panic("only approved projects can create Epic or Legendary quests")
}
if r := validKind(kind, arg); r != "" {
panic(r)
}
if pay != PayFixed && pay != PaySplit {
panic("bad pay style")
}
if pay == PaySplit && rarity < Epic && kind != KindPush {
panic("split pay is for Epic/Legendary or partner quests")
}
if max < 1 || (supplyCap[rarity] > 0 && max > supplyCap[rarity]) {
panic("max winners out of range for this rarity")
}
if days < 1 || days > 90 {
panic("days must be 1-90")
}
if strings.TrimSpace(title) == "" || len(title) > 60 || len(desc) > 400 || len(art) > 24 {
panic("title 1-60, desc up to 400, art key up to 24 chars")
}
sent := unsafe.OriginSend().AmountOf("ugnot")
if sent <= 0 {
panic("send ugnot to fund the pool")
}
q := &Quest{
ID: len(quests) + 1, Title: title, Desc: desc, Art: art, Funder: funder,
Rarity: rarity, Kind: kind, Arg: arg, Pay: pay,
Pool: sent, Funded: sent, Max: max,
Expires: time.Now().Unix() + int64(days)*daySecs,
won: map[address]bool{}, pending: map[address]string{},
}
if pay == PayFixed {
if sent%int64(max) != 0 {
panic("pool must divide evenly by max winners")
}
q.Reward = sent / int64(max)
}
quests = append(quests, q)
posted[funder]++
touch(funder)
note("quest #" + itoa(q.ID) + " created, pool " + gnot(sent))
return q.ID
}
// Review approves or rejects a manual proof. Funder or admin only.
func Review(cur realm, id int, wallet address, ok bool) {
q := mustQuest(id)
caller := cur.Previous().Address()
if caller != q.Funder && caller != admin {
panic("only the quest funder can review")
}
if _, has := q.pending[wallet]; !has {
panic("no pending proof")
}
delete(q.pending, wallet)
if ok {
award(cur, q, wallet)
} else {
addReceipt(q, wallet, false, "project review → rejected", 0)
note("quest #" + itoa(id) + " proof rejected for " + short(wallet))
}
}
// Refund returns the unclaimed pool of an expired fixed quest to its funder.
func Refund(cur realm, id int) {
q := mustQuest(id)
if q.Pay != PayFixed {
panic("split quests use Settle")
}
if time.Now().Unix() < q.Expires {
panic("quest still running: pool is locked")
}
if q.Pool == 0 {
panic("nothing to refund")
}
amt := q.Pool
q.Pool = 0
send(cur, q.Funder, amt)
note("quest #" + itoa(id) + " refunded " + gnot(amt) + " to funder")
}
// Settle pays a split quest after expiry. Anyone can call it.
func Settle(cur realm, id int) {
q := mustQuest(id)
if q.Pay != PaySplit || q.Settled {
panic("not a split quest or already settled")
}
if time.Now().Unix() < q.Expires {
panic("quest still running")
}
q.Settled = true
n := int64(len(q.Winners))
if n > 0 {
share := q.Pool / n
for _, w := range q.Winners {
send(cur, w, share)
q.Pool -= share
paidOut += share
}
note("quest #" + itoa(id) + " split " + gnot(share) + " x " + itoa(int(n)))
}
if q.Pool > 0 {
left := q.Pool
q.Pool = 0
send(cur, q.Funder, left)
}
}
// ---------- questers ----------
// Claim runs the quest's own check on the caller and pays if it passes.
func Claim(cur realm, id int) {
requireWallet(cur)
q := mustQuest(id)
user := cur.Previous().Address()
if r := verifyReason(q, user); r != "" {
panic(r)
}
award(cur, q, user)
}
// Submit sends a proof (link or text) for a manual quest.
func Submit(cur realm, id int, proof string) {
requireWallet(cur)
q := mustQuest(id)
user := cur.Previous().Address()
if q.Kind != KindManual {
panic("not a manual quest")
}
open(q, user)
if len(proof) == 0 || len(proof) > 280 {
panic("proof must be 1-280 chars")
}
touch(user)
q.pending[user] = proof
note("quest #" + itoa(id) + " proof submitted by " + short(user))
}
// Complete is called by the partner realm named in a push quest.
func Complete(cur realm, id int, wallet address) {
q := mustQuest(id)
if q.Kind != KindPush {
panic("not a push quest")
}
if cur.Previous().PkgPath() != q.Arg {
panic("only " + q.Arg + " can complete this quest")
}
award(cur, q, wallet)
}
// ---------- admin ----------
func ApproveProject(cur realm, p address, on bool) {
onlyAdmin(cur)
projects[p] = on
}
// Revoke removes a card from a cheater wallet.
func Revoke(cur realm, wallet address, id int) {
onlyAdmin(cur)
list := cards[wallet]
for i, c := range list {
if c.QuestID == id {
cards[wallet] = append(list[:i], list[i+1:]...)
points[wallet] -= cardPts[c.Rarity]
note("card from quest #" + itoa(id) + " revoked from " + short(wallet))
return
}
}
panic("wallet has no card from that quest")
}
// ---------- read-only checks (other realms can call these) ----------
func HasCard(wallet address, id int) bool {
for _, c := range cards[wallet] {
if c.QuestID == id {
return true
}
}
return false
}
func BestRarity(wallet address) int {
best := 0
for _, c := range cards[wallet] {
if c.Rarity > best {
best = c.Rarity
}
}
return best
}
func HasRarity(wallet address, min int) bool { return BestRarity(wallet) >= min }
func PointsOf(wallet address) int64 { return points[wallet] }
func CardCount(wallet address) int { return len(cards[wallet]) }
// ---------- internals ----------
func award(cur realm, q *Quest, user address) {
if r := gateReason(q, user); r != "" {
panic(r)
}
day := strconv.FormatInt(time.Now().Unix()/daySecs, 10)
key := string(user) + ":" + day
daily[key]++
q.won[user] = true
q.Winners = append(q.Winners, user)
if _, seen := points[user]; !seen {
players = append(players, user)
}
touch(user)
if len(cards[user]) == 0 {
if inv, ok := inviter[user]; ok {
invitesDone[inv]++
}
}
cards[user] = append(cards[user], Card{
QuestID: q.ID, Title: q.Title, Art: q.Art, Rarity: q.Rarity,
Serial: len(q.Winners), Season: Season, At: time.Now().Unix(),
})
points[user] += cardPts[q.Rarity]
minted++
paid := int64(0)
if q.Pay == PayFixed {
paid = q.Reward
}
addReceipt(q, user, true, checkLabel(q), paid)
msg := short(user) + " won " + rarityName[q.Rarity] + " #" + itoa(len(q.Winners)) + " on quest #" + itoa(q.ID)
if q.Pay == PayFixed {
q.Pool -= q.Reward
send(cur, user, q.Reward)
paidOut += q.Reward
msg += ", paid " + gnot(q.Reward)
}
note(msg)
}
func open(q *Quest, user address) {
if time.Now().Unix() >= q.Expires {
panic("quest expired")
}
if q.won[user] {
panic("already claimed: one win per wallet")
}
}
func send(cur realm, to address, amt int64) {
if amt <= 0 {
return
}
b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
b.SendCoins(cur.Address(), to, chain.Coins{{"ugnot", amt}})
}
// requireWallet blocks calls routed through other realms (anti-farming bots,
// and makes sure sent coins really came from the caller).
func requireWallet(cur realm) {
if !cur.Previous().IsUserCall() {
panic("call this directly from your wallet")
}
}
func onlyAdmin(cur realm) {
if cur.Previous().Address() != admin {
panic("admin only")
}
}
func mustQuest(id int) *Quest {
if id < 1 || id > len(quests) {
panic("quest not found")
}
return quests[id-1]
}
func note(s string) {
log = append(log, event{time.Now().Unix(), s})
if len(log) > 50 {
log = log[len(log)-50:]
}
}
func itoa(n int) string { return strconv.Itoa(n) }
func gnot(ugnot int64) string {
whole := ugnot / 1000000
frac := ugnot % 1000000
if frac == 0 {
return strconv.FormatInt(whole, 10) + " GNOT"
}
f := strings.TrimRight(strconv.FormatInt(frac+1000000, 10)[1:], "0")
return strconv.FormatInt(whole, 10) + "." + f + " GNOT"
}
func short(a address) string {
s := string(a)
if len(s) < 12 {
return s
}
return s[:7] + "…" + s[len(s)-4:]
}
// ---------- pages ----------
func Render(path string) string {
switch {
case strings.HasPrefix(path, "api/"):
return renderAPI(path[4:])
case path == "":
return renderBoard()
case strings.HasPrefix(path, "q/"):
id, err := strconv.Atoi(path[2:])
if err != nil || id < 1 || id > len(quests) {
return "quest not found"
}
return renderQuest(quests[id-1])
case strings.HasPrefix(path, "p/"):
return renderPassport(address(path[2:]))
case path == "top":
return renderTop()
}
return "404"
}
func renderBoard() string {
s := "# MeQuest\n_Quests that verify themselves._ Season " + Season + "\n\n"
s += "[Leaderboard](:top)\n\n## Quests\n\n"
if len(quests) == 0 {
s += "No quests yet.\n"
}
for i := len(quests) - 1; i >= 0; i-- {
q := quests[i]
s += "- [#" + itoa(q.ID) + " " + q.Title + "](:q/" + itoa(q.ID) + ") · " + rarityName[q.Rarity] +
" · " + itoa(len(q.Winners)) + "/" + itoa(q.Max) + " claimed · pool " + gnot(q.Pool) + " left\n"
}
s += "\n## Live feed\n\n"
for i := len(log) - 1; i >= 0 && i >= len(log)-10; i-- {
s += "- " + log[i].Msg + "\n"
}
return s
}
func renderQuest(q *Quest) string {
s := "# #" + itoa(q.ID) + " " + q.Title + "\n\n" + q.Desc + "\n\n"
s += "- Card: **" + rarityName[q.Rarity] + "** (" + Season + ")\n"
s += "- Check: " + q.Kind
if q.Arg != "" {
s += " `" + q.Arg + "`"
}
s += "\n- Pay: " + q.Pay
if q.Pay == PayFixed {
s += ", " + gnot(q.Reward) + " per winner"
}
s += "\n- Pool: " + gnot(q.Pool) + " locked of " + gnot(q.Funded) + " funded\n"
s += "- Winners: " + itoa(len(q.Winners)) + "/" + itoa(q.Max) + "\n"
s += "- Funder: " + short(q.Funder) + "\n- Ends: " + time.Unix(q.Expires, 0).UTC().Format("2006-01-02 15:04 UTC") + "\n"
return s
}
func renderPassport(w address) string {
best := BestRarity(w)
s := "# Passport: " + short(w) + "\n\n**" + rankName[best] + "** · " +
strconv.FormatInt(points[w], 10) + " pts · " + itoa(len(cards[w])) + " cards\n\n"
for _, c := range cards[w] {
s += "- " + rarityName[c.Rarity] + " · " + c.Title + " · #" + itoa(c.Serial) + " · " + c.Season + "\n"
}
return s
}
func renderTop() string {
list := ranked()
s := "# Season " + Season + " leaderboard\n\n"
for i, w := range list {
if i == 10 {
break
}
s += itoa(i+1) + ". [" + short(w) + "](:p/" + string(w) + ") · " + strconv.FormatInt(points[w], 10) + " pts\n"
}
return s
}