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/g1pzw2mc795ahjumtmkxjyxhz0awklc3apyfpw9e/heirrealm/v2"
gno = "0.9"

[addpkg]
  creator = "g1pzw2mc795ahjumtmkxjyxhz0awklc3apyfpw9e"
  height = 1423166
  max_deposit = "60000000ugnot"

heirrealm.gno

// Package heirrealm is a dead-man's-switch inheritance realm for Gno.land.
//
// The problem: a Gno holder dies, loses their keys, or simply disappears,
// and their GNOT is locked forever. No will, no custodian, no recovery.
//
// HeirRealm lets the holder name a beneficiary and a check-in window.
// As long as the holder checks in before the window expires, nothing
// happens. Miss the window and anyone — an incentivised keeper, not a
// trusted custodian — can trigger the release. The keeper earns a small
// fee for doing the work; the rest goes to the beneficiary. The keeper
// can never release early, never change the beneficiary, and never
// touch the funds before the deadline.
//
// Design choices (all documented in README.md):
//   - Denomination is ugnot only (GNOT). One coin type keeps the
//     accounting auditable.
//   - Keeper fee is 2% (200 basis points) of the vault balance at
//     release time. Integer math: fee = balance * 200 / 10000.
//     For balances under 50 ugnot the fee rounds to 0.
//   - Check-in interval must be between 60 seconds (1 minute, so the
//     60-second demo can fast-forward) and 365 days.
//   - CheckIn only works BEFORE the deadline. Once the deadline has
//     passed, the vault is claimable and the owner can no longer
//     rescue it by checking in — that is the whole point of a
//     dead-man's switch.
//   - Cancel (owner refund) only works BEFORE the deadline and only
//     while the vault is still active. After expiry the funds belong
//     to the beneficiary.
//   - The keeper may not be the owner or the beneficiary.
//   - Time is block time: time.Now(), the same timelock primitive
//     used by examples/gno.land/r/demo/defi/atomicswap in gnolang/gno.
//
// Caller authentication follows the atomicswap pattern: payment
// functions require cur.Previous().IsUserCall() and read the attached
// coins from unsafe.OriginSend(). A realm in the middle of a call
// chain cannot fake a payment, because OriginSend describes the
// transaction envelope and IsUserCall rejects non-wallet callers.
//
// Social/voice recovery is intentionally NOT in this MVP. It is listed
// as a future extension in README.md.
package heirrealm

import (
	"chain"
	"chain/banker"
	"chain/runtime/unsafe"
	"strconv"
	"time"

	"gno.land/p/nt/avl/v0"
)

// Denom is the only coin this realm accepts: ugnot (GNOT).
const Denom = "ugnot"

// KeeperFeeBPS is the keeper's cut of a released vault, in basis
// points. 200 bps = 2%.
const KeeperFeeBPS = 200

// MinCheckInIntervalSeconds is the shortest check-in window: 60s.
// It exists so the demo can fast-forward through a full lifecycle
// in about a minute.
const MinCheckInIntervalSeconds = 60

// MaxCheckInIntervalSeconds is the longest check-in window: 365 days.
const MaxCheckInIntervalSeconds = 365 * 24 * 60 * 60

// ProductionGracePeriodSeconds is the production default grace period
// (7 days = 604,800s) before an expired vault becomes claimable.
const ProductionGracePeriodSeconds = 7 * 24 * 60 * 60

// GracePeriodSeconds is the grace window after Deadline during which
// TriggerRelease is still blocked and only the owner's Heartbeat can
// revive the vault: 60s for demo, 7 days in production.
const GracePeriodSeconds = 60 // 60s for demo, 7 days in production

var (
	vaults    avl.Tree // vault ID (string) -> *Vault
	nextVault int
)

// Vault is one inheritance vault.
type Vault struct {
	ID          int
	Owner       address
	Beneficiary address
	Balance     int64 // ugnot held by this vault
	Interval    int64 // check-in window, in seconds
	GracePeriod int64 // post-deadline grace window, in seconds
	Deadline    time.Time
	CreatedAt   time.Time
	Released    bool
	Cancelled   bool
	Keeper      address   // set on release; zero address until then
	ReleasedAt  time.Time // zero until released
}

