Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

Playground

gnomod.toml

module = "gno.land/r/g1l4ummjltcfraqysyklw3vchf2vwl85fqnssupe/warmpocketen"
gno = "0.9"

[addpkg]
  creator = "g1l4ummjltcfraqysyklw3vchf2vwl85fqnssupe"
  height = 1655670
  max_deposit = "5000000ugnot"

warmpocket.gno

// Package warmpocket implements on-chain gift envelopes and recurring care plans.
//
// WarmPocket (Chinese name: 暖袋) keeps funds inside the realm until a
// recipient claims them. Two modes are supported:
//
//   - Instant gift: a single claim, optionally protected by a secret link code.
//   - Care plan: monthly / quarterly / yearly installments that the recipient
//     claims when each installment is due; the sender can cancel and reclaim
//     any unclaimed funds at any time.
//
// All money flows are push-only (the sender attaches ugnot to the transaction),
// and payouts are made from the realm's own balance with BankerTypeRealmSend.
package warmpocketen

import (
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"strings"
	"time"

	"chain"
	"chain/banker"
	"chain/runtime/unsafe"
)

const (
	denom       = "ugnot"
	kindInstant = "instant"
	kindPlan    = "plan"
	version     = "warmpocket:v1"
)

// Gift is the persisted record of one envelope or one recurring plan.
type Gift struct {
	ID           string
	Kind         string
	Sender       address
	Recipient    address
	Code         string
	Title        string
	Theme        string
	Amount       int64 // per claim, in ugnot
	Total        int64 // originally funded amount
	Remaining    int64 // still held by the realm for this gift
	PeriodMonths int   // 0 for instant, otherwise 1 / 3 / 12
	Installments int
	Paid         int
	NextDue      int64 // unix seconds
	CreatedAt    int64
	Claimed      bool
	Canceled     bool
}

var (
	gifts  = map[string]*Gift{}
	codes  = map[string]string{}
	order  []string
	seq    int64
)

// requireUser accepts only a direct EOA transaction and returns the signer.
// The EOA check is what guarantees that OriginSend funds really reached this
// realm, so the two checks below must always be used together.
func requireUser(cur realm) address {
	if !cur.Previous().IsUserCall() {
		panic("direct wallet call required")
	}
	return unsafe.OriginCaller()
}

// requireSend verifies that the transaction attached exactly the expected amount.
func requireSend(amount int64) {
	if unsafe.OriginSend().AmountOf(denom) != amount {
		panic("wrong payment amount")
	}
}

// pay sends ugnot from the realm balance to the given address.
func pay(cur realm, to address, amount int64) {
	if amount <= 0 {
		panic("invalid payout")
	}
	b := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	b.SendCoins(unsafe.CurrentRealm().Address(), to, chain.NewCoins(chain.Coin{denom, amount}))
}

func validateCode(code string) {
	if len(code) < 6 || len(code) > 64 {
		panic("code must be 6-64 characters")
	}
	if _, exists := codes[code]; exists {
		panic("code already used")
	}
}

func parseRecipient(recipient string) address {
	var result address
	if recipient == "" {
		return result
	}
	result = address(recipient)
	if !result.IsValid() {
		panic("invalid recipient address")
	}
	return result
}

func makeCode(seed string) string {
	sum := sha256.Sum256([]byte(seed + strconv.FormatInt(seq, 10) + strconv.FormatInt(time.Now().UnixNano(), 10)))
	return hex.EncodeToString(sum[:8])
}

func save(g *Gift) string {
	seq++
	g.ID = "G" + strconv.FormatInt(seq, 10)
	g.CreatedAt = time.Now().Unix()
	gifts[g.ID] = g
	codes[g.Code] = g.ID
	order = append(order, g.ID)
	return g.ID
}

// CreateInstant funds a single-use envelope. A recipient address restricts the
// claim to one wallet; leaving it empty turns the code into a bearer link.
func CreateInstant(cur realm, code, title, theme, recipient string, amount int64) string {
	caller := requireUser(cur)
	if amount <= 0 {
		panic("amount must be positive")
	}
	requireSend(amount)
	if code == "" {
		code = makeCode("instant:" + caller.String())
	}
	validateCode(code)
	g := &Gift{
		Kind:      kindInstant,
		Sender:    caller,
		Recipient: parseRecipient(recipient),
		Code:      code,
		Title:     title,
		Theme:     theme,
		Amount:    amount,
		Total:     amount,
		Remaining: amount,
	}
	return save(g)
}

// CreatePlan funds a recurring allowance. Funds are held by the realm and
// released one installment at a time when the recipient calls Claim.
func CreatePlan(cur realm, code, title, theme, recipient string, amount int64, periodMonths, installments int, startUnix int64) string {
	caller := requireUser(cur)
	if amount <= 0 {
		panic("amount must be positive")
	}
	if installments < 1 || installments > 240 {
		panic("installments must be between 1 and 240")
	}
	if periodMonths != 1 && periodMonths != 3 && periodMonths != 12 {
		panic("period must be 1, 3 or 12 months")
	}
	total := amount * int64(installments)
	requireSend(total)
	if code == "" {
		code = makeCode("plan:" + caller.String())
	}
	validateCode(code)
	if startUnix <= 0 {
		startUnix = time.Now().Unix()
	}
	g := &Gift{
		Kind:         kindPlan,
		Sender:       caller,
		Recipient:    parseRecipient(recipient),
		Code:         code,
		Title:        title,
		Theme:        theme,
		Amount:       amount,
		Total:        total,
		Remaining:    total,
		PeriodMonths: periodMonths,
		Installments: installments,
		NextDue:      startUnix,
	}
	return save(g)
}

