2021-05-06 11:23:48 -07:00
package authz
import (
"time"
proto "github.com/gogo/protobuf/proto"
cdctypes "github.com/cosmos/cosmos-sdk/codec/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
)
2022-03-24 11:27:23 -07:00
// NewGrant returns new Grant. Expiration is optional and noop if null.
// It returns an error if the expiration is before the current block time,
// which is passed into the `blockTime` arg.
func NewGrant ( blockTime time . Time , a Authorization , expiration * time . Time ) ( Grant , error ) {
if expiration != nil && ! expiration . After ( blockTime ) {
2022-04-19 12:08:35 -07:00
return Grant { } , sdkerrors . Wrapf ( ErrInvalidExpirationTime , "expiration must be after the current block time (%v), got %v" , blockTime . Format ( time . RFC3339 ) , expiration . Format ( time . RFC3339 ) )
2022-02-07 06:38:45 -08:00
}
2021-05-10 02:28:08 -07:00
msg , ok := a . ( proto . Message )
2021-05-06 11:23:48 -07:00
if ! ok {
2022-04-19 12:08:35 -07:00
return Grant { } , sdkerrors . ErrPackAny . Wrapf ( "cannot proto marshal %T" , a )
2021-05-06 11:23:48 -07:00
}
any , err := cdctypes . NewAnyWithValue ( msg )
if err != nil {
return Grant { } , err
}
2022-03-24 11:27:23 -07:00
return Grant {
Expiration : expiration ,
Authorization : any ,
} , nil
2021-05-06 11:23:48 -07:00
}
2022-02-03 08:01:33 -08:00
var (
_ cdctypes . UnpackInterfacesMessage = & Grant { }
)
2021-05-06 11:23:48 -07:00
// UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
2021-05-10 02:28:08 -07:00
func ( g Grant ) UnpackInterfaces ( unpacker cdctypes . AnyUnpacker ) error {
2021-05-06 11:23:48 -07:00
var authorization Authorization
2021-05-10 02:28:08 -07:00
return unpacker . UnpackAny ( g . Authorization , & authorization )
2021-05-06 11:23:48 -07:00
}
// GetAuthorization returns the cached value from the Grant.Authorization if present.
2022-02-16 09:36:50 -08:00
func ( g Grant ) GetAuthorization ( ) ( Authorization , error ) {
2021-05-10 02:28:08 -07:00
if g . Authorization == nil {
2022-04-19 12:08:35 -07:00
return nil , sdkerrors . ErrInvalidType . Wrap ( "authorization is nil" )
2021-05-10 02:28:08 -07:00
}
a , ok := g . Authorization . GetCachedValue ( ) . ( Authorization )
2021-05-06 11:23:48 -07:00
if ! ok {
2022-02-16 09:36:50 -08:00
return nil , sdkerrors . ErrInvalidType . Wrapf ( "expected %T, got %T" , ( Authorization ) ( nil ) , g . Authorization . GetCachedValue ( ) )
2021-05-06 11:23:48 -07:00
}
2022-02-16 09:36:50 -08:00
return a , nil
2021-05-10 02:28:08 -07:00
}
func ( g Grant ) ValidateBasic ( ) error {
av := g . Authorization . GetCachedValue ( )
a , ok := av . ( Authorization )
if ! ok {
2022-04-19 12:08:35 -07:00
return sdkerrors . ErrInvalidType . Wrapf ( "expected %T, got %T" , ( Authorization ) ( nil ) , av )
2021-05-10 02:28:08 -07:00
}
return a . ValidateBasic ( )
2021-05-06 11:23:48 -07:00
}