gcx/backend/services/translate-service/internal/domain/vo/address.go

46 lines
1.3 KiB
Go

package vo
import (
"fmt"
"regexp"
"strings"
)
// Address is a value object representing a blockchain or internal platform address.
type Address string
// addressPattern matches common hex-based addresses (0x-prefixed, 10-64 hex chars)
// as well as non-hex internal platform addresses (alphanumeric + hyphens, >= 6 chars).
var (
hexAddressPattern = regexp.MustCompile(`^0x[0-9a-fA-F]{10,64}$`)
internalAddressPattern = regexp.MustCompile(`^[a-zA-Z0-9_-]{6,128}$`)
)
// NewAddress creates a validated Address value object.
func NewAddress(raw string) (Address, error) {
trimmed := strings.TrimSpace(raw)
if trimmed == "" {
return "", fmt.Errorf("address must not be empty")
}
if !hexAddressPattern.MatchString(trimmed) && !internalAddressPattern.MatchString(trimmed) {
return "", fmt.Errorf("invalid address format: %s", trimmed)
}
return Address(trimmed), nil
}
// String returns the string representation of the address.
func (a Address) String() string {
return string(a)
}
// IsHex reports whether the address is a hex-encoded on-chain address.
func (a Address) IsHex() bool {
return hexAddressPattern.MatchString(string(a))
}
// IsValid reports whether the address passes format validation.
func (a Address) IsValid() bool {
s := string(a)
return hexAddressPattern.MatchString(s) || internalAddressPattern.MatchString(s)
}