// GraceEnd returns the end of the vault's grace period (Deadline + GracePeriod).
// Keepers can only call TriggerRelease strictly after GraceEnd.
func (v Vault) GraceEnd() time.Time {
	gp := v.GracePeriod
	if gp <= 0 {
		gp = GracePeriodSeconds
	}
	return v.Deadline.Add(time.Duration(gp) * time.Second)
}

// Status returns a human-readable state for the vault.
func (v Vault) Status() string {
	if v.Released {
		return "released"
	}
	if v.Cancelled {
		return "cancelled"
	}
	now := time.Now()
	if now.After(v.GraceEnd()) {
		return "expired — awaiting keeper"
	}
	if now.After(v.Deadline) {
		return "in grace period — awaiting heartbeat"
	}
	return "active"
}

// KeeperFee returns the keeper's cut of the vault balance at release.
func (v Vault) KeeperFee() int64 {
	return v.Balance * KeeperFeeBPS / 10000
}

// BeneficiaryShare returns what the beneficiary receives at release.
func (v Vault) BeneficiaryShare() int64 {
	return v.Balance - v.KeeperFee()
}

// CreateVault opens a vault for beneficiary with a check-in window of
// intervalSeconds. Attach the initial deposit with -send ugnot.
//
// The caller becomes the owner. The beneficiary must not be the owner.
// The deposit must be more than 0 ugnot.
func CreateVault(cur realm, beneficiary address, intervalSeconds int64) int {
	if !cur.Previous().IsUserCall() {
		panic("heirrealm: only direct wallet calls may create a vault")
	}
	owner := cur.Previous().Address()
	if beneficiary == "" {
		panic("heirrealm: beneficiary must not be empty")
	}
	if beneficiary == owner {
		panic("heirrealm: beneficiary must not be the owner")
	}
	if intervalSeconds < MinCheckInIntervalSeconds {
		panic("heirrealm: check-in interval too short (minimum 60 seconds)")
	}
	if intervalSeconds > MaxCheckInIntervalSeconds {
		panic("heirrealm: check-in interval too long (maximum 365 days)")
	}
	sent := unsafe.OriginSend()
	if len(sent) == 0 || sent.AmountOf(Denom) <= 0 {
		panic("heirrealm: attach an initial deposit in ugnot with -send")
	}
	if len(sent) != 1 || sent[0].Denom != Denom {
		panic("heirrealm: only ugnot is accepted")
	}
	amount := sent.AmountOf(Denom)
	now := time.Now()
	nextVault++
	v := &Vault{
		ID:          nextVault,
		Owner:       owner,
		Beneficiary: beneficiary,
		Balance:     amount,
		Interval:    intervalSeconds,
		GracePeriod: GracePeriodSeconds,
		Deadline:    now.Add(time.Duration(intervalSeconds) * time.Second),
		CreatedAt:   now,
	}
	vaults.Set(strconv.Itoa(v.ID), v)
	return v.ID
}

// Deposit tops up an active vault. Only the owner may deposit, and
// only ugnot is accepted. The check-in timer is NOT reset by a
// deposit — only CheckIn resets it.
func Deposit(cur realm, id int) int64 {
	if !cur.Previous().IsUserCall() {
		panic("heirrealm: only direct wallet calls may deposit")
	}
	v := mustGetVault(id)
	caller := cur.Previous().Address()
	if caller != v.Owner {
		panic("heirrealm: only the vault owner may deposit")
	}
	requireActive(v)
	sent := unsafe.OriginSend()
	if len(sent) == 0 || sent.AmountOf(Denom) <= 0 {
		panic("heirrealm: attach ugnot with -send")
	}
	if len(sent) != 1 || sent[0].Denom != Denom {
		panic("heirrealm: only ugnot is accepted")
	}
	v.Balance += sent.AmountOf(Denom)
	vaults.Set(strconv.Itoa(v.ID), v)
	return v.Balance
}

