Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use TextMarshaler interface to simplify eth.Address and eth.Data #62

Open
ryanschneider opened this issue Apr 6, 2022 · 0 comments
Open

Comments

@ryanschneider
Copy link
Contributor

Not directly related to #61, but we could also simplify with the TextMarshaler and TextUnmarshaler interface, so we don't have to deal with json.Marshal/Unmarshal in our functions for the base64 encoding/decoding.

Those text marshalers would focus solely on validating and returning a canonical representation of an address, which would be compatible with other encoding formats.

Before

func (a *Address) UnmarshalJSON(data []byte) error {
	// We'll keep the checksummed string in memory so we can use it for internal representations
	str, err := unmarshalHex(data, 20, "data")
	str = ToChecksumAddress(str)
	if err != nil {
		return err
	}
	*a = Address(str)
	return nil
}

func (a Address) MarshalJSON() ([]byte, error) {
	// Seems like geth and parity both return the lower-cased string rather than the checksummed one
	s := strings.ToLower(string(a))
	return json.Marshal(&s)
}

After

func (a *Address) UnmarshalText(text []byte) error {
	str, err := validateHex(string(text), 20, "data")
	if err != nil {
		return err
	}
	str = ToChecksumAddress(str)
	*a = Address(str)
	return nil
}

func (a Address) MarshalText() ([]byte, error) {
	return bytes.ToLower([]byte(a)), nil
}

Originally posted by @basgys in #61 (comment)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant