AddressConverter library provides utility functions for converting between Ethereum address (20 bytes) and bytes32 (32 bytes) types. This is commonly needed when working with cross-chain messaging protocols that use bytes32 for addresses.
Overview
Ethereum addresses are 20 bytes, while many cross-chain protocols use bytes32 for standardized addressing across different chains. This library handles the conversion between these formats safely and efficiently.Functions
toBytes32
Converts an Ethereum address to bytes32 format.addr: The Ethereum address to convert (20 bytes)
- Casting to
uint160(20 bytes) - Casting to
uint256(32 bytes, zero-padded on left) - Casting to
bytes32
toAddress
Converts bytes32 back to an Ethereum address.b: The bytes32 value to convert (32 bytes)
InvalidAddress(bytes32): If the bytes32 value cannot be safely converted to an address (top 12 bytes are not zero)
- Validates that the bytes32 can be safely converted using
isValidAddress() - Converts by casting to
uint256, thenuint160, thenaddress
isValidAddress
Checks if a bytes32 value can be safely converted to an Ethereum address.b: The bytes32 value to validate
true if the bytes32 can be safely converted to an address, false otherwise
Validation:
For a bytes32 to represent a valid Ethereum address:
- The top 12 bytes (96 bits) must be zero
- Only the bottom 20 bytes (160 bits) should contain data
Errors
InvalidAddress
Thrown when attempting to convert an invalid bytes32 value to an address.value: The invalid bytes32 value that was attempted to be converted
- When calling
toAddress()with a bytes32 value where the top 12 bytes are not zero
Usage Patterns
Basic Conversion
Safe Conversion with Validation
Integration with Cross-Chain Protocols
TypeScript Equivalent
The TypeScript SDK provides equivalent functionality. See TypeScript SDK Utilities for the TypeScript implementation.Gas Optimization
All functions in this library are marked asinternal pure, meaning:
- No state is read or modified
- Functions are inlined during compilation (no JUMP operations)
- Minimal gas cost (just the type conversions)
Best Practices
- Always validate when converting from bytes32 to address using external input
- Use library syntax for cleaner code:
address.toBytes32()instead ofAddressConverter.toBytes32(address) - Handle errors appropriately when
toAddress()might revert - Batch conversions when possible to optimize gas in loops