global_keeper.gno
1.89 Kb ยท 83 lines
1package referral
2
3import (
4 "chain"
5 "chain/runtime"
6)
7
8var gReferralKeeper ReferralKeeper
9
10const EventRegisterFailed = "ReferralRegistrationFailed"
11
12func init() {
13 if gReferralKeeper == nil {
14 gReferralKeeper = NewKeeper()
15 }
16}
17
18// GetReferral returns the referral address for the given address.
19func GetReferral(addr string) string {
20 referral, err := gReferralKeeper.get(address(addr))
21 if err != nil {
22 return ""
23 }
24 return referral.String()
25}
26
27// HasReferral returns true if the given address has a referral.
28func HasReferral(addr string) bool {
29 _, err := gReferralKeeper.get(address(addr))
30 return err == nil
31}
32
33// IsEmpty returns true if no referrals exist in the system.
34func IsEmpty() bool {
35 return gReferralKeeper.isEmpty()
36}
37
38// GetLastOpTimestamp returns the last operation timestamp for the given address.
39// Returns ErrNotFound if no operation exists.
40func GetLastOpTimestamp(addr string) (int64, error) {
41 return gReferralKeeper.getLastOpTimestamp(address(addr))
42}
43
44// ContractAddress returns the address of the referral contract.
45// Use this address as the referral parameter in TryRegister to remove an existing referral.
46func ContractAddress() string {
47 return selfAddress.String()
48}
49
50// TryRegister attempts to register a new referral.
51//
52// Parameters:
53// - addr: address to register
54// - referral: referral address string
55//
56// Returns true on success, false on failure.
57// Panics if the caller is not authorized.
58func TryRegister(cur realm, addr address, referral string) bool {
59 caller := runtime.PreviousRealm().Address()
60 assertValidCaller(caller)
61
62 refAddr := address(referral)
63
64 err := gReferralKeeper.register(addr, refAddr)
65 if err != nil {
66 chain.Emit(
67 EventRegisterFailed,
68 "address", addr.String(),
69 "error", err.Error(),
70 )
71
72 return false
73 }
74
75 chain.Emit(
76 "RegisterReferral",
77 "prevAddr", caller.String(),
78 "address", addr.String(),
79 "referral", refAddr.String(),
80 )
81
82 return true
83}