common: add IsZero methods for Hash and Address types

This commit is contained in:
islishude 2025-02-12 09:11:10 +08:00
parent da71839a27
commit ffec10f511
2 changed files with 62 additions and 0 deletions

View File

@ -194,6 +194,11 @@ func (h *Hash) UnmarshalGraphQL(input interface{}) error {
return err
}
// IsZero returns true if the hash is the zero hash.
func (h Hash) IsZero() bool {
return h == Hash{}
}
// UnprefixedHash allows marshaling a Hash without 0x prefix.
type UnprefixedHash Hash
@ -371,6 +376,11 @@ func (a *Address) UnmarshalGraphQL(input interface{}) error {
return err
}
// IsZero returns true if the address is the zero address.
func (a Address) IsZero() bool {
return a == Address{}
}
// UnprefixedAddress allows marshaling an Address without 0x prefix.
type UnprefixedAddress Address

View File

@ -151,3 +151,55 @@ func TestToFilterArg(t *testing.T) {
})
}
}
func TestAddress_IsZero(t *testing.T) {
tests := []struct {
name string
address common.Address
want bool
}{
{
"zero address",
common.Address{},
true,
},
{
"non-zero address",
common.HexToAddress("0xD36722ADeC3EdCB29c8e7b5a47f352D701393462"),
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.address.IsZero(); got != tt.want {
t.Errorf("Address.IsZero() = %v, want %v", got, tt.want)
}
})
}
}
func TestHash_IsZero(t *testing.T) {
tests := []struct {
name string
hash common.Hash
want bool
}{
{
"zero hash",
common.Hash{},
true,
},
{
"non-zero hash",
common.HexToHash("0xaba98c3b293961bb1bbd754e148cfd2ad50f887e3eebee0135d77b841a6daac9"),
false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := tt.hash.IsZero(); got != tt.want {
t.Errorf("Hash.IsZero() = %v, want %v", got, tt.want)
}
})
}
}