// CheckIn resets the vault's deadline to now + the check-in interval.
// Only the owner may check in, only while the vault is active, and
// only BEFORE the deadline has passed. After the deadline the vault
// is claimable and checking in can no longer save it.
func CheckIn(cur realm, id int) time.Time {
	v := mustGetVault(id)
	caller := cur.Previous().Address()
	if caller != v.Owner {
		panic("heirrealm: only the vault owner may check in")
	}
	requireActive(v)
	if !time.Now().Before(v.Deadline) {
		panic("heirrealm: deadline has passed, check-in is too late")
	}
	v.Deadline = time.Now().Add(time.Duration(v.Interval) * time.Second)
	vaults.Set(strconv.Itoa(v.ID), v)
	return v.Deadline
}

// Heartbeat revives a vault during its post-deadline grace period and
// resets its deadline to now + the check-in interval, identically to
// CheckIn. Only the vault owner may call Heartbeat, and only strictly
// during the grace window (after Deadline, before Deadline + GracePeriod).
func Heartbeat(cur realm, id int) time.Time {
	v := mustGetVault(id)
	caller := cur.Previous().Address()
	if caller != v.Owner {
		panic("heirrealm: only the vault owner may send a heartbeat")
	}
	requireActive(v)
	now := time.Now()
	if !now.After(v.Deadline) {
		panic("heirrealm: deadline has not passed yet, use CheckIn before the deadline")
	}
	if !now.Before(v.GraceEnd()) {
		panic("heirrealm: grace period has ended, heartbeat is too late")
	}
	v.Deadline = now.Add(time.Duration(v.Interval) * time.Second)
	vaults.Set(strconv.Itoa(v.ID), v)
	return v.Deadline
}

// TriggerRelease releases an expired vault once both its check-in
// deadline AND its post-deadline grace period have passed. Anyone may
// call it — that is the keeper's job — but the keeper may not be the
// owner or the beneficiary. The keeper earns 2% of the balance; the
// beneficiary receives the remaining 98%.
func TriggerRelease(cur realm, id int) (beneficiaryShare int64, keeperFee int64) {
	v := mustGetVault(id)
	keeper := cur.Previous().Address()
	if keeper == "" {
		panic("heirrealm: keeper must not be empty")
	}
	if keeper == v.Owner {
		panic("heirrealm: the owner cannot be the keeper")
	}
	if keeper == v.Beneficiary {
		panic("heirrealm: the beneficiary cannot be the keeper")
	}
	requireActive(v)
	now := time.Now()
	if !now.After(v.Deadline) {
		panic("heirrealm: vault has not expired yet")
	}
	if !now.After(v.GraceEnd()) {
		panic("heirrealm: vault is in grace period, cannot release before deadline + grace")
	}
	keeperFee = v.KeeperFee()
	beneficiaryShare = v.BeneficiaryShare()
	realmAddr := cur.Address()
	banker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	if keeperFee > 0 {
		banker_.SendCoins(realmAddr, keeper, chain.Coins{chain.NewCoin(Denom, keeperFee)})
	}
	if beneficiaryShare > 0 {
		banker_.SendCoins(realmAddr, v.Beneficiary, chain.Coins{chain.NewCoin(Denom, beneficiaryShare)})
	}
	v.Released = true
	v.Keeper = keeper
	v.ReleasedAt = time.Now()
	vaults.Set(strconv.Itoa(v.ID), v)
	return beneficiaryShare, keeperFee
}

// Cancel closes an active vault and refunds the full balance to the
// owner. Only the owner may cancel, and only BEFORE the deadline.
// After expiry the funds belong to the beneficiary and the owner
// can no longer claw them back.
func Cancel(cur realm, id int) int64 {
	v := mustGetVault(id)
	caller := cur.Previous().Address()
	if caller != v.Owner {
		panic("heirrealm: only the vault owner may cancel")
	}
	requireActive(v)
	if !time.Now().Before(v.Deadline) {
		panic("heirrealm: deadline has passed, vault can no longer be cancelled")
	}
	refund := v.Balance
	realmAddr := cur.Address()
	banker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)
	if refund > 0 {
		banker_.SendCoins(realmAddr, v.Owner, chain.Coins{chain.NewCoin(Denom, refund)})
	}
	v.Balance = 0
	v.Cancelled = true
	vaults.Set(strconv.Itoa(v.ID), v)
	return refund
}

