github.com/Finschia/finschia-sdk@v0.49.1/x/feegrant/grant.go (about)

     1  package feegrant
     2  
     3  import (
     4  	"github.com/gogo/protobuf/proto"
     5  
     6  	"github.com/Finschia/finschia-sdk/codec/types"
     7  	sdk "github.com/Finschia/finschia-sdk/types"
     8  	sdkerrors "github.com/Finschia/finschia-sdk/types/errors"
     9  )
    10  
    11  var _ types.UnpackInterfacesMessage = &Grant{}
    12  
    13  // NewGrant creates a new FeeAllowanceGrant.
    14  //
    15  //nolint:interfacer
    16  func NewGrant(granter, grantee sdk.AccAddress, feeAllowance FeeAllowanceI) (Grant, error) {
    17  	msg, ok := feeAllowance.(proto.Message)
    18  	if !ok {
    19  		return Grant{}, sdkerrors.Wrapf(sdkerrors.ErrPackAny, "cannot proto marshal %T", feeAllowance)
    20  	}
    21  
    22  	any, err := types.NewAnyWithValue(msg)
    23  	if err != nil {
    24  		return Grant{}, err
    25  	}
    26  
    27  	return Grant{
    28  		Granter:   granter.String(),
    29  		Grantee:   grantee.String(),
    30  		Allowance: any,
    31  	}, nil
    32  }
    33  
    34  // ValidateBasic performs basic validation on
    35  // FeeAllowanceGrant
    36  func (a Grant) ValidateBasic() error {
    37  	if a.Granter == "" {
    38  		return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing granter address")
    39  	}
    40  	if a.Grantee == "" {
    41  		return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "missing grantee address")
    42  	}
    43  	if a.Grantee == a.Granter {
    44  		return sdkerrors.Wrap(sdkerrors.ErrInvalidAddress, "cannot self-grant fee authorization")
    45  	}
    46  
    47  	f, err := a.GetGrant()
    48  	if err != nil {
    49  		return err
    50  	}
    51  
    52  	return f.ValidateBasic()
    53  }
    54  
    55  // GetGrant unpacks allowance
    56  func (a Grant) GetGrant() (FeeAllowanceI, error) {
    57  	allowance, ok := a.Allowance.GetCachedValue().(FeeAllowanceI)
    58  	if !ok {
    59  		return nil, sdkerrors.Wrap(ErrNoAllowance, "failed to get allowance")
    60  	}
    61  
    62  	return allowance, nil
    63  }
    64  
    65  // UnpackInterfaces implements UnpackInterfacesMessage.UnpackInterfaces
    66  func (a Grant) UnpackInterfaces(unpacker types.AnyUnpacker) error {
    67  	var allowance FeeAllowanceI
    68  	return unpacker.UnpackAny(a.Allowance, &allowance)
    69  }