Type system utilities providing opaque types for enhanced type safety and validation functions for blockchain data types.
Type-safe wrappers around primitive types to prevent accidental misuse and provide compile-time type checking.
type OpaqueType<T extends string, U> = U & Tag<T, U>;
/** Hexadecimal string type */
type HexString = OpaqueType<'HexString', string>;
/** Ethereum address string type */
type AddressString = OpaqueType<'AddressString', string>;
/** Big integer string representation */
type BigIntString = OpaqueType<'BigIntString', string>;
/** Integer number type */
type IntNumber = OpaqueType<'IntNumber', number>;
/** Regular expression string type */
type RegExpString = OpaqueType<'RegExpString', string>;
/** Callback function type */
type Callback<T> = (err: Error | null, result: T | null) => void;Usage Examples:
import { HexString, AddressString, hexStringFromNumber } from "@coinbase/wallet-sdk";
// Type-safe hex strings
const chainId: HexString = hexStringFromNumber(1);
const txHash: HexString = HexString("0x1234567890abcdef");
// Type-safe addresses
const userAddress: AddressString = AddressString("0x742d35Cc6634C0532925a3b8D186dFaedD9B6E3C");
// TypeScript will prevent mixing types
// const invalid = chainId + userAddress; // Type error!Functions for working with hexadecimal strings, conversions, and validation.
/**
* Convert number to hexadecimal string with 0x prefix
* @param num - Number to convert
* @returns Hex string representation
*/
function hexStringFromNumber(num: number): HexString;
/**
* Check if string has 0x prefix
* @param str - String to check
* @returns True if string starts with 0x or 0X
*/
function has0xPrefix(str: string): boolean;
/**
* Remove 0x prefix from hex string
* @param hex - Hex string to strip
* @returns Hex string without 0x prefix
*/
function strip0x(hex: string): string;
/**
* Add 0x prefix to hex string
* @param hex - Hex string to prefix
* @returns Hex string with 0x prefix
*/
function prepend0x(hex: string): string;
/**
* Validate if value is a valid hex string
* @param hex - Value to validate
* @returns Type predicate for HexString
*/
function isHexString(hex: unknown): hex is HexString;
/**
* Ensure value is a valid hex string
* @param hex - Value to validate and convert
* @param includePrefix - Whether to include 0x prefix
* @returns Validated hex string
* @throws ProviderRpcError for invalid hex strings
*/
function ensureHexString(hex: unknown, includePrefix?: boolean): HexString;
/**
* Ensure hex string has even length (pad with leading zero if needed)
* @param hex - Hex string to validate
* @param includePrefix - Whether to include 0x prefix
* @returns Even-length hex string
*/
function ensureEvenLengthHexString(hex: unknown, includePrefix?: boolean): HexString;Usage Examples:
// Convert numbers to hex
const blockNumber = hexStringFromNumber(12345678);
console.log(blockNumber); // "0xbc614e"
// Work with hex string prefixes
const hexWithPrefix = "0xabcdef";
const hexWithoutPrefix = strip0x(hexWithPrefix); // "abcdef"
const restored = prepend0x(hexWithoutPrefix); // "0xabcdef"
// Validate and ensure hex strings
if (isHexString(userInput)) {
const validHex = ensureHexString(userInput, true);
console.log("Valid hex:", validHex);
}
// Handle even-length requirement
const paddedHex = ensureEvenLengthHexString("0xabc"); // "0x0abc"Functions for working with Ethereum addresses with validation and type safety.
/**
* Validate and ensure value is a valid Ethereum address
* @param str - Value to validate as address
* @returns Validated address string
* @throws ProviderRpcError for invalid addresses
*/
function ensureAddressString(str: unknown): AddressString;
/**
* Compare two address arrays for equality
* @param arr1 - First address array
* @param arr2 - Second address array
* @returns True if arrays contain same addresses in same order
*/
function areAddressArraysEqual(arr1: AddressString[], arr2: AddressString[]): boolean;Usage Examples:
// Validate addresses
try {
const userAddress = ensureAddressString("0x742d35Cc6634C0532925a3b8D186dFaedD9B6E3C");
console.log("Valid address:", userAddress);
} catch (error) {
console.error("Invalid address:", error.message);
}
// Compare address arrays
const oldAccounts = [AddressString("0x123..."), AddressString("0x456...")];
const newAccounts = [AddressString("0x123..."), AddressString("0x456...")];
const unchanged = areAddressArraysEqual(oldAccounts, newAccounts); // trueFunctions for working with integers, big integers, and numeric conversions.
/**
* Convert hex string to integer number
* @param hex - Hex string to convert
* @returns Integer representation
*/
function intNumberFromHexString(hex: HexString): IntNumber;
/**
* Ensure value is a valid integer number
* @param num - Value to validate and convert
* @returns Validated integer number
* @throws ProviderRpcError for invalid numbers
*/
function ensureIntNumber(num: unknown): IntNumber;
/**
* Convert BigInt to string representation
* @param bi - BigInt to convert
* @returns String representation of BigInt
*/
function bigIntStringFromBigInt(bi: bigint): BigIntString;
/**
* Ensure value is a valid BigInt
* @param val - Value to validate and convert
* @returns Validated BigInt
* @throws ProviderRpcError for invalid values
*/
function ensureBigInt(val: unknown): bigint;
/**
* Check if value is a BigNumber (from libraries like bn.js)
* @param val - Value to check
* @returns True if value is a BigNumber instance
*/
function isBigNumber(val: unknown): boolean;Usage Examples:
// Convert hex to numbers
const blockNumber = intNumberFromHexString(HexString("0x12345"));
console.log(blockNumber); // 74565
// Work with big integers
const largeValue = ensureBigInt("999999999999999999999");
const valueString = bigIntStringFromBigInt(largeValue);
// Validate numbers
const validInt = ensureIntNumber("42"); // IntNumber(42)
const validBigInt = ensureBigInt("0x1fffffffffffff"); // Large BigIntFunctions for working with binary data, buffers, and encoding.
/**
* Generate random bytes as hex string
* @param length - Number of bytes to generate
* @returns Random hex string
*/
function randomBytesHex(length: number): string;
/**
* Convert Uint8Array to hex string
* @param value - Uint8Array to convert
* @returns Hex string representation
*/
function uint8ArrayToHex(value: Uint8Array): string;
/**
* Convert hex string to Uint8Array
* @param hexString - Hex string to convert
* @returns Uint8Array representation
*/
function hexStringToUint8Array(hexString: string): Uint8Array;
/**
* Convert Buffer to hex string
* @param buf - Buffer to convert
* @param includePrefix - Whether to include 0x prefix
* @returns Hex string representation
*/
function hexStringFromBuffer(buf: Buffer, includePrefix?: boolean): HexString;
/**
* Encode value to hex string
* @param str - Value to encode
* @returns Hex-encoded string with 0x prefix
*/
function encodeToHexString(str: unknown): HexString;
/**
* Ensure value is a Buffer
* @param str - Value to convert to Buffer
* @returns Buffer representation
* @throws ProviderRpcError for invalid data
*/
function ensureBuffer(str: unknown): Buffer;Usage Examples:
// Generate random data
const randomId = randomBytesHex(16); // 32-character hex string
const entropy = new Uint8Array(32);
crypto.getRandomValues(entropy);
const entropyHex = uint8ArrayToHex(entropy);
// Convert between formats
const message = "Hello, World!";
const encoded = encodeToHexString(message);
const buffer = ensureBuffer(encoded);
const hexFromBuffer = hexStringFromBuffer(buffer, true);Functions for safe JSON parsing and object validation.
/**
* Ensure value is a parsed JSON object
* @param val - Value that should be JSON string or object
* @returns Parsed object
* @throws ProviderRpcError for invalid JSON
*/
function ensureParsedJSONObject<T extends object>(val: unknown): T;
/**
* Ensure value is a RegExp string
* @param regExp - RegExp to convert to string
* @returns RegExp string representation
* @throws ProviderRpcError for invalid RegExp
*/
function ensureRegExpString(regExp: unknown): RegExpString;
/**
* Create a numeric range array
* @param start - Start number (inclusive)
* @param stop - Stop number (exclusive)
* @returns Array of numbers from start to stop-1
*/
function range(start: number, stop: number): number[];Usage Examples:
// Parse JSON safely
const config = ensureParsedJSONObject<{name: string, version: string}>(
'{"name": "myapp", "version": "1.0.0"}'
);
// Work with RegExp
const pattern = /^0x[a-fA-F0-9]{40}$/;
const regexpString = ensureRegExpString(pattern);
// Generate ranges
const indices = range(0, 10); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]Functions for working with web browser APIs and DOM elements.
/**
* Get favicon URL from current page
* @returns Favicon URL or fallback favicon.ico path
*/
function getFavicon(): string | null;Usage Examples:
// Get page favicon for app metadata
const appLogoUrl = getFavicon();
const sdk = createCoinbaseWalletSDK({
appName: "My Dapp",
appLogoUrl, // Use favicon as fallback
appChainIds: [1]
});The opaque type system provides several advantages:
// Example of type safety in action
function processTransaction(
from: AddressString,
to: AddressString,
value: HexString,
chainId: IntNumber
) {
// TypeScript ensures correct types are passed
return {
from,
to,
value,
chainId: hexStringFromNumber(chainId)
};
}
// Usage with type checking
const tx = processTransaction(
ensureAddressString("0x123..."),
ensureAddressString("0x456..."),
hexStringFromNumber(1000000000000000000), // 1 ETH in wei
IntNumber(1) // Ethereum mainnet
);