heirrealm.gno
9.61 Kb · 295 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
68var (
69 vaults avl.Tree // vault ID (string) -> *Vault
70 nextVault int
71)
72
73// Vault is one inheritance vault.
74type Vault struct {
75 ID int
76 Owner address
77 Beneficiary address
78 Balance int64 // ugnot held by this vault
79 Interval int64 // check-in window, in seconds
80 Deadline time.Time
81 CreatedAt time.Time
82 Released bool
83 Cancelled bool
84 Keeper address // set on release; zero address until then
85 ReleasedAt time.Time // zero until released
86}
87
88// Status returns a human-readable state for the vault.
89func (v Vault) Status() string {
90 if v.Released {
91 return "released"
92 }
93 if v.Cancelled {
94 return "cancelled"
95 }
96 if time.Now().After(v.Deadline) {
97 return "expired — awaiting keeper"
98 }
99 return "active"
100}
101
102// KeeperFee returns the keeper's cut of the vault balance at release.
103func (v Vault) KeeperFee() int64 {
104 return v.Balance * KeeperFeeBPS / 10000
105}
106
107// BeneficiaryShare returns what the beneficiary receives at release.
108func (v Vault) BeneficiaryShare() int64 {
109 return v.Balance - v.KeeperFee()
110}
111
112// CreateVault opens a vault for beneficiary with a check-in window of
113// intervalSeconds. Attach the initial deposit with -send ugnot.
114//
115// The caller becomes the owner. The beneficiary must not be the owner.
116// The deposit must be more than 0 ugnot.
117func CreateVault(cur realm, beneficiary address, intervalSeconds int64) int {
118 if !cur.Previous().IsUserCall() {
119 panic("heirrealm: only direct wallet calls may create a vault")
120 }
121 owner := cur.Previous().Address()
122 if beneficiary == "" {
123 panic("heirrealm: beneficiary must not be empty")
124 }
125 if beneficiary == owner {
126 panic("heirrealm: beneficiary must not be the owner")
127 }
128 if intervalSeconds < MinCheckInIntervalSeconds {
129 panic("heirrealm: check-in interval too short (minimum 60 seconds)")
130 }
131 if intervalSeconds > MaxCheckInIntervalSeconds {
132 panic("heirrealm: check-in interval too long (maximum 365 days)")
133 }
134 sent := unsafe.OriginSend()
135 if len(sent) == 0 || sent.AmountOf(Denom) <= 0 {
136 panic("heirrealm: attach an initial deposit in ugnot with -send")
137 }
138 if len(sent) != 1 || sent[0].Denom != Denom {
139 panic("heirrealm: only ugnot is accepted")
140 }
141 amount := sent.AmountOf(Denom)
142 now := time.Now()
143 nextVault++
144 v := &Vault{
145 ID: nextVault,
146 Owner: owner,
147 Beneficiary: beneficiary,
148 Balance: amount,
149 Interval: intervalSeconds,
150 Deadline: now.Add(time.Duration(intervalSeconds) * time.Second),
151 CreatedAt: now,
152 }
153 vaults.Set(strconv.Itoa(v.ID), v)
154 return v.ID
155}
156
157// Deposit tops up an active vault. Only the owner may deposit, and
158// only ugnot is accepted. The check-in timer is NOT reset by a
159// deposit — only CheckIn resets it.
160func Deposit(cur realm, id int) int64 {
161 if !cur.Previous().IsUserCall() {
162 panic("heirrealm: only direct wallet calls may deposit")
163 }
164 v := mustGetVault(id)
165 caller := cur.Previous().Address()
166 if caller != v.Owner {
167 panic("heirrealm: only the vault owner may deposit")
168 }
169 requireActive(v)
170 sent := unsafe.OriginSend()
171 if len(sent) == 0 || sent.AmountOf(Denom) <= 0 {
172 panic("heirrealm: attach ugnot with -send")
173 }
174 if len(sent) != 1 || sent[0].Denom != Denom {
175 panic("heirrealm: only ugnot is accepted")
176 }
177 v.Balance += sent.AmountOf(Denom)
178 vaults.Set(strconv.Itoa(v.ID), v)
179 return v.Balance
180}
181
182// CheckIn resets the vault's deadline to now + the check-in interval.
183// Only the owner may check in, only while the vault is active, and
184// only BEFORE the deadline has passed. After the deadline the vault
185// is claimable and checking in can no longer save it.
186func CheckIn(cur realm, id int) time.Time {
187 v := mustGetVault(id)
188 caller := cur.Previous().Address()
189 if caller != v.Owner {
190 panic("heirrealm: only the vault owner may check in")
191 }
192 requireActive(v)
193 if !time.Now().Before(v.Deadline) {
194 panic("heirrealm: deadline has passed, check-in is too late")
195 }
196 v.Deadline = time.Now().Add(time.Duration(v.Interval) * time.Second)
197 vaults.Set(strconv.Itoa(v.ID), v)
198 return v.Deadline
199}
200
201// TriggerRelease releases an expired vault. Anyone may call it — that
202// is the keeper's job — but the keeper may not be the owner or the
203// beneficiary, and the deadline must have passed. The keeper earns
204// 2% of the balance; the beneficiary receives the remaining 98%.
205// The keeper is paid for doing the work, never a custodian: they
206// cannot release early, change the beneficiary, or touch the funds
207// before expiry.
208func TriggerRelease(cur realm, id int) (beneficiaryShare int64, keeperFee int64) {
209 v := mustGetVault(id)
210 keeper := cur.Previous().Address()
211 if keeper == "" {
212 panic("heirrealm: keeper must not be empty")
213 }
214 if keeper == v.Owner {
215 panic("heirrealm: the owner cannot be the keeper")
216 }
217 if keeper == v.Beneficiary {
218 panic("heirrealm: the beneficiary cannot be the keeper")
219 }
220 requireActive(v)
221 if !time.Now().After(v.Deadline) {
222 panic("heirrealm: vault has not expired yet")
223 }
224 keeperFee = v.KeeperFee()
225 beneficiaryShare = v.BeneficiaryShare()
226 realmAddr := cur.Address()
227 banker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)
228 if keeperFee > 0 {
229 banker_.SendCoins(realmAddr, keeper, chain.Coins{chain.NewCoin(Denom, keeperFee)})
230 }
231 if beneficiaryShare > 0 {
232 banker_.SendCoins(realmAddr, v.Beneficiary, chain.Coins{chain.NewCoin(Denom, beneficiaryShare)})
233 }
234 v.Released = true
235 v.Keeper = keeper
236 v.ReleasedAt = time.Now()
237 vaults.Set(strconv.Itoa(v.ID), v)
238 return beneficiaryShare, keeperFee
239}
240
241// Cancel closes an active vault and refunds the full balance to the
242// owner. Only the owner may cancel, and only BEFORE the deadline.
243// After expiry the funds belong to the beneficiary and the owner
244// can no longer claw them back.
245func Cancel(cur realm, id int) int64 {
246 v := mustGetVault(id)
247 caller := cur.Previous().Address()
248 if caller != v.Owner {
249 panic("heirrealm: only the vault owner may cancel")
250 }
251 requireActive(v)
252 if !time.Now().Before(v.Deadline) {
253 panic("heirrealm: deadline has passed, vault can no longer be cancelled")
254 }
255 refund := v.Balance
256 realmAddr := cur.Address()
257 banker_ := banker.NewBanker(banker.BankerTypeRealmSend, cur)
258 if refund > 0 {
259 banker_.SendCoins(realmAddr, v.Owner, chain.Coins{chain.NewCoin(Denom, refund)})
260 }
261 v.Balance = 0
262 v.Cancelled = true
263 vaults.Set(strconv.Itoa(v.ID), v)
264 return refund
265}
266
267// GetVault returns a copy of the vault with the given ID.
268// Read-only: callable as a query, no transaction needed.
269func GetVault(id int) Vault {
270 return *mustGetVault(id)
271}
272
273// VaultCount returns the number of vaults ever created.
274func VaultCount() int {
275 return nextVault
276}
277
278// requireActive panics unless the vault is still live.
279func requireActive(v *Vault) {
280 if v.Released {
281 panic("heirrealm: vault already released")
282 }
283 if v.Cancelled {
284 panic("heirrealm: vault already cancelled")
285 }
286}
287
288// mustGetVault loads a vault by ID or panics.
289func mustGetVault(id int) *Vault {
290 v := vaults.Get(strconv.Itoa(id))
291 if v == nil {
292 panic("heirrealm: unknown vault ID")
293 }
294 return v.(*Vault)
295}