// GetVault returns a copy of the vault with the given ID.
// Read-only: callable as a query, no transaction needed.
func GetVault(id int) Vault {
	return *mustGetVault(id)
}

// VaultCount returns the number of vaults ever created.
func VaultCount() int {
	return nextVault
}

// requireActive panics unless the vault is still live.
func requireActive(v *Vault) {
	if v.Released {
		panic("heirrealm: vault already released")
	}
	if v.Cancelled {
		panic("heirrealm: vault already cancelled")
	}
}

// mustGetVault loads a vault by ID or panics.
func mustGetVault(id int) *Vault {
	v := vaults.Get(strconv.Itoa(id))
	if v == nil {
		panic("heirrealm: unknown vault ID")
	}
	return v.(*Vault)
}

heirrealm_test.gno

package heirrealm

import (
	"chain"
	"chain/banker"
	"strconv"
	"strings"
	"testing"
	"time"

	"gno.land/p/nt/avl/v0"
	"gno.land/p/nt/testutils/v0"
	"gno.land/p/nt/uassert/v0"
)

func resetTestState() {
	vaults = avl.Tree{}
	nextVault = 0
}

const testPkgPath = "gno.land/r/g1pzw2mc795ahjumtmkxjyxhz0awklc3apyfpw9e/heirrealm/v2"

// makeVault creates a vault owned by owner for beneficiary with the
// given interval and deposit, funded on the realm so payouts work.
func makeVault(cur realm, t *testing.T, owner, beneficiary address, interval, deposit int64) int {
	pkgAddr := chain.PackageAddress(testPkgPath)
	testing.SetRealm(testing.NewUserRealm(owner))
	testing.SetOriginSend(chain.Coins{{Denom: Denom, Amount: deposit}})
	testing.IssueCoins(pkgAddr, chain.Coins{{Denom: Denom, Amount: deposit}})
	return CreateVault(cross(cur), beneficiary, interval)
}

func TestCreateVault(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner1")
	beneficiary := testutils.TestAddress("beneficiary1")
	id := makeVault(cur, t, owner, beneficiary, 3600, 1000)
	uassert.Equal(t, 1, id)
	uassert.Equal(t, 1, VaultCount())

	v := GetVault(id)
	uassert.Equal(t, owner, v.Owner)
	uassert.Equal(t, beneficiary, v.Beneficiary)
	uassert.Equal(t, int64(1000), v.Balance)
	uassert.Equal(t, int64(3600), v.Interval)
	uassert.Equal(t, "active", v.Status())
	uassert.False(t, v.Released)
	uassert.False(t, v.Cancelled)
	// Deadline is now + 3600s. In tests time.Now() is fixed, so the
	// deadline must be exactly 1h after the fixed test time.
	uassert.True(t, v.Deadline.Equal(time.Now().Add(3600*time.Second)))
	uassert.Equal(t, int64(20), v.KeeperFee()) // 2% of 1000
	uassert.Equal(t, int64(980), v.BeneficiaryShare())
}

func TestCreateVaultGuards(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner2")
	other := testutils.TestAddress("other2")

	// Beneficiary must not be the owner.
	testing.SetRealm(testing.NewUserRealm(owner))
	testing.SetOriginSend(chain.Coins{{Denom: Denom, Amount: 1000}})
	uassert.AbortsContains(t, cur, "must not be the owner", func() {
		CreateVault(cross(cur), owner, 3600)
	})

	// Interval too short (under 60s).
	uassert.AbortsContains(t, cur, "too short", func() {
		CreateVault(cross(cur), other, 30)
	})

	// Interval too long (over 365 days).
	uassert.AbortsContains(t, cur, "too long", func() {
		CreateVault(cross(cur), other, MaxCheckInIntervalSeconds+1)
	})

	// Zero deposit.
	testing.SetOriginSend(chain.Coins{})
	uassert.AbortsContains(t, cur, "initial deposit", func() {
		CreateVault(cross(cur), other, 3600)
	})

	// No vaults were created by the failed calls.
	uassert.Equal(t, 0, VaultCount())
}

