types: add ValidateNonZeroAddress utility function (#1033)

* Add ValidateNonZeroAddress validation utility

* Update types/validation.go

Co-authored-by: Federico Kunze Küllmer <31522760+fedekunze@users.noreply.github.com>
This commit is contained in:
Loredana Cirstea 2022-04-07 13:51:28 +03:00 committed by GitHub
parent c70701e785
commit e1512c52e9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 0 deletions

View File

@ -29,6 +29,18 @@ func ValidateAddress(address string) error {
return nil
}
// ValidateNonZeroAddress returns an error if the provided string is not a hex
// formatted string address or is equal to zero
func ValidateNonZeroAddress(address string) error {
if IsZeroAddress(address) {
return sdkerrors.Wrapf(
sdkerrors.ErrInvalidAddress, "address '%s' must not be zero",
address,
)
}
return ValidateAddress(address)
}
// SafeInt64 checks for overflows while casting a uint64 to int64 value.
func SafeInt64(value uint64) (int64, error) {
if value > uint64(math.MaxInt64) {

View File

@ -85,6 +85,37 @@ func TestValidateAddress(t *testing.T) {
}
}
func TestValidateNonZeroAddress(t *testing.T) {
testCases := []struct {
name string
address string
expError bool
}{
{
"empty string", "", true,
},
{
"invalid address", "0x", true,
},
{
"zero address", common.Address{}.String(), true,
},
{
"valid address", tests.GenerateAddress().Hex(), false,
},
}
for _, tc := range testCases {
err := ValidateNonZeroAddress(tc.address)
if tc.expError {
require.Error(t, err, tc.name)
} else {
require.NoError(t, err, tc.name)
}
}
}
func TestSafeInt64(t *testing.T) {
testCases := []struct {
name string