state.gno
2.68 Kb ยท 99 lines
1package pool
2
3import (
4 "chain/runtime"
5 "errors"
6
7 prbac "gno.land/p/gnoswap/rbac"
8 "gno.land/p/gnoswap/store"
9 "gno.land/p/gnoswap/version_manager"
10 "gno.land/r/gnoswap/access"
11
12 // initialize rbac roles
13 _ "gno.land/r/gnoswap/rbac"
14)
15
16var (
17 currentAddress = runtime.CurrentRealm().Address()
18 domainPath = runtime.CurrentRealm().PkgPath()
19
20 // kvStore is the core storage instance for the pool domain.
21 // All pool implementations share this single storage instance,
22 // ensuring data consistency across version upgrades.
23 kvStore store.KVStore
24
25 // versionManager is the version manager for the pool domain.
26 // It manages the registration and switching of pool implementations.
27 versionManager version_manager.VersionManager
28
29 // implementation is the currently active pool implementation.
30 // This pointer is switched during upgrades to point to different versions (v1, v2, etc.).
31 // The proxy layer routes all calls to this implementation.
32 implementation IPool
33)
34
35// init initializes the pool domain state.
36// This function is called when the pool domain contract is first deployed.
37func init() {
38 // Create a new KV store instance for this domain
39 kvStore = store.NewKVStore(currentAddress)
40 initRegisterReadableContract()
41
42 // Initialize the initializers map to store implementation registration functions
43 versionManager = version_manager.NewVersionManager(
44 domainPath,
45 kvStore,
46 initializeDomainStore,
47 )
48
49 implementation = nil
50}
51
52func initRegisterReadableContract() {
53 positionAddr := access.MustGetAddress(prbac.ROLE_POSITION.String())
54 stakerAddr := access.MustGetAddress(prbac.ROLE_STAKER.String())
55 routerAddr := access.MustGetAddress(prbac.ROLE_ROUTER.String())
56
57 if err := kvStore.AddAuthorizedCaller(routerAddr, store.ReadOnly); err != nil {
58 panic(err)
59 }
60
61 if err := kvStore.AddAuthorizedCaller(positionAddr, store.ReadOnly); err != nil {
62 panic(err)
63 }
64
65 if err := kvStore.AddAuthorizedCaller(stakerAddr, store.ReadOnly); err != nil {
66 panic(err)
67 }
68}
69
70func initializeDomainStore(kvStore store.KVStore) any {
71 return NewPoolStore(kvStore)
72}
73
74// getImplementation returns the currently active pool implementation.
75// This function is used by all proxy functions to route calls to the active implementation.
76// If no implementation is set, it panics to prevent invalid state.
77func getImplementation() IPool {
78 if implementation == nil {
79 panic("implementation is not initialized")
80 }
81
82 return implementation
83}
84
85func updateImplementation() error {
86 result := versionManager.GetCurrentImplementation()
87 if result == nil {
88 return errors.New("implementation is not initialized")
89 }
90
91 impl, ok := result.(IPool)
92 if !ok {
93 return errors.New("impl is not an IPool")
94 }
95
96 implementation = impl
97
98 return nil
99}