func TestDeposit(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner3")
	beneficiary := testutils.TestAddress("beneficiary3")
	other := testutils.TestAddress("other3")
	id := makeVault(cur, t, owner, beneficiary, 3600, 1000)

	// Owner tops up by 500.
	testing.SetRealm(testing.NewUserRealm(owner))
	testing.SetOriginSend(chain.Coins{{Denom: Denom, Amount: 500}})
	balance := Deposit(cross(cur), id)
	uassert.Equal(t, int64(1500), balance)
	uassert.Equal(t, int64(1500), GetVault(id).Balance)

	// A non-owner cannot deposit.
	testing.SetRealm(testing.NewUserRealm(other))
	testing.SetOriginSend(chain.Coins{{Denom: Denom, Amount: 500}})
	uassert.AbortsContains(t, cur, "only the vault owner may deposit", func() {
		Deposit(cross(cur), id)
	})
	uassert.Equal(t, int64(1500), GetVault(id).Balance)

	// A zero deposit fails.
	testing.SetRealm(testing.NewUserRealm(owner))
	testing.SetOriginSend(chain.Coins{})
	uassert.AbortsContains(t, cur, "attach ugnot", func() {
		Deposit(cross(cur), id)
	})
}

func TestCheckInResetsTimer(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner4")
	beneficiary := testutils.TestAddress("beneficiary4")
	other := testutils.TestAddress("other4")
	id := makeVault(cur, t, owner, beneficiary, 3600, 1000)

	// Simulate a nearly-expired vault, then check in.
	v := mustGetVault(id)
	v.Deadline = time.Now().Add(10 * time.Second)
	vaults.Set("1", v)
	oldDeadline := v.Deadline

	testing.SetRealm(testing.NewUserRealm(owner))
	newDeadline := CheckIn(cross(cur), id)
	uassert.True(t, newDeadline.After(oldDeadline))
	uassert.True(t, newDeadline.Equal(time.Now().Add(3600*time.Second)))
	uassert.Equal(t, "active", GetVault(id).Status())

	// A non-owner cannot check in.
	testing.SetRealm(testing.NewUserRealm(other))
	uassert.AbortsContains(t, cur, "only the vault owner may check in", func() {
		CheckIn(cross(cur), id)
	})

	// Checking in after the deadline is too late.
	v = mustGetVault(id)
	v.Deadline = time.Now().Add(-1 * time.Hour)
	vaults.Set("1", v)
	testing.SetRealm(testing.NewUserRealm(owner))
	uassert.AbortsContains(t, cur, "too late", func() {
		CheckIn(cross(cur), id)
	})
}

func TestEarlyReleaseFails(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner5")
	beneficiary := testutils.TestAddress("beneficiary5")
	keeper := testutils.TestAddress("keeper5")
	id := makeVault(cur, t, owner, beneficiary, 3600, 1000)

	testing.SetRealm(testing.NewUserRealm(keeper))
	uassert.AbortsContains(t, cur, "has not expired yet", func() {
		TriggerRelease(cross(cur), id)
	})
	uassert.Equal(t, "active", GetVault(id).Status())
	uassert.False(t, GetVault(id).Released)
}

func TestExpiredReleaseSplits(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner6")
	beneficiary := testutils.TestAddress("beneficiary6")
	keeper := testutils.TestAddress("keeper6")
	id := makeVault(cur, t, owner, beneficiary, 3600, 1000)

	// Fast-forward: move the deadline into the past.
	v := mustGetVault(id)
	v.Deadline = time.Now().Add(-1 * time.Hour)
	vaults.Set("1", v)
	uassert.Equal(t, "expired — awaiting keeper", GetVault(id).Status())

	testing.SetRealm(testing.NewUserRealm(keeper))
	share, fee := TriggerRelease(cross(cur), id)
	uassert.Equal(t, int64(980), share)
	uassert.Equal(t, int64(20), fee)

	// Balances on chain: beneficiary 98%, keeper 2%.
	banker_ := banker.NewReadonlyBanker()
	uassert.Equal(t, int64(980), banker_.GetCoin(beneficiary, Denom))
	uassert.Equal(t, int64(20), banker_.GetCoin(keeper, Denom))

	// Vault is marked released, with the keeper recorded.
	released := GetVault(id)
	uassert.True(t, released.Released)
	uassert.Equal(t, keeper, released.Keeper)
	uassert.Equal(t, "released", released.Status())

	// Double-release fails.
	uassert.AbortsContains(t, cur, "already released", func() {
		TriggerRelease(cross(cur), id)
	})
	// Check-in after release fails too.
	testing.SetRealm(testing.NewUserRealm(owner))
	uassert.AbortsContains(t, cur, "already released", func() {
		CheckIn(cross(cur), id)
	})
}

