/ src / lib / utils.ts
utils.ts
 1  import { toHexString } from "@dfinity/candid/lib/cjs";
 2  import { clsx, type ClassValue } from "clsx";
 3  import { CanisterStatusResponse } from "../declarations/hanse_system/hanse_system.did";
 4  import { twMerge } from "tailwind-merge";
 5  
 6  export const errorHandler = (error: Error | unknown | null): string => {
 7    // Check if an error was passed
 8    if (!error) {
 9      // Return an empty string if no error was passed
10      return "";
11    }
12  
13    const errorString = error.toString();
14  
15    // Regular expression to match the specific error text
16    // Error: Call was rejected:
17    // Request ID: c2eb7e506a48634d1f839095cea252f0b99171807b576a4518b26260bb9dbd53
18    // Reject code: 5
19    // Reject text: Canister bkyz2-fmaaa-aaaaa-qaaaq-cai trapped explicitly: User already exists!
20    const regex = /Reject text: (.*)/;
21  
22    // Use the regular expression to find the error message
23    const match = errorString.match(regex);
24  
25    // Check if a match was found
26    if (match && match[1]) {
27      // Return the extracted error message
28      return match[1];
29    } else {
30      // Return a generic error message if no specific message was found
31      return "An unknown error occurred.";
32    }
33  };
34  
35  export const objectToString = (data: any) => {
36    return JSON.stringify(
37      data,
38      (_, value) => (typeof value === "bigint" ? value.toString() : value),
39      2,
40    );
41  };
42  
43  export const getModuleHash = (
44    status: CanisterStatusResponse,
45  ): string | undefined => {
46    const moduleHash = status.module_hash;
47  
48    if (moduleHash.length === 1) {
49      return toHexString(moduleHash[0] as Uint8Array);
50    }
51    return undefined;
52  };
53  
54  export function cn(...inputs: ClassValue[]) {
55    return twMerge(clsx(inputs));
56  }
57  
58  export const focusRing =
59    "focusable-element focus:outline-none ring-inset focus:ring-1 focus:ring-foreground focus:ring-offset-2";