lifetime.gno
2.01 Kb ยท 81 lines
1package lifetime
2
3import (
4 "std"
5
6 "gno.land/p/demo/avl"
7 "gno.land/p/demo/ownable"
8)
9
10// LifetimeSubscription represents a subscription that requires only a one-time payment.
11// It grants permanent access to a service or product.
12type LifetimeSubscription struct {
13 ownable.Ownable
14 amount int64
15 subs *avl.Tree // std.Address -> bool
16}
17
18// NewLifetimeSubscription creates and returns a new lifetime subscription.
19func NewLifetimeSubscription(amount int64) *LifetimeSubscription {
20 return &LifetimeSubscription{
21 Ownable: *ownable.New(),
22 amount: amount,
23 subs: avl.NewTree(),
24 }
25}
26
27// processSubscription handles the subscription process for a given receiver.
28func (ls *LifetimeSubscription) processSubscription(receiver std.Address) error {
29 amount := std.OriginSend()
30
31 if amount.AmountOf("ugnot") != ls.amount {
32 return ErrAmt
33 }
34
35 _, exists := ls.subs.Get(receiver.String())
36
37 if exists {
38 return ErrAlreadySub
39 }
40
41 ls.subs.Set(receiver.String(), true)
42
43 return nil
44}
45
46// Subscribe processes the payment for a lifetime subscription.
47func (ls *LifetimeSubscription) Subscribe() error {
48 caller := std.CurrentRealm().Address()
49 return ls.processSubscription(caller)
50}
51
52// GiftSubscription allows the caller to pay for a lifetime subscription for another user.
53func (ls *LifetimeSubscription) GiftSubscription(receiver std.Address) error {
54 return ls.processSubscription(receiver)
55}
56
57// HasValidSubscription checks if the given address has an active lifetime subscription.
58func (ls *LifetimeSubscription) HasValidSubscription(addr std.Address) error {
59 _, exists := ls.subs.Get(addr.String())
60
61 if !exists {
62 return ErrNoSub
63 }
64
65 return nil
66}
67
68// UpdateAmount allows the owner of the LifetimeSubscription contract to update the subscription price.
69func (ls *LifetimeSubscription) UpdateAmount(newAmount int64) error {
70 if !ls.OwnedByCurrent() {
71 return ErrNotAuthorized
72 }
73
74 ls.amount = newAmount
75 return nil
76}
77
78// GetAmount returns the current subscription price.
79func (ls *LifetimeSubscription) GetAmount() int64 {
80 return ls.amount
81}