func TestKeeperCannotBeOwnerOrBeneficiary(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner7")
	beneficiary := testutils.TestAddress("beneficiary7")
	id := makeVault(cur, t, owner, beneficiary, 3600, 1000)

	v := mustGetVault(id)
	v.Deadline = time.Now().Add(-1 * time.Hour)
	vaults.Set("1", v)

	testing.SetRealm(testing.NewUserRealm(owner))
	uassert.AbortsContains(t, cur, "owner cannot be the keeper", func() {
		TriggerRelease(cross(cur), id)
	})
	testing.SetRealm(testing.NewUserRealm(beneficiary))
	uassert.AbortsContains(t, cur, "beneficiary cannot be the keeper", func() {
		TriggerRelease(cross(cur), id)
	})
	uassert.False(t, GetVault(id).Released)
}

func TestCancelRefunds(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner8")
	beneficiary := testutils.TestAddress("beneficiary8")
	other := testutils.TestAddress("other8")
	id := makeVault(cur, t, owner, beneficiary, 3600, 500)

	// A non-owner cannot cancel.
	testing.SetRealm(testing.NewUserRealm(other))
	uassert.AbortsContains(t, cur, "only the vault owner may cancel", func() {
		Cancel(cross(cur), id)
	})

	// Owner cancels before expiry: full refund.
	testing.SetRealm(testing.NewUserRealm(owner))
	refund := Cancel(cross(cur), id)
	uassert.Equal(t, int64(500), refund)
	banker_ := banker.NewReadonlyBanker()
	uassert.Equal(t, int64(500), banker_.GetCoin(owner, Denom))
	cancelled := GetVault(id)
	uassert.True(t, cancelled.Cancelled)
	uassert.Equal(t, int64(0), cancelled.Balance)
	uassert.Equal(t, "cancelled", cancelled.Status())

	// Nothing more can happen to a cancelled vault.
	// (Call as a third party: as the owner, TriggerRelease would
	// abort on the keeper check first, which is also correct.)
	testing.SetRealm(testing.NewUserRealm(other))
	uassert.AbortsContains(t, cur, "already cancelled", func() {
		TriggerRelease(cross(cur), id)
	})
	testing.SetRealm(testing.NewUserRealm(owner))
	uassert.AbortsContains(t, cur, "already cancelled", func() {
		CheckIn(cross(cur), id)
	})

	// Cancelling after the deadline is refused: after expiry the
	// funds belong to the beneficiary.
	id2 := makeVault(cur, t, owner, beneficiary, 3600, 500)
	v := mustGetVault(id2)
	v.Deadline = time.Now().Add(-1 * time.Hour)
	vaults.Set("2", v)
	uassert.AbortsContains(t, cur, "no longer be cancelled", func() {
		Cancel(cross(cur), id2)
	})
}

func TestRender(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner9")
	beneficiary := testutils.TestAddress("beneficiary9")
	id := makeVault(cur, t, owner, beneficiary, 3600, 1000)

	home := Render("")
	uassert.True(t, strings.Contains(home, "# HeirRealm"))
	uassert.True(t, strings.Contains(home, "Vault #1"))
	uassert.True(t, strings.Contains(home, "active"))

	detail := Render("1")
	uassert.True(t, strings.Contains(detail, "Vault #1"))
	uassert.True(t, strings.Contains(detail, "1000 ugnot"))

	uassert.Equal(t, "# HeirRealm\n\nUnknown vault.", Render("999"))
	_ = id
}

