-
Notifications
You must be signed in to change notification settings - Fork 566
/
stateful_authenticator.go
81 lines (65 loc) · 2.55 KB
/
stateful_authenticator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package testutils
import (
"encoding/json"
"fmt"
"github.com/cosmos/cosmos-sdk/store/prefix"
storetypes "github.com/cosmos/cosmos-sdk/store/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/osmosis-labs/osmosis/v25/x/smart-account/authenticator"
)
var _ authenticator.Authenticator = &StatefulAuthenticator{}
type StatefulAuthenticatorData struct {
Value int
}
// StatefulAuthenticator is an experiment of how to write authenticators that handle state
type StatefulAuthenticator struct {
KvStoreKey storetypes.StoreKey
}
func (s StatefulAuthenticator) Type() string {
return "Stateful"
}
func (s StatefulAuthenticator) StaticGas() uint64 {
return 1000
}
func (s StatefulAuthenticator) Initialize(config []byte) (authenticator.Authenticator, error) {
return s, nil
}
func (s StatefulAuthenticator) Authenticate(ctx sdk.Context, request authenticator.AuthenticationRequest) error {
statefulData := StatefulAuthenticatorData{Value: s.GetValue(ctx)}
if statefulData.Value > 10 {
return fmt.Errorf("Value is too high: %d", statefulData.Value)
}
s.SetValue(ctx, statefulData.Value+1)
return nil
}
func (s StatefulAuthenticator) Track(ctx sdk.Context, request authenticator.AuthenticationRequest) error {
statefulData := StatefulAuthenticatorData{Value: s.GetValue(ctx)}
if statefulData.Value > 10 {
return fmt.Errorf("Value is too high: %d", statefulData.Value)
}
s.SetValue(ctx, statefulData.Value+1)
return nil
}
func (s StatefulAuthenticator) SetValue(ctx sdk.Context, value int) {
kvStore := prefix.NewStore(ctx.KVStore(s.KvStoreKey), []byte(s.Type()))
statefulData := StatefulAuthenticatorData{Value: value}
newBz, _ := json.Marshal(statefulData)
kvStore.Set([]byte("value"), newBz)
}
func (s StatefulAuthenticator) GetValue(ctx sdk.Context) int {
kvStore := prefix.NewStore(ctx.KVStore(s.KvStoreKey), []byte(s.Type()))
bz := kvStore.Get([]byte("value")) // global value. On the real thing we may want the account
var statefulData StatefulAuthenticatorData
_ = json.Unmarshal(bz, &statefulData) // if we can't unmarshal, we just assume it's 0
return statefulData.Value
}
func (s StatefulAuthenticator) ConfirmExecution(ctx sdk.Context, request authenticator.AuthenticationRequest) error {
s.SetValue(ctx, s.GetValue(ctx)+1)
return nil
}
func (s StatefulAuthenticator) OnAuthenticatorAdded(ctx sdk.Context, account sdk.AccAddress, config []byte, authenticatorId string) error {
return nil
}
func (s StatefulAuthenticator) OnAuthenticatorRemoved(ctx sdk.Context, account sdk.AccAddress, config []byte, authenticatorId string) error {
return nil
}