Skip to main content
The 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.
Parameters:
  • addr: The Ethereum address to convert (20 bytes)
Returns: The bytes32 representation of the address (32 bytes, zero-padded) Implementation: The function converts the address by:
  1. Casting to uint160 (20 bytes)
  2. Casting to uint256 (32 bytes, zero-padded on left)
  3. Casting to bytes32
Example:

toAddress

Converts bytes32 back to an Ethereum address.
Parameters:
  • b: The bytes32 value to convert (32 bytes)
Returns: The Ethereum address extracted from the bytes32 value Reverts:
  • InvalidAddress(bytes32): If the bytes32 value cannot be safely converted to an address (top 12 bytes are not zero)
Implementation: The function:
  1. Validates that the bytes32 can be safely converted using isValidAddress()
  2. Converts by casting to uint256, then uint160, then address
Example:

isValidAddress

Checks if a bytes32 value can be safely converted to an Ethereum address.
Parameters:
  • b: The bytes32 value to validate
Returns: 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
Example:

Errors

InvalidAddress

Thrown when attempting to convert an invalid bytes32 value to an address.
Parameters:
  • value: The invalid bytes32 value that was attempted to be converted
When it occurs:
  • 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 as internal 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

  1. Always validate when converting from bytes32 to address using external input
  2. Use library syntax for cleaner code: address.toBytes32() instead of AddressConverter.toBytes32(address)
  3. Handle errors appropriately when toAddress() might revert
  4. Batch conversions when possible to optimize gas in loops