func TestTriggerReleaseDuringGraceFails(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner10")
	beneficiary := testutils.TestAddress("beneficiary10")
	keeper := testutils.TestAddress("keeper10")
	id := makeVault(cur, t, owner, beneficiary, 60, 1000)

	// Move deadline 30s into the past: past deadline, still inside 60s grace period.
	v := mustGetVault(id)
	v.Deadline = time.Now().Add(-30 * time.Second)
	vaults.Set(strconv.Itoa(id), v)

	uassert.Equal(t, "in grace period — awaiting heartbeat", GetVault(id).Status())

	testing.SetRealm(testing.NewUserRealm(keeper))
	uassert.AbortsContains(t, cur, "grace period", func() {
		TriggerRelease(cross(cur), id)
	})
	uassert.False(t, GetVault(id).Released)
}

func TestHeartbeatDuringGraceRevivesVault(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner11")
	beneficiary := testutils.TestAddress("beneficiary11")
	id := makeVault(cur, t, owner, beneficiary, 60, 1000)

	// Move deadline 30s into the past (inside the 60s grace period).
	v := mustGetVault(id)
	v.Deadline = time.Now().Add(-30 * time.Second)
	vaults.Set(strconv.Itoa(id), v)
	uassert.Equal(t, "in grace period — awaiting heartbeat", GetVault(id).Status())

	testing.SetRealm(testing.NewUserRealm(owner))
	newDeadline := Heartbeat(cross(cur), id)
	uassert.True(t, newDeadline.Equal(time.Now().Add(60*time.Second)))

	revived := GetVault(id)
	uassert.Equal(t, "active", revived.Status())
	uassert.True(t, revived.Deadline.Equal(time.Now().Add(60*time.Second)))
	uassert.Equal(t, int64(1000), revived.Balance)
}

func TestHeartbeatBeforeDeadlineFails(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner12")
	beneficiary := testutils.TestAddress("beneficiary12")
	id := makeVault(cur, t, owner, beneficiary, 60, 1000)

	testing.SetRealm(testing.NewUserRealm(owner))
	uassert.AbortsContains(t, cur, "deadline has not passed", func() {
		Heartbeat(cross(cur), id)
	})
}

func TestHeartbeatAfterGraceEndsFails(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner13")
	beneficiary := testutils.TestAddress("beneficiary13")
	id := makeVault(cur, t, owner, beneficiary, 60, 1000)

	// Move deadline past deadline + 60s grace period (61s ago -> grace ended 1s ago).
	v := mustGetVault(id)
	v.Deadline = time.Now().Add(-time.Duration(GracePeriodSeconds+1) * time.Second)
	vaults.Set(strconv.Itoa(id), v)
	uassert.Equal(t, "expired — awaiting keeper", GetVault(id).Status())

	testing.SetRealm(testing.NewUserRealm(owner))
	uassert.AbortsContains(t, cur, "grace period has ended", func() {
		Heartbeat(cross(cur), id)
	})
}

func TestHeartbeatNonOwnerFails(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner14")
	beneficiary := testutils.TestAddress("beneficiary14")
	stranger := testutils.TestAddress("stranger14")
	id := makeVault(cur, t, owner, beneficiary, 60, 1000)

	// Place vault inside the 60s grace period.
	v := mustGetVault(id)
	v.Deadline = time.Now().Add(-30 * time.Second)
	vaults.Set(strconv.Itoa(id), v)

	testing.SetRealm(testing.NewUserRealm(stranger))
	uassert.AbortsContains(t, cur, "only the vault owner", func() {
		Heartbeat(cross(cur), id)
	})

	testing.SetRealm(testing.NewUserRealm(beneficiary))
	uassert.AbortsContains(t, cur, "only the vault owner", func() {
		Heartbeat(cross(cur), id)
	})
}

func TestTriggerReleaseAfterGraceSplits(cur realm, t *testing.T) {
	defer resetTestState()
	owner := testutils.TestAddress("owner15")
	beneficiary := testutils.TestAddress("beneficiary15")
	keeper := testutils.TestAddress("keeper15")
	id := makeVault(cur, t, owner, beneficiary, 60, 1000)

	// Move deadline past deadline + 60s grace period.
	v := mustGetVault(id)
	v.Deadline = time.Now().Add(-time.Duration(GracePeriodSeconds+5) * time.Second)
	vaults.Set(strconv.Itoa(id), v)
	uassert.Equal(t, "expired — awaiting keeper", GetVault(id).Status())

	testing.SetRealm(testing.NewUserRealm(keeper))
	share, fee := TriggerRelease(cross(cur), id)
	uassert.Equal(t, int64(980), share)
	uassert.Equal(t, int64(20), fee)

	banker_ := banker.NewReadonlyBanker()
	uassert.Equal(t, int64(980), banker_.GetCoin(beneficiary, Denom))
	uassert.Equal(t, int64(20), banker_.GetCoin(keeper, Denom))
	uassert.Equal(t, "released", GetVault(id).Status())
}

