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.

heirrealm.gno

11.42 Kb · 345 lines
  1// Package heirrealm is a dead-man's-switch inheritance realm for Gno.land.
  2//
  3// The problem: a Gno holder dies, loses their keys, or simply disappears,
  4// and their GNOT is locked forever. No will, no custodian, no recovery.
  5//
  6// HeirRealm lets the holder name a beneficiary and a check-in window.
  7// As long as the holder checks in before the window expires, nothing
  8// happens. Miss the window and anyone — an incentivised keeper, not a
  9// trusted custodian — can trigger the release. The keeper earns a small
 10// fee for doing the work; the rest goes to the beneficiary. The keeper
 11// can never release early, never change the beneficiary, and never
 12// touch the funds before the deadline.
 13//
 14// Design choices (all documented in README.md):
 15//   - Denomination is ugnot only (GNOT). One coin type keeps the
 16//     accounting auditable.
 17//   - Keeper fee is 2% (200 basis points) of the vault balance at
 18//     release time. Integer math: fee = balance * 200 / 10000.
 19//     For balances under 50 ugnot the fee rounds to 0.
 20//   - Check-in interval must be between 60 seconds (1 minute, so the
 21//     60-second demo can fast-forward) and 365 days.
 22//   - CheckIn only works BEFORE the deadline. Once the deadline has
 23//     passed, the vault is claimable and the owner can no longer
 24//     rescue it by checking in — that is the whole point of a
 25//     dead-man's switch.
 26//   - Cancel (owner refund) only works BEFORE the deadline and only
 27//     while the vault is still active. After expiry the funds belong
 28//     to the beneficiary.
 29//   - The keeper may not be the owner or the beneficiary.
 30//   - Time is block time: time.Now(), the same timelock primitive
 31//     used by examples/gno.land/r/demo/defi/atomicswap in gnolang/gno.
 32//
 33// Caller authentication follows the atomicswap pattern: payment
 34// functions require cur.Previous().IsUserCall() and read the attached
 35// coins from unsafe.OriginSend(). A realm in the middle of a call
 36// chain cannot fake a payment, because OriginSend describes the
 37// transaction envelope and IsUserCall rejects non-wallet callers.
 38//
 39// Social/voice recovery is intentionally NOT in this MVP. It is listed
 40// as a future extension in README.md.
 41package heirrealm
 42
 43import (
 44	"chain"
 45	"chain/banker"
 46	"chain/runtime/unsafe"
 47	"strconv"
 48	"time"
 49
 50	"gno.land/p/nt/avl/v0"
 51)
 52
 53// Denom is the only coin this realm accepts: ugnot (GNOT).
 54const Denom = "ugnot"
 55
 56// KeeperFeeBPS is the keeper's cut of a released vault, in basis
 57// points. 200 bps = 2%.
 58const KeeperFeeBPS = 200
 59
 60// MinCheckInIntervalSeconds is the shortest check-in window: 60s.
 61// It exists so the demo can fast-forward through a full lifecycle
 62// in about a minute.
 63const MinCheckInIntervalSeconds = 60
 64
 65// MaxCheckInIntervalSeconds is the longest check-in window: 365 days.
 66const MaxCheckInIntervalSeconds = 365 * 24 * 60 * 60
 67
 68// ProductionGracePeriodSeconds is the production default grace period
 69// (7 days = 604,800s) before an expired vault becomes claimable.
 70const ProductionGracePeriodSeconds = 7 * 24 * 60 * 60
 71
 72// GracePeriodSeconds is the grace window after Deadline during which
 73// TriggerRelease is still blocked and only the owner's Heartbeat can
 74// revive the vault: 60s for demo, 7 days in production.
 75const GracePeriodSeconds = 60 // 60s for demo, 7 days in production
 76
 77var (
 78	vaults    avl.Tree // vault ID (string) -> *Vault
 79	nextVault int
 80)
 81
 82// Vault is one inheritance vault.
 83type Vault struct {
 84	ID          int
 85	Owner       address
 86	Beneficiary address
 87	Balance     int64 // ugnot held by this vault
 88	Interval    int64 // check-in window, in seconds
 89	GracePeriod int64 // post-deadline grace window, in seconds
 90	Deadline    time.Time
 91	CreatedAt   time.Time
 92	Released    bool
 93	Cancelled   bool
 94	Keeper      address   // set on release; zero address until then
 95	ReleasedAt  time.Time // zero until released
 96}
 97
 98// GraceEnd returns the end of the vault's grace period (Deadline + GracePeriod).
 99// Keepers can only call TriggerRelease strictly after GraceEnd.
