warmpocket.gno
9.02 Kb · 375 lines
1// Package warmpocket implements on-chain gift envelopes and recurring care plans.
2//
3// WarmPocket (中文名:暖袋) keeps funds inside the realm until a recipient
4// claims them. Two modes are supported:
5//
6// - Instant gift: a single claim, optionally protected by a secret link code.
7// - Care plan: monthly / quarterly / yearly installments that the recipient
8// claims when each installment is due; the sender can cancel and reclaim
9// any unclaimed funds at any time.
10//
11// All money flows are push-only (the sender attaches ugnot to the transaction),
12// and payouts are made from the realm's own balance with BankerTypeRealmSend.
13package warmpocket
14
15import (
16 "crypto/sha256"
17 "encoding/hex"
18 "strconv"
19 "strings"
20 "time"
21
22 "chain"
23 "chain/banker"
24 "chain/runtime/unsafe"
25)
26
27const (
28 denom = "ugnot"
29 kindInstant = "instant"
30 kindPlan = "plan"
31 version = "warmpocket:v1"
32)
33
34// Gift is the persisted record of one envelope or one recurring plan.
35type Gift struct {
36 ID string
37 Kind string
38 Sender address
39 Recipient address
40 Code string
41 Title string
42 Theme string
43 Amount int64 // per claim, in ugnot
44 Total int64 // originally funded amount
45 Remaining int64 // still held by the realm for this gift
46 PeriodMonths int // 0 for instant, otherwise 1 / 3 / 12
47 Installments int
48 Paid int
49 NextDue int64 // unix seconds
50 CreatedAt int64
51 Claimed bool
52 Canceled bool
53}
54
55var (
56 gifts = map[string]*Gift{}
57 codes = map[string]string{}
58 order []string
59 seq int64
60)
61
62// requireUser accepts only a direct EOA transaction and returns the signer.
63// The EOA check is what guarantees that OriginSend funds really reached this
64// realm, so the two checks below must always be used together.
65func requireUser(cur realm) address {
66 if !cur.Previous().IsUserCall() {
67 panic("direct wallet call required")
68 }
69 return unsafe.OriginCaller()
70}
71
72// requireSend verifies that the transaction attached exactly the expected amount.
73func requireSend(amount int64) {
74 if unsafe.OriginSend().AmountOf(denom) != amount {
75 panic("wrong payment amount")
76 }
77}
78
79// pay sends ugnot from the realm balance to the given address.
80func pay(cur realm, to address, amount int64) {
81 if amount <= 0 {
82 panic("invalid payout")
83 }
84 b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
85 b.SendCoins(unsafe.CurrentRealm().Address(), to, chain.NewCoins(chain.Coin{denom, amount}))
86}
87
88func validateCode(code string) {
89 if len(code) < 6 || len(code) > 64 {
90 panic("code must be 6-64 characters")
91 }
92 if _, exists := codes[code]; exists {
93 panic("code already used")
94 }
95}
96
97func parseRecipient(recipient string) address {
98 var result address
99 if recipient == "" {
100 return result
101 }
102 result = address(recipient)
103 if !result.IsValid() {
104 panic("invalid recipient address")
105 }
106 return result
107}
108
109func makeCode(seed string) string {
110 sum := sha256.Sum256([]byte(seed + strconv.FormatInt(seq, 10) + strconv.FormatInt(time.Now().UnixNano(), 10)))
111 return hex.EncodeToString(sum[:8])
112}
113
114func save(g *Gift) string {
115 seq++
116 g.ID = "G" + strconv.FormatInt(seq, 10)
117 g.CreatedAt = time.Now().Unix()
118 gifts[g.ID] = g
119 codes[g.Code] = g.ID
120 order = append(order, g.ID)
121 return g.ID
122}
123
124// CreateInstant funds a single-use envelope. A recipient address restricts the
125// claim to one wallet; leaving it empty turns the code into a bearer link.
126func CreateInstant(cur realm, code, title, theme, recipient string, amount int64) string {
127 caller := requireUser(cur)
128 if amount <= 0 {
129 panic("amount must be positive")
130 }
131 requireSend(amount)
132 if code == "" {
133 code = makeCode("instant:" + caller.String())
134 }
135 validateCode(code)
136 g := &Gift{
137 Kind: kindInstant,
138 Sender: caller,
139 Recipient: parseRecipient(recipient),
140 Code: code,
141 Title: title,
142 Theme: theme,
143 Amount: amount,
144 Total: amount,
145 Remaining: amount,
146 }
147 return save(g)
148}
149
150// CreatePlan funds a recurring allowance. Funds are held by the realm and
151// released one installment at a time when the recipient calls Claim.
152func CreatePlan(cur realm, code, title, theme, recipient string, amount int64, periodMonths, installments int, startUnix int64) string {
153 caller := requireUser(cur)
154 if amount <= 0 {
155 panic("amount must be positive")
156 }
157 if installments < 1 || installments > 240 {
158 panic("installments must be between 1 and 240")
159 }
160 if periodMonths != 1 && periodMonths != 3 && periodMonths != 12 {
161 panic("period must be 1, 3 or 12 months")
162 }
163 total := amount * int64(installments)
164 requireSend(total)
165 if code == "" {
166 code = makeCode("plan:" + caller.String())
167 }
168 validateCode(code)
169 if startUnix <= 0 {
170 startUnix = time.Now().Unix()
171 }
172 g := &Gift{
173 Kind: kindPlan,
174 Sender: caller,
175 Recipient: parseRecipient(recipient),
176 Code: code,
177 Title: title,
178 Theme: theme,
179 Amount: amount,
180 Total: total,
181 Remaining: total,
182 PeriodMonths: periodMonths,
183 Installments: installments,
184 NextDue: startUnix,
185 }
186 return save(g)
187}
188
189func addMonths(unix int64, months int) int64 {
190 return time.Unix(unix, 0).AddDate(0, months, 0).Unix()
191}
192
193// Claim pays one installment to the caller. For an instant gift the envelope
194// is marked claimed; for a plan the next due date is advanced by its period.
195func Claim(cur realm, code string) string {
196 caller := requireUser(cur)
197 id, ok := codes[code]
198 if !ok {
199 panic("unknown code")
200 }
201 g := gifts[id]
202 if g == nil {
203 panic("unknown gift")
204 }
205 if g.Canceled {
206 panic("gift was canceled")
207 }
208 var zero address
209 if g.Recipient != zero && g.Recipient != caller {
210 panic("not the recipient")
211 }
212
213 if g.Kind == kindInstant {
214 if g.Claimed {
215 panic("already claimed")
216 }
217 g.Claimed = true
218 g.Remaining = 0
219 pay(cur, caller, g.Amount)
220 return g.ID
221 }
222
223 if g.Paid >= g.Installments {
224 panic("plan completed")
225 }
226 if time.Now().Unix() < g.NextDue {
227 panic("not due yet")
228 }
229 g.Paid++
230 g.Remaining -= g.Amount
231 g.NextDue = addMonths(g.NextDue, g.PeriodMonths)
232 pay(cur, caller, g.Amount)
233 return g.ID
234}
235
236// Cancel refunds all unclaimed funds to the original sender.
237func Cancel(cur realm, id string) string {
238 caller := requireUser(cur)
239 g := gifts[id]
240 if g == nil {
241 panic("unknown gift")
242 }
243 if g.Sender != caller {
244 panic("only the sender can cancel")
245 }
246 if g.Canceled {
247 panic("already canceled")
248 }
249 remaining := g.Remaining
250 if remaining <= 0 {
251 panic("nothing to refund")
252 }
253 g.Canceled = true
254 g.Remaining = 0
255 pay(cur, caller, remaining)
256 return g.ID
257}
258
259// ---- read-only helpers, callable through vm/qeval ----
260
261func Ping() string {
262 return version
263}
264
265func Count() int {
266 return len(order)
267}
268
269func IDAt(i int) string {
270 if i < 0 || i >= len(order) {
271 return ""
272 }
273 return order[i]
274}
275
276func clean(s string) string {
277 s = strings.ReplaceAll(s, "|", "|")
278 return strings.ReplaceAll(s, ";", ";")
279}
280
281func flag(v bool) string {
282 if v {
283 return "1"
284 }
285 return "0"
286}
287
288func recipientText(a address) string {
289 var zero address
290 if a == zero {
291 return ""
292 }
293 return a.String()
294}
295
296// GetGift returns pipe-separated fields:
297// id|kind|sender|recipient|code|title|theme|amount|remaining|period|installments|paid|nextDue|createdAt|claimed|canceled
298func GetGift(id string) string {
299 g := gifts[id]
300 if g == nil {
301 return ""
302 }
303 parts := []string{
304 g.ID,
305 g.Kind,
306 g.Sender.String(),
307 recipientText(g.Recipient),
308 g.Code,
309 clean(g.Title),
310 clean(g.Theme),
311 strconv.FormatInt(g.Amount, 10),
312 strconv.FormatInt(g.Remaining, 10),
313 strconv.Itoa(g.PeriodMonths),
314 strconv.Itoa(g.Installments),
315 strconv.Itoa(g.Paid),
316 strconv.FormatInt(g.NextDue, 10),
317 strconv.FormatInt(g.CreatedAt, 10),
318 flag(g.Claimed),
319 flag(g.Canceled),
320 }
321 return strings.Join(parts, "|")
322}
323
324func GetByCode(code string) string {
325 id, ok := codes[code]
326 if !ok {
327 return ""
328 }
329 return GetGift(id)
330}
331
332// Render gives gnoweb a usable, text-only dashboard for the realm.
333func Render(path string) string {
334 out := "# 暖袋 WarmPocket\n\n"
335 out += "Gift envelopes and recurring care plans, settled on chain.\n\n"
336
337 if strings.HasPrefix(path, "gift/") {
338 id := strings.TrimPrefix(path, "gift/")
339 raw := GetGift(id)
340 if raw == "" {
341 return out + "Gift not found.\n"
342 }
343 f := strings.Split(raw, "|")
344 out += "## " + f[5] + "\n\n"
345 out += "- Kind: " + f[1] + "\n"
346 out += "- Theme: " + f[6] + "\n"
347 out += "- Amount per claim: " + f[7] + " ugnot\n"
348 out += "- Remaining: " + f[8] + " ugnot\n"
349 out += "- Paid: " + f[11] + "/" + f[10] + "\n"
350 out += "- Claimed: " + f[14] + " / Canceled: " + f[15] + "\n"
351 return out
352 }
353
354 out += "Total gifts: " + strconv.Itoa(Count()) + "\n\n"
355 if Count() == 0 {
356 return out + "No gift yet. Create the first one from the web app.\n"
357 }
358 start := Count() - 20
359 if start < 0 {
360 start = 0
361 }
362 for i := start; i < Count(); i++ {
363 f := strings.Split(GetGift(IDAt(i)), "|")
364 status := "open"
365 if f[15] == "1" {
366 status = "canceled"
367 } else if f[1] == kindInstant && f[14] == "1" {
368 status = "claimed"
369 } else if f[1] == kindPlan {
370 status = f[11] + "/" + f[10] + " paid"
371 }
372 out += "- [" + f[0] + "](" + path + "gift/" + f[0] + ") " + f[5] + " — " + f[7] + " ugnot — " + status + "\n"
373 }
374 return out
375}