agentpay.gno
2.34 Kb · 76 lines
1// Package agentpay pays a Mimir agent for one Mimir API call in mUSD: the
2// gno.land port of contracts/MimirAgentPay.sol.
3//
4// The caller asks Mimir for a quote (GET /api/launch/:id/call), which names
5// the agent's wallet, the price, a fresh `secret` and
6// callId = hex(sha256(secret)). It approves this realm on mUSD and calls Pay
7// in the same transaction, then sends the transaction hash and the secret to
8// Mimir in `X-Mimir-Payment: gno:<tx>:<secret>`. Mimir reads the Paid event
9// and counts it only if its callId is the hash of that secret, so a
10// transaction seen on chain is useless to anyone without the secret.
11//
12// Non-custodial: mUSD moves from the payer straight to the agent in the same
13// call; this realm never holds funds, takes no fee and has no owner. The only
14// state is the call ids each payer has used, so a quote is paid once. Ids are
15// kept per payer, so nobody can spend someone else's pending id first.
16package agentpay
17
18import (
19 "chain"
20 "strconv"
21
22 "gno.land/p/nt/avl/v0"
23 "gno.land/r/g12dcsmwccgdxasqde2eumua88tlrkw83kqf6tcz/musd"
24)
25
26// used: payer + "/" + callId -> true
27var used avl.Tree
28
29func Pay(cur realm, agent address, amount int64, callID string) {
30 payer := cur.Previous().Address()
31 if !agent.IsValid() {
32 panic("ZeroAddress")
33 }
34 if agent == cur.Address() {
35 panic("BadAgent")
36 }
37 if amount <= 0 {
38 panic("ZeroAmount")
39 }
40 if !isHash(callID) {
41 panic("BadCallId")
42 }
43 k := payer.String() + "/" + callID
44 if used.Has(k) {
45 panic("CallIdUsed")
46 }
47 used.Set(k, true)
48 musd.TransferFrom(cross(cur), payer, agent, amount)
49 chain.Emit("Paid", "callId", callID, "agent", agent.String(), "payer", payer.String(),
50 "amount", strconv.FormatInt(amount, 10))
51}
52
53// Used reports whether payer has already paid for callID.
54func Used(payer address, callID string) bool { return used.Has(payer.String() + "/" + callID) }
55
56// isHash accepts a lowercase hex sha256 digest, never the zero hash.
57func isHash(s string) bool {
58 if len(s) != 64 {
59 return false
60 }
61 zero := true
62 for _, c := range s {
63 if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
64 return false
65 }
66 if c != '0' {
67 zero = false
68 }
69 }
70 return !zero
71}
72
73func Render(path string) string {
74 return "# Mimir agent pay\n\nPays a Mimir agent for one API call in mUSD, straight from the payer to the agent. " +
75 "No custody, no fee, no owner. Each call id is paid once per payer.\n"
76}