100func (v Vault) GraceEnd() time.Time {
101	gp := v.GracePeriod
102	if gp <= 0 {
103		gp = GracePeriodSeconds
104	}
105	return v.Deadline.Add(time.Duration(gp) * time.Second)
106}
107
108// Status returns a human-readable state for the vault.
109func (v Vault) Status() string {
110	if v.Released {
111		return "released"
112	}
113	if v.Cancelled {
114		return "cancelled"
115	}
116	now := time.Now()
117	if now.After(v.GraceEnd()) {
118		return "expired — awaiting keeper"
119	}
120	if now.After(v.Deadline) {
121		return "in grace period — awaiting heartbeat"
122	}
123	return "active"
124}
125
126// KeeperFee returns the keeper's cut of the vault balance at release.
127func (v Vault) KeeperFee() int64 {
128	return v.Balance * KeeperFeeBPS / 10000
129}
130
131// BeneficiaryShare returns what the beneficiary receives at release.
132func (v Vault) BeneficiaryShare() int64 {
133	return v.Balance - v.KeeperFee()
134}
135
136// CreateVault opens a vault for beneficiary with a check-in window of
137// intervalSeconds. Attach the initial deposit with -send ugnot.
138//
139// The caller becomes the owner. The beneficiary must not be the owner.
140// The deposit must be more than 0 ugnot.
141func CreateVault(cur realm, beneficiary address, intervalSeconds int64) int {
142	if !cur.Previous().IsUserCall() {
143		panic("heirrealm: only direct wallet calls may create a vault")
144	}
145	owner := cur.Previous().Address()
146	if beneficiary == "" {
147		panic("heirrealm: beneficiary must not be empty")
148	}
149	if beneficiary == owner {
150		panic("heirrealm: beneficiary must not be the owner")
151	}
152	if intervalSeconds < MinCheckInIntervalSeconds {
153		panic("heirrealm: check-in interval too short (minimum 60 seconds)")
154	}
155	if intervalSeconds > MaxCheckInIntervalSeconds {
156		panic("heirrealm: check-in interval too long (maximum 365 days)")
157	}
158	sent := unsafe.OriginSend()
159	if len(sent) == 0 || sent.AmountOf(Denom) <= 0 {
160		panic("heirrealm: attach an initial deposit in ugnot with -send")
161	}
162	if len(sent) != 1 || sent[0].Denom != Denom {
163		panic("heirrealm: only ugnot is accepted")
164	}
165	amount := sent.AmountOf(Denom)
166	now := time.Now()
167	nextVault++
168	v := &Vault{
169		ID:          nextVault,
170		Owner:       owner,
171		Beneficiary: beneficiary,
172		Balance:     amount,
173		Interval:    intervalSeconds,
174		GracePeriod: GracePeriodSeconds,
175		Deadline:    now.Add(time.Duration(intervalSeconds) * time.Second),
176		CreatedAt:   now,
177	}
178	vaults.Set(strconv.Itoa(v.ID), v)
179	return v.ID
180}
181
182// Deposit tops up an active vault. Only the owner may deposit, and
183// only ugnot is accepted. The check-in timer is NOT reset by a
184// deposit — only CheckIn resets it.
185func Deposit(cur realm, id int) int64 {
186	if !cur.Previous().IsUserCall() {
187		panic("heirrealm: only direct wallet calls may deposit")
188	}
189	v := mustGetVault(id)
190	caller := cur.Previous().Address()
191	if caller != v.Owner {
192		panic("heirrealm: only the vault owner may deposit")
193	}
194	requireActive(v)
195	sent := unsafe.OriginSend()
196	if len(sent) == 0 || sent.AmountOf(Denom) <= 0 {
197		panic("heirrealm: attach ugnot with -send")
198	}
199	if len(sent) != 1 || sent[0].Denom != Denom {
200		panic("heirrealm: only ugnot is accepted")
201	}
202	v.Balance += sent.AmountOf(Denom)
203	vaults.Set(strconv.Itoa(v.ID), v)
204	return v.Balance
205}
206
207// CheckIn resets the vault's deadline to now + the check-in interval.
208// Only the owner may check in, only while the vault is active, and
209// only BEFORE the deadline has passed. After the deadline the vault
210// is claimable and checking in can no longer save it.
211func CheckIn(cur realm, id int) time.Time {
212	v := mustGetVault(id)
213	caller := cur.Previous().Address()
214	if caller != v.Owner {
215		panic("heirrealm: only the vault owner may check in")
216	}
217	requireActive(v)
218	if !time.Now().Before(v.Deadline) {
219		panic("heirrealm: deadline has passed, check-in is too late")
220	}
221	v.Deadline = time.Now().Add(time.Duration(v.Interval) * time.Second)
222	vaults.Set(strconv.Itoa(v.ID), v)
223	return v.Deadline
224}
225
226// Heartbeat revives a vault during its post-deadline grace period and
227// resets its deadline to now + the check-in interval, identically to
228// CheckIn. Only the vault owner may call Heartbeat, and only strictly
229// during the grace window (after Deadline, before Deadline + GracePeriod).
230func Heartbeat(cur realm, id int) time.Time {
231	v := mustGetVault(id)
232	caller := cur.Previous().Address()
233	if caller != v.Owner {
234		panic("heirrealm: only the vault owner may send a heartbeat")
235	}
236	requireActive(v)
237	now := time.Now()
238	if !now.After(v.Deadline) {
239		panic("heirrealm: deadline has not passed yet, use CheckIn before the deadline")
240	}
241	if !now.Before(v.GraceEnd()) {
242		panic("heirrealm: grace period has ended, heartbeat is too late")
243	}
244	v.Deadline = now.Add(time.Duration(v.Interval) * time.Second)
245	vaults.Set(strconv.Itoa(v.ID), v)
246	return v.Deadline
247}
248
249// TriggerRelease releases an expired vault once both its check-in
250// deadline AND its post-deadline grace period have passed. Anyone may
251// call it — that is the keeper's job — but the keeper may not be the
252// owner or the beneficiary. The keeper earns 2% of the balance; the
253// beneficiary receives the remaining 98%.
254func TriggerRelease(cur realm, id int) (beneficiaryShare int64, keeperFee int64) {
255	v := mustGetVault(id)
256	keeper := cur.Previous().Address()
257	if keeper == "" {
258		panic("heirrealm: keeper must not be empty")
259	}
260	if keeper == v.Owner {
261		panic("heirrealm: the owner cannot be the keeper")
262	}
263	if keeper == v.Beneficiary {
264		panic("heirrealm: the beneficiary cannot be the keeper")
265	}
266	requireActive(v)
267	now := time.Now()
268	if !now.After(v.Deadline) {
269		panic("heirrealm: vault has not expired yet")
270	}
271	if !now.After(v.GraceEnd()) {
272		panic("heirrealm: vault is in grace period, cannot release before deadline + grace")
273	}
274	keeperFee = v.KeeperFee()
275	beneficiaryShare = v.BeneficiaryShare()
276	realmAddr := cur.Address()
277	banker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)
278	if keeperFee > 0 {
279		banker_.SendCoins(realmAddr, keeper, chain.Coins{chain.NewCoin(Denom, keeperFee)})
280	}
281	if beneficiaryShare > 0 {
282		banker_.SendCoins(realmAddr, v.Beneficiary, chain.Coins{chain.NewCoin(Denom, beneficiaryShare)})
283	}
284	v.Released = true
285	v.Keeper = keeper
286	v.ReleasedAt = time.Now()
287	vaults.Set(strconv.Itoa(v.ID), v)
288	return beneficiaryShare, keeperFee
289}
290
291// Cancel closes an active vault and refunds the full balance to the
292// owner. Only the owner may cancel, and only BEFORE the deadline.
293// After expiry the funds belong to the beneficiary and the owner
294// can no longer claw them back.
295func Cancel(cur realm, id int) int64 {
296	v := mustGetVault(id)
297	caller := cur.Previous().Address()
298	if caller != v.Owner {
299		panic("heirrealm: only the vault owner may cancel")
300	}
301	requireActive(v)
302	if !time.Now().Before(v.Deadline) {
303		panic("heirrealm: deadline has passed, vault can no longer be cancelled")
304	}
305	refund := v.Balance
306	realmAddr := cur.Address()
307	banker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)
308	if refund > 0 {
309		banker_.SendCoins(realmAddr, v.Owner, chain.Coins{chain.NewCoin(Denom, refund)})
310	}
311	v.Balance = 0
312	v.Cancelled = true
313	vaults.Set(strconv.Itoa(v.ID), v)
314	return refund
315}
316
317// GetVault returns a copy of the vault with the given ID.
318// Read-only: callable as a query, no transaction needed.
319func GetVault(id int) Vault {
320	return *mustGetVault(id)
321}
322
323// VaultCount returns the number of vaults ever created.
324func VaultCount() int {
325	return nextVault
326}
327
328// requireActive panics unless the vault is still live.
329func requireActive(v *Vault) {
330	if v.Released {
331		panic("heirrealm: vault already released")
332	}
333	if v.Cancelled {
334		panic("heirrealm: vault already cancelled")
335	}
336}
337
338// mustGetVault loads a vault by ID or panics.
339func mustGetVault(id int) *Vault {
340	v := vaults.Get(strconv.Itoa(id))
341	if v == nil {
342		panic("heirrealm: unknown vault ID")
343	}
344	return v.(*Vault)
345}