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