-
Notifications
You must be signed in to change notification settings - Fork 47
/
common.go
86 lines (74 loc) · 2.25 KB
/
common.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
82
83
84
85
86
package types
import (
sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/bnb-chain/greenfield/types"
)
func NewPrincipalWithAccount(addr sdk.AccAddress) *Principal {
return &Principal{
Type: PRINCIPAL_TYPE_GNFD_ACCOUNT,
Value: addr.String(),
}
}
func NewPrincipalWithGroupId(groupID sdkmath.Uint) *Principal {
return &Principal{
Type: PRINCIPAL_TYPE_GNFD_GROUP,
Value: groupID.String(),
}
}
func NewPrincipalWithGroupInfo(groupOwner sdk.AccAddress, groupName string) *Principal {
return &Principal{
Type: PRINCIPAL_TYPE_GNFD_GROUP,
Value: types.NewGroupGRN(groupOwner, groupName).String(),
}
}
func (p *Principal) ValidateBasic() error {
switch p.Type {
case PRINCIPAL_TYPE_UNSPECIFIED:
return ErrInvalidPrincipal.Wrapf("Not allowed empty principal type.")
case PRINCIPAL_TYPE_GNFD_ACCOUNT:
_, err := sdk.AccAddressFromHexUnsafe(p.Value)
if err != nil {
return ErrInvalidPrincipal.Wrapf("Invalid account, principal: %s, err: %s", p.String(), err)
}
case PRINCIPAL_TYPE_GNFD_GROUP:
return nil
default:
return ErrInvalidPrincipal.Wrapf("Unknown principal type.")
}
return nil
}
func (p *Principal) GetAccountAddress() (sdk.AccAddress, error) {
if p.Type != PRINCIPAL_TYPE_GNFD_ACCOUNT {
panic("principal type mismatch.")
}
accAddr, err := sdk.AccAddressFromHexUnsafe(p.Value)
if err != nil {
return nil, ErrInvalidPrincipal.Wrapf("Invalid account, principal: %s, err: %s", p.String(), err)
}
return accAddr, nil
}
func (p *Principal) GetGroupID() (sdkmath.Uint, error) {
if p.Type != PRINCIPAL_TYPE_GNFD_GROUP {
panic("principal type mismatch.")
}
groupID, err := sdkmath.ParseUint(p.Value)
if err != nil {
return sdkmath.ZeroUint(), ErrInvalidPrincipal.Wrapf("Invalid groupID, principal: %s, err: %s", p.String(), err)
}
return groupID, nil
}
func (p *Principal) MustGetAccountAddress() sdk.AccAddress {
address, err := p.GetAccountAddress()
if err != nil {
panic(ErrInvalidPrincipal.Wrapf("Invalid account, principal: %s, err: %s", p.String(), err))
}
return address
}
func (p *Principal) MustGetGroupID() sdkmath.Uint {
groupID, err := p.GetGroupID()
if err != nil {
panic(ErrInvalidPrincipal.Wrapf("Invalid groupID, principal: %s, err: %s", p.String(), err))
}
return groupID
}