func addMonths(unix int64, months int) int64 {
	return time.Unix(unix, 0).AddDate(0, months, 0).Unix()
}

// Claim pays one installment to the caller. For an instant gift the envelope
// is marked claimed; for a plan the next due date is advanced by its period.
func Claim(cur realm, code string) string {
	caller := requireUser(cur)
	id, ok := codes[code]
	if !ok {
		panic("unknown code")
	}
	g := gifts[id]
	if g == nil {
		panic("unknown gift")
	}
	if g.Canceled {
		panic("gift was canceled")
	}
	var zero address
	if g.Recipient != zero && g.Recipient != caller {
		panic("not the recipient")
	}

	if g.Kind == kindInstant {
		if g.Claimed {
			panic("already claimed")
		}
		g.Claimed = true
		g.Remaining = 0
		pay(cur, caller, g.Amount)
		return g.ID
	}

	if g.Paid >= g.Installments {
		panic("plan completed")
	}
	if time.Now().Unix() < g.NextDue {
		panic("not due yet")
	}
	g.Paid++
	g.Remaining -= g.Amount
	g.NextDue = addMonths(g.NextDue, g.PeriodMonths)
	pay(cur, caller, g.Amount)
	return g.ID
}

// Cancel refunds all unclaimed funds to the original sender.
func Cancel(cur realm, id string) string {
	caller := requireUser(cur)
	g := gifts[id]
	if g == nil {
		panic("unknown gift")
	}
	if g.Sender != caller {
		panic("only the sender can cancel")
	}
	if g.Canceled {
		panic("already canceled")
	}
	remaining := g.Remaining
	if remaining <= 0 {
		panic("nothing to refund")
	}
	g.Canceled = true
	g.Remaining = 0
	pay(cur, caller, remaining)
	return g.ID
}

// ---- read-only helpers, callable through vm/qeval ----

func Ping() string {
	return version
}

func Count() int {
	return len(order)
}

func IDAt(i int) string {
	if i < 0 || i >= len(order) {
		return ""
	}
	return order[i]
}

func clean(s string) string {
	s = strings.ReplaceAll(s, "|", "&#124;")
	return strings.ReplaceAll(s, ";", "&#59;")
}

func flag(v bool) string {
	if v {
		return "1"
	}
	return "0"
}

func recipientText(a address) string {
	var zero address
	if a == zero {
		return ""
	}
	return a.String()
}

// GetGift returns pipe-separated fields:
// id|kind|sender|recipient|code|title|theme|amount|remaining|period|installments|paid|nextDue|createdAt|claimed|canceled
func GetGift(id string) string {
	g := gifts[id]
	if g == nil {
		return ""
	}
	parts := []string{
		g.ID,
		g.Kind,
		g.Sender.String(),
		recipientText(g.Recipient),
		g.Code,
		clean(g.Title),
		clean(g.Theme),
		strconv.FormatInt(g.Amount, 10),
		strconv.FormatInt(g.Remaining, 10),
		strconv.Itoa(g.PeriodMonths),
		strconv.Itoa(g.Installments),
		strconv.Itoa(g.Paid),
		strconv.FormatInt(g.NextDue, 10),
		strconv.FormatInt(g.CreatedAt, 10),
		flag(g.Claimed),
		flag(g.Canceled),
	}
	return strings.Join(parts, "|")
}

func GetByCode(code string) string {
	id, ok := codes[code]
	if !ok {
		return ""
	}
	return GetGift(id)
}

// Render gives gnoweb a usable, text-only dashboard for the realm.
func Render(path string) string {
	out := "# WarmPocket\n\n"
	out += "Gift envelopes and recurring care plans, settled on chain.\n\n"

	if strings.HasPrefix(path, "gift/") {
		id := strings.TrimPrefix(path, "gift/")
		raw := GetGift(id)
		if raw == "" {
			return out + "Gift not found.\n"
		}
		f := strings.Split(raw, "|")
		out += "## " + f[5] + "\n\n"
		out += "- Kind: " + f[1] + "\n"
		out += "- Theme: " + f[6] + "\n"
		out += "- Amount per claim: " + f[7] + " ugnot\n"
		out += "- Remaining: " + f[8] + " ugnot\n"
		out += "- Paid: " + f[11] + "/" + f[10] + "\n"
		out += "- Claimed: " + f[14] + " / Canceled: " + f[15] + "\n"
		return out
	}

	out += "Total gifts: " + strconv.Itoa(Count()) + "\n\n"
	if Count() == 0 {
		return out + "No gift yet. Create the first one from the web app.\n"
	}
	start := Count() - 20
	if start < 0 {
		start = 0
	}
	for i := start; i < Count(); i++ {
		f := strings.Split(GetGift(IDAt(i)), "|")
		status := "open"
		if f[15] == "1" {
			status = "canceled"
		} else if f[1] == kindInstant && f[14] == "1" {
			status = "claimed"
		} else if f[1] == kindPlan {
			status = f[11] + "/" + f[10] + " paid"
		}
		out += "- [" + f[0] + "](" + path + "gift/" + f[0] + ") " + f[5] + " — " + f[7] + " ugnot — " + status + "\n"
	}
	return out
}