render.gno

package heirrealm

import (
	"strconv"
	"time"

	"gno.land/p/nt/ufmt/v0"
)

// Render is the gnoweb homepage for the realm. It lists every vault
// with its owner, beneficiary, balance, deadline and status, plus a
// short how-to. A single vault can be viewed at /<id>.
func Render(path string) string {
	if path != "" {
		id, err := strconv.Atoi(path)
		if err != nil {
			return "# HeirRealm\n\nUnknown vault."
		}
		v := vaults.Get(strconv.Itoa(id))
		if v == nil {
			return "# HeirRealm\n\nUnknown vault."
		}
		return renderVault(v.(*Vault))
	}
	out := "# HeirRealm — dead-man's switch for Gno\n\n"
	out += "Name a beneficiary and a check-in window. Check in before the window ends and nothing happens. "
	out += "Miss the window and any keeper can trigger the release: the beneficiary gets 98%, the keeper earns a 2% fee. "
	out += "No custodian, no will, no trusted third party.\n\n"
	out += "## Vaults\n\n"
	if nextVault == 0 {
		out += "No vaults yet. Create one with `CreateVault(beneficiary, intervalSeconds)` and attach ugnot with `-send`.\n"
		return out
	}
	for i := 1; i <= nextVault; i++ {
		v := vaults.Get(strconv.Itoa(i))
		if v == nil {
			continue
		}
		vv := v.(*Vault)
		out += ufmt.Sprintf("- Vault #%d — %s — balance %d ugnot — deadline %s\n",
			vv.ID, vv.Status(), vv.Balance, vv.Deadline.Format(time.RFC3339))
	}
	out += "\n## How it works\n\n"
	out += "1. `CreateVault(beneficiary, intervalSeconds)` + `-send` ugnot — you are the owner.\n"
	out += "2. `CheckIn(vaultID)` before the deadline to reset the timer.\n"
	out += "3. `Heartbeat(vaultID)` during the post-deadline grace period to revive the vault and reset the deadline (owner only).\n"
	out += "4. `Deposit(vaultID)` + `-send` ugnot to top up (owner only, timer unchanged).\n"
	out += "5. After deadline + grace period, anyone except the owner or beneficiary calls `TriggerRelease(vaultID)` and earns 2%.\n"
	out += "6. `Cancel(vaultID)` refunds the owner in full — owner only, before the deadline.\n"
	return out
}

func renderVault(v *Vault) string {
	out := ufmt.Sprintf("# HeirRealm — Vault #%d\n\n", v.ID)
	out += ufmt.Sprintf("- Status: %s\n", v.Status())
	out += ufmt.Sprintf("- Owner: %s\n", v.Owner)
	out += ufmt.Sprintf("- Beneficiary: %s\n", v.Beneficiary)
	out += ufmt.Sprintf("- Balance: %d ugnot\n", v.Balance)
	out += ufmt.Sprintf("- Check-in interval: %d seconds\n", v.Interval)
	out += ufmt.Sprintf("- Deadline: %s\n", v.Deadline.Format(time.RFC3339))
	out += ufmt.Sprintf("- Grace period ends: %s (%d seconds)\n", v.GraceEnd().Format(time.RFC3339), v.GracePeriod)
	out += ufmt.Sprintf("- Keeper fee at release: %d ugnot (2%%)\n", v.KeeperFee())
	out += ufmt.Sprintf("- Beneficiary share at release: %d ugnot (98%%)\n", v.BeneficiaryShare())
	if v.Released {
		out += ufmt.Sprintf("- Released by keeper: %s at %s\n", v.Keeper, v.ReleasedAt.Format(time.RFC3339))
	}
	return out
}