2026-03-03 05:37:14 +00:00
|
|
|
import { getAddress, isAddress, type Address } from 'viem';
|
|
|
|
|
|
|
|
|
|
export function isRecord(value: unknown): value is Record<string, unknown> {
|
|
|
|
|
return typeof value === 'object' && value !== null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function coerceString(value: unknown): string | null {
|
|
|
|
|
if (typeof value === 'string') {
|
|
|
|
|
const trimmed = value.trim();
|
|
|
|
|
if (trimmed.length > 0) return trimmed;
|
|
|
|
|
}
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function getErrorMessage(error: unknown, fallback: string): string {
|
|
|
|
|
if (error instanceof Error) {
|
2026-03-06 05:02:10 +00:00
|
|
|
// viem's BaseError extends Error and exposes a terse shortMessage; prefer it.
|
2026-03-06 05:13:27 +00:00
|
|
|
const short = coerceString((error as unknown as Record<string, unknown>).shortMessage);
|
2026-03-06 05:02:10 +00:00
|
|
|
if (short) return short;
|
2026-03-03 05:37:14 +00:00
|
|
|
const msg = coerceString(error.message);
|
|
|
|
|
if (msg) return msg;
|
|
|
|
|
}
|
|
|
|
|
if (isRecord(error)) {
|
|
|
|
|
const short = coerceString(error.shortMessage);
|
|
|
|
|
if (short) return short;
|
|
|
|
|
const msg = coerceString(error.message);
|
|
|
|
|
if (msg) return msg;
|
|
|
|
|
}
|
|
|
|
|
return fallback;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function ensureAddress(value: string, label: string): Address {
|
|
|
|
|
if (!value || !isAddress(value)) {
|
|
|
|
|
throw new Error(`${label} is not a valid address`);
|
|
|
|
|
}
|
|
|
|
|
return getAddress(value);
|
|
|
|
|
}
|