@chipi-stack/chipi-react 14.3.1 → 14.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/context/ChipiProvider.tsx","../src/hooks/useCreateWallet.ts","../src/hooks/useGetWallet.ts","../src/hooks/useChipiWallet.ts","../src/hooks/useChipiSession.ts","../src/hooks/useMigrateWalletToPasskey.ts","../src/hooks/useUpdateWalletEncryption.ts","../src/hooks/useTransfer.ts","../src/hooks/useApprove.ts","../src/hooks/useGetTransactionList.ts","../src/hooks/useGetTransaction.ts","../src/hooks/useGetTransactionStatus.ts","../src/hooks/useSyncOnChainTransfers.ts","../src/hooks/usePurchaseSku.ts","../src/hooks/useGetSkuPurchase.ts","../src/hooks/useGetSkuList.ts","../src/hooks/useGetSku.ts","../src/hooks/useCallAnyContract.ts","../src/hooks/useRecordSendTransaction.ts","../src/hooks/useGetTokenBalance.ts","../src/hooks/useCreateSessionKey.ts","../src/hooks/useAddSessionKeyToContract.ts","../src/hooks/useRevokeSessionKey.ts","../src/hooks/useGetSessionData.ts","../src/hooks/useExecuteWithSession.ts","../src/hooks/useX402Payment.ts"],"names":["getWebWalletEncryptKey","useQueryClient","useQuery","ChipiApiError","useMutation","useMemo","useCallback","createWalletPasskey","query","input","useState"],"mappings":";;;;;;;;;;;AAgBA,IAAM,YAAA,GAAe,cAAwC,IAAI,CAAA;AAQjE,IAAM,qBAAA,GAAwC;AAAA;AAAA,EAE5C,qBAAqB,YAAY;AAC/B,IAAA,IAAI;AACF,MAAA,OAAO,MAAMA,mBAAA,EAAuB;AAAA,IACtC,SAAS,KAAA,EAAO;AAGd,MAAA,OAAA,CAAQ,IAAA;AAAA,QACN,2DAAA;AAAA,QACA,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU;AAAA,OAC3C;AACA,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AACF,CAAA;AAGA,I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\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport { ChipiSDK } from \"@chipi-stack/backend\";\nimport type { ChipiSDKConfig } from \"@chipi-stack/types\";\nimport { getWalletEncryptKey as getWebWalletEncryptKey } from \"@chipi-stack/chipi-passkey\";\n\nexport interface PasskeyAdapter {\n getWalletEncryptKey: (input: { externalUserId: string }) => Promise<string | null>;\n}\n\ninterface ChipiContextValue {\n chipiSDK: ChipiSDK;\n config: ChipiSDKConfig;\n passkeyAdapter: PasskeyAdapter;\n}\n\nconst ChipiContext = createContext<ChipiContextValue | null>(null);\n\ninterface ChipiProviderProps {\n children: ReactNode;\n config: ChipiSDKConfig;\n passkeyAdapter?: PasskeyAdapter;\n}\n\nconst defaultPasskeyAdapter: PasskeyAdapter = {\n // Web default: attempts passkey auth, returns null on failure (caller uses PIN backup)\n getWalletEncryptKey: async () => {\n try {\n return await getWebWalletEncryptKey();\n } catch (error) {\n // Passkey failed (PRF unavailable, user cancelled, localStorage cleared)\n // Log for debugging — return null so caller can fall back to PIN backup\n console.warn(\n \"[ChipiProvider] Passkey auth failed, falling back to PIN:\",\n error instanceof Error ? error.message : error\n );\n return null;\n }\n },\n};\n\n// Default QueryClient configuration\nconst createDefaultQueryClient = () =>\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 60 * 1000, // 1 minute\n gcTime: 10 * 60 * 1000, // 10 minutes (formerly cacheTime)\n retry: (failureCount, error: any) => {\n // Don't retry on 4xx errors\n if (error?.status >= 400 && error?.status < 500) {\n return false;\n }\n return failureCount < 3;\n },\n },\n mutations: {\n retry: false,\n },\n },\n });\n\n/**\n * Provider component that wraps your app and provides Chipi SDK context with QueryClient\n */\nexport function ChipiProvider({ children, config, passkeyAdapter }: ChipiProviderProps) {\n // Create QueryClient\n const queryClient = React.useMemo(() => createDefaultQueryClient(), []);\n\n const chipiSDK = React.useMemo(() => new ChipiSDK(config), [config]);\n const resolvedPasskeyAdapter = passkeyAdapter ?? defaultPasskeyAdapter;\n\n const value = React.useMemo(\n () => ({\n chipiSDK,\n config,\n passkeyAdapter: resolvedPasskeyAdapter,\n }),\n [chipiSDK, config, resolvedPasskeyAdapter]\n );\n\n return (\n <QueryClientProvider client={queryClient}>\n <ChipiContext.Provider value={value}>{children}</ChipiContext.Provider>\n </QueryClientProvider>\n );\n}\n\n/**\n * Hook to access Chipi SDK context\n */\nexport function useChipiContext(): ChipiContextValue {\n const context = useContext(ChipiContext);\n\n if (!context) {\n throw new Error(\"useChipiContext must be used within a ChipiProvider\");\n }\n\n return context;\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { CreateWalletParams, CreateWalletResponse } from \"@chipi-stack/types\";\nimport { createWalletPasskey } from \"@chipi-stack/chipi-passkey\";\n\ntype CreateWalletInput = {\n params: CreateWalletParams;\n bearerToken: string;\n};\n\n/**\n * Hook for creating a new wallet.\n *\n * Supports dual-key wrapping: when `usePasskey: true` AND `encryptKey` (PIN) provided,\n * the private key is encrypted twice — once with the passkey-derived key (primary) and\n * once with the PIN (backup). If passkey fails later, PIN recovers the wallet.\n *\n * @example\n * ```tsx\n * // Passkey + PIN (recommended)\n * await createWalletAsync({\n * params: {\n * encryptKey: pin, // PIN backup\n * externalUserId: userId,\n * chain: Chain.STARKNET,\n * usePasskey: true, // Creates passkey + dual encryption\n * },\n * bearerToken,\n * });\n *\n * // PIN only (backward compatible)\n * await createWalletAsync({\n * params: {\n * encryptKey: pin,\n * externalUserId: userId,\n * chain: Chain.STARKNET,\n * },\n * bearerToken,\n * });\n * ```\n */\nexport function useCreateWallet(): {\n createWallet: (input: CreateWalletInput) => void;\n createWalletAsync: (input: CreateWalletInput) => Promise<CreateWalletResponse>;\n data: CreateWalletResponse | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<CreateWalletResponse, Error, CreateWalletInput> = useMutation({\n mutationFn: async (input: CreateWalletInput) => {\n let encryptKey = input.params.encryptKey;\n let encryptKeyBackup: string | undefined;\n let credentialId: string | undefined;\n let prfSupported: boolean | undefined;\n let authMethod: string | undefined;\n\n if (input.params.usePasskey) {\n if (!input.params.externalUserId) {\n throw new Error(\"externalUserId is required when using passkey\");\n }\n\n try {\n const passkeyResult = await createWalletPasskey(\n input.params.externalUserId,\n input.params.externalUserId\n );\n\n credentialId = passkeyResult.credentialId;\n prfSupported = passkeyResult.prfSupported;\n\n if (encryptKey) {\n // Dual-key mode: passkey is primary, PIN is backup\n encryptKeyBackup = encryptKey;\n encryptKey = passkeyResult.encryptKey;\n authMethod = \"passkey+pin\";\n } else {\n // Passkey-only mode (no PIN backup — not recommended)\n encryptKey = passkeyResult.encryptKey;\n authMethod = \"passkey\";\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Passkey creation failed: ${error.message}`);\n }\n throw new Error(\"Failed to create passkey for wallet\");\n }\n } else {\n // PIN-only mode\n authMethod = encryptKey ? \"pin\" : undefined;\n }\n\n if (!encryptKey) {\n throw new Error(\"encryptKey is required when usePasskey is false\");\n }\n\n return chipiSDK.createWallet({\n params: {\n ...input.params,\n encryptKey,\n encryptKeyBackup,\n authMethod: authMethod as any,\n credentialId,\n prfSupported,\n deviceType: \"web\",\n },\n bearerToken: input.bearerToken,\n });\n },\n });\n\n return {\n createWallet: mutation.mutate,\n createWalletAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { GetWalletParams, GetWalletResponse } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype GetWalletInput = {\n params?: GetWalletParams;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<GetWalletResponse | null, Error>, \"queryKey\" | \"queryFn\">;\n};\n\nexport function useGetWallet(input?: GetWalletInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const query = useQuery<GetWalletResponse | null, Error>({\n queryKey: [\"wallet\", input?.params?.externalUserId],\n queryFn: async () => {\n if (!input || !input.params || !input.getBearerToken) throw new Error(\"Input is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getWallet(input.params, bearerToken);\n },\n enabled: Boolean(\n input?.params?.externalUserId &&\n input?.getBearerToken &&\n input.params.externalUserId.trim() !== \"\"\n ),\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchWallet = async (newInput: GetWalletInput): Promise<GetWalletResponse | null> => {\n return queryClient.fetchQuery({\n queryKey: [\"wallet\", newInput?.params?.externalUserId],\n queryFn: async () => {\n if (!newInput || !newInput.getBearerToken || !newInput.params)\n throw new Error(\"Input is required\");\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getWallet(newInput.params, bearerToken);\n },\n retry: (failureCount, error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchWallet,\n };\n}\n","\"use client\";\n\nimport { useCallback, useMemo } from \"react\";\nimport { useQuery, useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\nimport {\n type WalletType,\n type GetWalletResponse,\n type CreateWalletResponse,\n type GetTokenBalanceResponse,\n Chain,\n ChainToken,\n} from \"@chipi-stack/types\";\n\n/**\n * Configuration for useChipiWallet hook\n */\nexport interface UseChipiWalletConfig {\n /** External user ID (e.g., from Clerk, Firebase, etc.) */\n externalUserId: string | null | undefined;\n /** Function to get the bearer token for API calls */\n getBearerToken: () => Promise<string | null | undefined>;\n /** Default token for balance display (defaults to USDC) */\n defaultToken?: ChainToken;\n /** Whether to automatically fetch wallet on mount */\n enabled?: boolean;\n}\n\n/**\n * Extended wallet response with additional computed properties\n */\nexport interface ChipiWalletData extends GetWalletResponse {\n /** Whether this wallet supports session keys */\n supportsSessionKeys: boolean;\n /** Formatted short address for display */\n shortAddress: string;\n}\n\n/**\n * Return type for useChipiWallet hook\n */\nexport interface UseChipiWalletReturn {\n // Wallet data\n /** The user's wallet data, null if not found, undefined if loading */\n wallet: ChipiWalletData | null | undefined;\n /** Whether the user has a wallet */\n hasWallet: boolean;\n /** Whether the wallet is currently being fetched */\n isLoadingWallet: boolean;\n /** Error from fetching wallet */\n walletError: Error | null;\n\n // Balance data\n /** The wallet's balance for the default token */\n balance: GetTokenBalanceResponse | undefined;\n /** Formatted balance string (e.g., \"100.50\") */\n formattedBalance: string;\n /** Whether balance is loading */\n isLoadingBalance: boolean;\n\n // Create wallet\n /** Create a new wallet */\n\n createWallet: (params: {\n encryptKey: string;\n walletType?: WalletType;\n }) => Promise<CreateWalletResponse>;\n /** Whether wallet creation is in progress */\n isCreating: boolean;\n /** Data from the last wallet creation */\n createdWallet: CreateWalletResponse | undefined;\n\n // Actions\n /** Refetch the wallet data */\n refetchWallet: () => Promise<void>;\n /** Refetch the balance */\n refetchBalance: () => Promise<void>;\n /** Refetch both wallet and balance */\n refetchAll: () => Promise<void>;\n}\n\n/**\n * All-in-one wallet hook for Chipi SDK.\n *\n * Combines wallet fetching, creation, and balance checking into a single hook\n * for simplified wallet management.\n *\n * @example\n * ```tsx\n * import { useAuth } from \"@clerk/nextjs\";\n * import { useChipiWallet } from \"@chipi-stack/nextjs\";\n *\n * function WalletComponent() {\n * const { userId, getToken } = useAuth();\n * const {\n * wallet,\n * hasWallet,\n * balance,\n * formattedBalance,\n * createWallet,\n * isCreating,\n * isLoadingWallet,\n * } = useChipiWallet({\n * externalUserId: userId,\n * getBearerToken: getToken,\n * });\n *\n * if (isLoadingWallet) return <div>Loading...</div>;\n *\n * if (!hasWallet) {\n * return (\n * <button\n * onClick={() => createWallet({ encryptKey: \"1234\" })}\n * disabled={isCreating}\n * >\n * {isCreating ? \"Creating...\" : \"Create Wallet\"}\n * </button>\n * );\n * }\n *\n * return (\n * <div>\n * <p>Address: {wallet?.shortAddress}</p>\n * <p>Balance: ${formattedBalance} USDC</p>\n * <p>Session Keys: {wallet?.supportsSessionKeys ? \"Yes\" : \"No\"}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport function useChipiWallet(config: UseChipiWalletConfig): UseChipiWalletReturn {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const { externalUserId, getBearerToken, defaultToken = \"USDC\", enabled = true } = config;\n\n const trimmedUserId = externalUserId?.trim() || null;\n\n const isEnabled = Boolean(enabled && trimmedUserId);\n\n // ============ Wallet Query ============\n const walletQuery = useQuery<GetWalletResponse | null, Error>({\n queryKey: [\"chipi-wallet\", trimmedUserId],\n queryFn: async () => {\n if (!trimmedUserId) return null;\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getWallet({ externalUserId: trimmedUserId }, bearerToken);\n },\n enabled: isEnabled,\n retry: (failureCount, error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n });\n\n // ============ Balance Query ============\n const walletPublicKey = walletQuery.data?.publicKey;\n\n const balanceQuery = useQuery<GetTokenBalanceResponse, Error>({\n queryKey: [\"chipi-wallet-balance\", walletPublicKey, defaultToken],\n queryFn: async () => {\n if (!walletPublicKey) throw new Error(\"No wallet\");\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTokenBalance(\n {\n chain: Chain.STARKNET,\n chainToken: defaultToken as ChainToken,\n walletPublicKey,\n },\n bearerToken\n );\n },\n enabled: Boolean(isEnabled && walletPublicKey),\n retry: (failureCount, error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n });\n\n // ============ Create Wallet Mutation ============\n const createWalletMutation = useMutation<\n CreateWalletResponse,\n Error,\n { encryptKey: string; walletType?: WalletType }\n >({\n mutationFn: async ({ encryptKey, walletType = \"CHIPI\" }) => {\n if (!trimmedUserId) throw new Error(\"External user ID is required\");\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n return chipiSDK.createWallet({\n params: {\n chain: Chain.STARKNET,\n encryptKey,\n externalUserId: trimmedUserId,\n walletType,\n },\n bearerToken,\n });\n },\n onSuccess: () => {\n // Invalidate wallet query to refetch\n queryClient.invalidateQueries({\n queryKey: [\"chipi-wallet\", trimmedUserId],\n });\n },\n });\n\n // ============ Computed Values ============\n const wallet = useMemo<ChipiWalletData | null | undefined>(() => {\n if (walletQuery.isLoading) return undefined;\n if (!walletQuery.data) return null;\n\n const data = walletQuery.data;\n return {\n ...data,\n supportsSessionKeys: data.walletType === \"CHIPI\",\n shortAddress: formatAddress(data.publicKey),\n };\n }, [walletQuery.data, walletQuery.isLoading]);\n\n const formattedBalance = useMemo(() => {\n if (!balanceQuery.data?.balance) return \"0.00\";\n const num = Number(balanceQuery.data.balance);\n return num.toLocaleString(undefined, {\n minimumFractionDigits: 2,\n maximumFractionDigits:\n defaultToken === ChainToken.ETH || defaultToken === ChainToken.STRK ? 6 : 2,\n });\n }, [balanceQuery.data, defaultToken]);\n\n // ============ Actions ============\n const refetchWallet = useCallback(async () => {\n await walletQuery.refetch();\n }, [walletQuery]);\n\n const refetchBalance = useCallback(async () => {\n await balanceQuery.refetch();\n }, [balanceQuery]);\n\n const refetchAll = useCallback(async () => {\n await Promise.all([walletQuery.refetch(), balanceQuery.refetch()]);\n }, [walletQuery, balanceQuery]);\n\n const createWallet = useCallback(\n async (params: { encryptKey: string; walletType?: WalletType }) => {\n return createWalletMutation.mutateAsync(params);\n },\n [createWalletMutation]\n );\n\n return {\n // Wallet data\n wallet,\n hasWallet: wallet !== null && wallet !== undefined,\n isLoadingWallet: walletQuery.isLoading,\n walletError: walletQuery.error,\n\n // Balance data\n balance: balanceQuery.data,\n formattedBalance,\n isLoadingBalance: balanceQuery.isLoading,\n\n // Create wallet\n createWallet,\n isCreating: createWalletMutation.isPending,\n createdWallet: createWalletMutation.data,\n\n // Actions\n refetchWallet,\n refetchBalance,\n refetchAll,\n };\n}\n\n/**\n * Format a wallet address for display\n */\nfunction formatAddress(address: string, chars = 6): string {\n if (!address || address.length < chars * 2) return address;\n return `${address.slice(0, chars + 2)}...${address.slice(-chars)}`;\n}\n","\"use client\";\n\nimport { useCallback, useMemo, useState, useEffect } from \"react\";\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type {\n SessionKeyData,\n SessionConfig,\n SessionDataResponse,\n WalletData,\n WalletType,\n CreateSessionKeyParams,\n Call,\n SpendingPolicyConfig,\n SpendingPolicyData,\n} from \"@chipi-stack/types\";\n\n/**\n * Wallet data with optional wallet type for session operations\n */\nexport interface SessionWallet extends WalletData {\n walletType?: WalletType;\n}\n\n/**\n * Configuration for useChipiSession hook\n */\nexport interface UseChipiSessionConfig {\n /** Wallet data (must be a CHIPI wallet for session support) */\n wallet: SessionWallet | null | undefined;\n /** Encryption key (user's PIN) for signing operations */\n encryptKey: string;\n /** Function to get the bearer token for API calls */\n getBearerToken: () => Promise<string | null | undefined>;\n /** Previously stored session data (from Clerk metadata, database, etc.) */\n storedSession?: SessionKeyData | null;\n /** Callback fired when a new session is created (for persistence) */\n onSessionCreated?: (session: SessionKeyData) => void | Promise<void>;\n /** Session duration in seconds (default: 6 hours) */\n defaultDurationSeconds?: number;\n /** Default max calls for session registration (default: 1000) */\n defaultMaxCalls?: number;\n /** Whether to auto-check session status on mount */\n autoCheckStatus?: boolean;\n}\n\n/**\n * Session lifecycle state\n */\nexport type SessionState =\n | \"none\" // No session exists\n | \"created\" // Session created locally, not registered on-chain\n | \"active\" // Session registered and active on-chain\n | \"expired\" // Session has expired\n | \"revoked\"; // Session has been revoked\n\n/**\n * Return type for useChipiSession hook\n */\nexport interface UseChipiSessionReturn {\n // Session data\n /** Current session key data */\n session: SessionKeyData | null;\n /** On-chain session status (from contract query) */\n sessionStatus: SessionDataResponse | undefined;\n /** Current session lifecycle state */\n sessionState: SessionState;\n /** Whether there is an active, usable session */\n hasActiveSession: boolean;\n /** Whether the session has expired */\n isSessionExpired: boolean;\n /** Remaining calls available for the session */\n remainingCalls: number | undefined;\n /** Whether the wallet supports sessions (CHIPI wallet) */\n supportsSession: boolean;\n\n // Actions\n /** Create a new session keypair locally (does NOT register on-chain) */\n createSession: (config?: Partial<CreateSessionKeyParams>) => Promise<SessionKeyData>;\n /** Register the current session on the blockchain */\n registerSession: (config?: Partial<SessionConfig>) => Promise<string>;\n /** Revoke the current session from the blockchain */\n revokeSession: () => Promise<string>;\n /** Execute calls using the session key (no owner signature needed) */\n executeWithSession: (calls: Call[]) => Promise<string>;\n /** Clear the current session from local state */\n clearSession: () => void;\n /** Refresh the on-chain session status */\n refetchStatus: () => Promise<void>;\n\n // Spending Policy Actions\n /** Set a spending policy for the current session + token pair */\n setSpendingPolicy: (config: Omit<SpendingPolicyConfig, \"sessionPublicKey\">) => Promise<string>;\n /** Query the spending policy for a token (read-only, no gas) */\n getSpendingPolicy: (token: string) => Promise<SpendingPolicyData>;\n /** Remove a spending policy for a token */\n removeSpendingPolicy: (token: string) => Promise<string>;\n\n // Loading states\n isCreating: boolean;\n isRegistering: boolean;\n isRevoking: boolean;\n isExecuting: boolean;\n isLoadingStatus: boolean;\n isSettingSpendingPolicy: boolean;\n isRemovingSpendingPolicy: boolean;\n\n // Errors\n error: Error | null;\n}\n\n/**\n * All-in-one session management hook for Chipi SDK.\n *\n * Combines session creation, registration, execution, and revocation\n * into a single unified API. Session keys enable gasless transactions\n * without requiring the owner's private key for each operation.\n *\n * **Important:** Sessions only work with CHIPI wallets. ARGENT wallets\n * do not support session keys.\n *\n * @example\n * ```tsx\n * import { useAuth } from \"@clerk/nextjs\";\n * import { useChipiWallet, useChipiSession } from \"@chipi-stack/nextjs\";\n *\n * function SessionComponent() {\n * const { userId, getToken } = useAuth();\n * const [pin, setPin] = useState(\"\");\n * const { wallet } = useChipiWallet({ externalUserId: userId, getBearerToken: getToken });\n *\n * const {\n * session,\n * hasActiveSession,\n * sessionState,\n * createSession,\n * registerSession,\n * executeWithSession,\n * isCreating,\n * isRegistering,\n * } = useChipiSession({\n * wallet,\n * encryptKey: pin,\n * getBearerToken: getToken,\n * onSessionCreated: async (newSession) => {\n * // Persist to Clerk metadata or database\n * await saveSessionToClerk(newSession);\n * },\n * });\n *\n * const handleSetupSession = async () => {\n * // Step 1: Create session locally\n * await createSession();\n * // Step 2: Register on-chain\n * await registerSession();\n * };\n *\n * const handleTransfer = async () => {\n * // Execute transfer using session (no PIN needed after setup)\n * await executeWithSession([{\n * contractAddress: USDC_ADDRESS,\n * entrypoint: \"transfer\",\n * calldata: [recipient, amount, \"0x0\"],\n * }]);\n * };\n *\n * return (\n * <div>\n * <p>Session State: {sessionState}</p>\n * {!hasActiveSession ? (\n * <button onClick={handleSetupSession} disabled={isCreating || isRegistering}>\n * Setup Session\n * </button>\n * ) : (\n * <button onClick={handleTransfer}>\n * Transfer (Gasless)\n * </button>\n * )}\n * </div>\n * );\n * }\n * ```\n */\nexport function useChipiSession(config: UseChipiSessionConfig): UseChipiSessionReturn {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const {\n wallet,\n encryptKey,\n getBearerToken,\n storedSession,\n onSessionCreated,\n defaultDurationSeconds = 21600, // 6 hours\n defaultMaxCalls = 1000,\n autoCheckStatus = true,\n } = config;\n\n // ============ Local Session State ============\n const [localSession, setLocalSession] = useState<SessionKeyData | null>(storedSession ?? null);\n const [error, setError] = useState<Error | null>(null);\n\n // Sync stored session when it changes\n useEffect(() => {\n setLocalSession(storedSession ?? null);\n }, [storedSession]);\n\n // ============ Computed Values ============\n const supportsSession = useMemo(() => {\n if (!wallet) return false;\n // CHIPI wallets support sessions, ARGENT wallets don't\n // If walletType is undefined (legacy), assume it doesn't support sessions\n return wallet.walletType === \"CHIPI\";\n }, [wallet]);\n\n // ============ Session Status Query ============\n const sessionStatusQuery = useQuery<SessionDataResponse | null, Error>({\n queryKey: [\"chipi-session-status\", wallet?.publicKey, localSession?.publicKey],\n queryFn: async () => {\n if (!wallet?.publicKey || !localSession?.publicKey) return null;\n return chipiSDK.sessions.getSessionData({\n walletAddress: wallet.publicKey,\n sessionPublicKey: localSession.publicKey,\n });\n },\n enabled: Boolean(\n autoCheckStatus && wallet?.publicKey && localSession?.publicKey && supportsSession\n ),\n staleTime: 30000, // 30 seconds\n });\n\n // ============ Session State Computation ============\n const sessionState = useMemo<SessionState>(() => {\n if (!localSession) return \"none\";\n\n const status = sessionStatusQuery.data;\n\n // If we have status data from the contract\n if (status) {\n if (!status.isActive) return \"revoked\";\n if (status.validUntil * 1000 < Date.now()) return \"expired\";\n if (status.remainingCalls <= 0) return \"expired\";\n return \"active\";\n }\n\n // No status data yet - check local expiration\n if (localSession.validUntil * 1000 < Date.now()) return \"expired\";\n\n // Session exists locally but no on-chain status - assume created but not registered\n return \"created\";\n }, [localSession, sessionStatusQuery.data]);\n\n const hasActiveSession = sessionState === \"active\";\n const isSessionExpired = sessionState === \"expired\";\n const remainingCalls = sessionStatusQuery.data?.remainingCalls;\n\n // ============ Create Session Mutation ============\n const createSessionMutation = useMutation<SessionKeyData, Error, Partial<CreateSessionKeyParams>>(\n {\n mutationFn: async (params = {}) => {\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!supportsSession)\n throw new Error(\n \"Wallet does not support sessions. Only CHIPI wallets support session keys.\"\n );\n\n const sessionData = chipiSDK.sessions.createSessionKey({\n encryptKey,\n durationSeconds: params.durationSeconds ?? defaultDurationSeconds,\n });\n\n return sessionData;\n },\n onSuccess: async (sessionData) => {\n setLocalSession(sessionData);\n setError(null);\n\n // Call the persistence callback if provided\n if (onSessionCreated) {\n await onSessionCreated(sessionData);\n }\n },\n onError: (err) => {\n setError(err);\n },\n }\n );\n\n // ============ Register Session Mutation ============\n const registerSessionMutation = useMutation<string, Error, Partial<SessionConfig>>({\n mutationFn: async (sessionConfig = {}) => {\n if (!wallet) throw new Error(\"Wallet is required\");\n if (!localSession) throw new Error(\"No session to register. Call createSession first.\");\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!supportsSession) throw new Error(\"Wallet does not support sessions\");\n\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.sessions.addSessionKeyToContract(\n {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n sessionConfig: {\n sessionPublicKey: localSession.publicKey,\n validUntil: sessionConfig.validUntil ?? localSession.validUntil,\n maxCalls: sessionConfig.maxCalls ?? defaultMaxCalls,\n allowedEntrypoints: sessionConfig.allowedEntrypoints ?? [],\n },\n },\n bearerToken\n );\n\n return txHash;\n },\n onSuccess: () => {\n setError(null);\n // Invalidate session status to refetch\n queryClient.invalidateQueries({\n queryKey: [\"chipi-session-status\", wallet?.publicKey, localSession?.publicKey],\n });\n },\n onError: (err) => {\n setError(err);\n },\n });\n\n // ============ Revoke Session Mutation ============\n const revokeSessionMutation = useMutation<string, Error, void>({\n mutationFn: async () => {\n if (!wallet) throw new Error(\"Wallet is required\");\n if (!localSession) throw new Error(\"No session to revoke\");\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!supportsSession) throw new Error(\"Wallet does not support sessions\");\n\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.sessions.revokeSessionKey(\n {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n sessionPublicKey: localSession.publicKey,\n },\n bearerToken\n );\n\n return txHash;\n },\n onSuccess: () => {\n setError(null);\n // Invalidate session status\n queryClient.invalidateQueries({\n queryKey: [\"chipi-session-status\", wallet?.publicKey, localSession?.publicKey],\n });\n },\n onError: (err) => {\n setError(err);\n },\n });\n\n // ============ Execute With Session Mutation ============\n const executeWithSessionMutation = useMutation<string, Error, Call[]>({\n mutationFn: async (calls) => {\n if (!wallet) throw new Error(\"Wallet is required\");\n if (!localSession) throw new Error(\"No active session\");\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!hasActiveSession) throw new Error(\"Session is not active. Register the session first.\");\n\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.executeTransactionWithSession({\n params: {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n session: localSession,\n calls,\n },\n bearerToken,\n });\n\n return txHash;\n },\n onSuccess: () => {\n setError(null);\n // Refetch status to update remaining calls\n queryClient.invalidateQueries({\n queryKey: [\"chipi-session-status\", wallet?.publicKey, localSession?.publicKey],\n });\n },\n onError: (err) => {\n setError(err);\n },\n });\n\n // ============ Set Spending Policy Mutation ============\n const setSpendingPolicyMutation = useMutation<\n string,\n Error,\n Omit<SpendingPolicyConfig, \"sessionPublicKey\">\n >({\n mutationFn: async (policyConfig) => {\n if (!wallet) throw new Error(\"Wallet is required\");\n if (!localSession)\n throw new Error(\"No session to set policy on. Create and register a session first.\");\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!supportsSession) throw new Error(\"Wallet does not support sessions\");\n\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.sessions.setSpendingPolicy(\n {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n spendingPolicyConfig: {\n sessionPublicKey: localSession.publicKey,\n ...policyConfig,\n },\n },\n bearerToken\n );\n\n return txHash;\n },\n onSuccess: () => {\n setError(null);\n },\n onError: (err) => {\n setError(err);\n },\n });\n\n // ============ Remove Spending Policy Mutation ============\n const removeSpendingPolicyMutation = useMutation<string, Error, string>({\n mutationFn: async (token) => {\n if (!wallet) throw new Error(\"Wallet is required\");\n if (!localSession) throw new Error(\"No session to remove policy from\");\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!supportsSession) throw new Error(\"Wallet does not support sessions\");\n\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.sessions.removeSpendingPolicy(\n {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n sessionPublicKey: localSession.publicKey,\n token,\n },\n bearerToken\n );\n\n return txHash;\n },\n onSuccess: () => {\n setError(null);\n },\n onError: (err) => {\n setError(err);\n },\n });\n\n // ============ Actions ============\n const createSession = useCallback(\n async (params?: Partial<CreateSessionKeyParams>) => {\n return createSessionMutation.mutateAsync(params ?? {});\n },\n [createSessionMutation]\n );\n\n const registerSession = useCallback(\n async (sessionConfig?: Partial<SessionConfig>) => {\n return registerSessionMutation.mutateAsync(sessionConfig ?? {});\n },\n [registerSessionMutation]\n );\n\n const revokeSession = useCallback(async () => {\n return revokeSessionMutation.mutateAsync();\n }, [revokeSessionMutation]);\n\n const executeWithSession = useCallback(\n async (calls: Call[]) => {\n return executeWithSessionMutation.mutateAsync(calls);\n },\n [executeWithSessionMutation]\n );\n\n const clearSession = useCallback(() => {\n setLocalSession(null);\n setError(null);\n }, []);\n\n const refetchStatus = useCallback(async () => {\n await sessionStatusQuery.refetch();\n }, [sessionStatusQuery]);\n\n const setSpendingPolicy = useCallback(\n async (policyConfig: Omit<SpendingPolicyConfig, \"sessionPublicKey\">) => {\n return setSpendingPolicyMutation.mutateAsync(policyConfig);\n },\n [setSpendingPolicyMutation]\n );\n\n const getSpendingPolicy = useCallback(\n async (token: string): Promise<SpendingPolicyData> => {\n if (!wallet?.publicKey) throw new Error(\"Wallet is required\");\n if (!localSession?.publicKey) throw new Error(\"No session to query policy for\");\n return chipiSDK.sessions.getSpendingPolicy({\n walletAddress: wallet.publicKey,\n sessionPublicKey: localSession.publicKey,\n token,\n });\n },\n [chipiSDK, wallet, localSession]\n );\n\n const removeSpendingPolicy = useCallback(\n async (token: string) => {\n return removeSpendingPolicyMutation.mutateAsync(token);\n },\n [removeSpendingPolicyMutation]\n );\n\n // ============ Combined Error ============\n const combinedError = useMemo(() => {\n return (\n error ||\n createSessionMutation.error ||\n registerSessionMutation.error ||\n revokeSessionMutation.error ||\n executeWithSessionMutation.error ||\n setSpendingPolicyMutation.error ||\n removeSpendingPolicyMutation.error ||\n sessionStatusQuery.error ||\n null\n );\n }, [\n error,\n createSessionMutation.error,\n registerSessionMutation.error,\n revokeSessionMutation.error,\n executeWithSessionMutation.error,\n setSpendingPolicyMutation.error,\n removeSpendingPolicyMutation.error,\n sessionStatusQuery.error,\n ]);\n\n return {\n // Session data\n session: localSession,\n sessionStatus: sessionStatusQuery.data ?? undefined,\n sessionState,\n hasActiveSession,\n isSessionExpired,\n remainingCalls,\n supportsSession,\n\n // Actions\n createSession,\n registerSession,\n revokeSession,\n executeWithSession,\n clearSession,\n refetchStatus,\n\n // Spending Policy Actions\n setSpendingPolicy,\n getSpendingPolicy,\n removeSpendingPolicy,\n\n // Loading states\n isCreating: createSessionMutation.isPending,\n isRegistering: registerSessionMutation.isPending,\n isRevoking: revokeSessionMutation.isPending,\n isExecuting: executeWithSessionMutation.isPending,\n isLoadingStatus: sessionStatusQuery.isLoading,\n isSettingSpendingPolicy: setSpendingPolicyMutation.isPending,\n isRemovingSpendingPolicy: removeSpendingPolicyMutation.isPending,\n\n // Errors\n error: combinedError,\n };\n}\n","import { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { MigrateWalletToPasskeyParams, WalletData } from \"@chipi-stack/types\";\nimport { createWalletPasskey } from \"@chipi-stack/chipi-passkey\";\nimport { decryptPrivateKey, encryptPrivateKey, type ChipiWallets } from \"@chipi-stack/backend\";\n\ntype MigrateWalletToPasskeyInput = MigrateWalletToPasskeyParams & {\n bearerToken: string;\n};\n\ninterface MigrateWalletToPasskeyResult {\n success: boolean;\n wallet: WalletData;\n credentialId: string;\n}\n\n/**\n * Hook for migrating a wallet from encryptKey (PIN) to passkey authentication\n */\nexport function useMigrateWalletToPasskey(): {\n migrateWalletToPasskey: (input: MigrateWalletToPasskeyInput) => void;\n migrateWalletToPasskeyAsync: (\n input: MigrateWalletToPasskeyInput\n ) => Promise<MigrateWalletToPasskeyResult>;\n data: MigrateWalletToPasskeyResult | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const mutation: UseMutationResult<\n MigrateWalletToPasskeyResult,\n Error,\n MigrateWalletToPasskeyInput\n > = useMutation({\n mutationFn: async (input: MigrateWalletToPasskeyInput) => {\n const { wallet, oldEncryptKey, externalUserId, bearerToken } = input;\n\n try {\n // Step 1: Validate old encryptKey by decrypting first (before creating passkey)\n let decryptedPrivateKey: string;\n try {\n decryptedPrivateKey = decryptPrivateKey(wallet.encryptedPrivateKey, oldEncryptKey);\n } catch {\n throw new Error(\n \"Failed to decrypt wallet with provided encryptKey. Please verify your PIN/password is correct.\"\n );\n }\n\n // Step 2: Create new passkey only after PIN is confirmed valid\n const passkeyResult = await createWalletPasskey(\n externalUserId,\n externalUserId // Using externalUserId as userName\n );\n\n // Step 3: Re-encrypt with new passkey-derived encryptKey\n const newEncryptedPrivateKey = encryptPrivateKey(\n decryptedPrivateKey,\n passkeyResult.encryptKey\n );\n\n // Step 4: Persist new encrypted key to backend\n const updateResult = await (chipiSDK.wallets as ChipiWallets).updateWalletEncryption(\n {\n externalUserId,\n newEncryptedPrivateKey,\n publicKey: wallet.publicKey,\n },\n bearerToken\n );\n\n if (updateResult?.success === false) {\n throw new Error(\"Backend rejected wallet encryption update\");\n }\n\n const updatedWallet: WalletData = {\n ...wallet,\n encryptedPrivateKey: newEncryptedPrivateKey,\n };\n\n // Invalidate cached wallet so useChipiWallet/useGetWallet refetch\n queryClient.invalidateQueries({\n queryKey: [\"chipi-wallet\", externalUserId],\n });\n queryClient.invalidateQueries({\n queryKey: [\"wallet\", externalUserId],\n });\n\n return {\n success: true,\n wallet: updatedWallet,\n credentialId: passkeyResult.credentialId,\n };\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Migration failed: ${error.message}`);\n }\n throw new Error(\"Failed to migrate wallet to passkey\");\n }\n },\n });\n\n return {\n migrateWalletToPasskey: mutation.mutate,\n migrateWalletToPasskeyAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type {\n UpdateWalletEncryptionParams,\n UpdateWalletEncryptionResponse,\n} from \"@chipi-stack/types\";\nimport { ChipiWallets } from \"@chipi-stack/backend\";\n\ntype UpdateWalletEncryptionInput = UpdateWalletEncryptionParams & {\n bearerToken: string;\n};\n\n/**\n * Hook for updating a wallet's encrypted private key.\n * Use when the user changes their passkey or PIN; the client re-encrypts the private key\n * and sends the new ciphertext here.\n */\nexport function useUpdateWalletEncryption(): {\n updateWalletEncryption: (input: UpdateWalletEncryptionInput) => void;\n updateWalletEncryptionAsync: (\n input: UpdateWalletEncryptionInput\n ) => Promise<UpdateWalletEncryptionResponse>;\n data: UpdateWalletEncryptionResponse | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const mutation: UseMutationResult<\n UpdateWalletEncryptionResponse,\n Error,\n UpdateWalletEncryptionInput\n > = useMutation({\n mutationFn: async (input: UpdateWalletEncryptionInput) => {\n const { bearerToken, ...params } = input;\n return (chipiSDK.wallets as ChipiWallets).updateWalletEncryption(params, bearerToken);\n },\n onSuccess: (_, variables) => {\n queryClient.invalidateQueries({\n queryKey: [\"chipi-wallet\", variables.externalUserId],\n });\n },\n });\n\n return {\n updateWalletEncryption: mutation.mutate,\n updateWalletEncryptionAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { TransferHookInput, WalletData } from \"@chipi-stack/types\";\n\ntype TransferInput = {\n params: TransferHookInput;\n bearerToken: string;\n};\n\n/**\n * Configuration for useTransfer hook.\n */\nexport interface UseTransferConfig {\n /**\n * Callback to prompt user for PIN when passkey fails.\n * Should show a PIN input dialog and return the PIN, or null to cancel.\n * Only called when usePasskey: true and passkey auth fails.\n */\n onPinRequired?: () => Promise<string | null>;\n}\n\n/**\n * Hook for transferring tokens.\n *\n * When `usePasskey: true`:\n * 1. Tries passkey authentication first\n * 2. If passkey fails and wallet has `encryptedPrivateKeyBackup`:\n * calls `onPinRequired` to get PIN, uses PIN to decrypt backup\n * 3. If no backup or no `onPinRequired`, throws\n *\n * @example\n * ```tsx\n * const { transferAsync } = useTransfer({\n * onPinRequired: async () => {\n * // Show PIN dialog, return PIN or null to cancel\n * return await showPinDialog();\n * },\n * });\n * ```\n */\nexport function useTransfer(config?: UseTransferConfig): {\n transfer: (input: TransferInput) => void;\n transferAsync: (input: TransferInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK, passkeyAdapter } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, TransferInput> = useMutation({\n mutationFn: async (input: TransferInput) => {\n let encryptKey = input.params.encryptKey;\n let walletForTransfer = input.params.wallet;\n\n // If usePasskey is true, try passkey first, fall back to PIN\n if (input.params.usePasskey) {\n if (!input.params.externalUserId) {\n throw new Error(\"externalUserId is required when usePasskey is true\");\n }\n\n // Try passkey authentication\n const passkeyKey = await passkeyAdapter.getWalletEncryptKey({\n externalUserId: input.params.externalUserId,\n });\n\n if (passkeyKey) {\n // Passkey succeeded — use passkey key with primary encryptedPrivateKey\n encryptKey = passkeyKey;\n } else {\n // Passkey failed (PRF unavailable, user cancelled, etc.)\n // Try PIN backup if wallet has encryptedPrivateKeyBackup\n const wallet = input.params.wallet as WalletData & {\n encryptedPrivateKeyBackup?: string;\n };\n\n if (wallet.encryptedPrivateKeyBackup && config?.onPinRequired) {\n const pin = await config.onPinRequired();\n if (!pin) {\n throw new Error(\"Transfer cancelled — PIN required as passkey fallback\");\n }\n encryptKey = pin;\n // Use the backup encrypted key for decryption\n walletForTransfer = {\n ...wallet,\n encryptedPrivateKey: wallet.encryptedPrivateKeyBackup,\n };\n } else if (wallet.encryptedPrivateKeyBackup) {\n throw new Error(\n \"Passkey authentication failed. Provide an onPinRequired callback to use PIN backup.\"\n );\n } else {\n throw new Error(\"Passkey authentication failed and no PIN backup available.\");\n }\n }\n }\n\n if (!encryptKey) {\n throw new Error(\"encryptKey is required when usePasskey is false\");\n }\n\n const {\n usePasskey: _usePasskey,\n externalUserId: _externalUserId,\n ...transferParams\n } = input.params;\n return chipiSDK.transfer({\n params: {\n ...transferParams,\n wallet: walletForTransfer,\n amount: String(transferParams.amount),\n encryptKey: encryptKey,\n },\n bearerToken: input.bearerToken,\n });\n },\n });\n\n return {\n transfer: mutation.mutate,\n transferAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { ApproveHookInput } from \"@chipi-stack/types\";\n\ntype ApproveInput = {\n params: ApproveHookInput;\n bearerToken: string;\n};\n\n/**\n * Hook for approving token spending\n */\nexport function useApprove(): {\n approve: (params: ApproveInput) => void;\n approveAsync: (params: ApproveInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK, passkeyAdapter } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, ApproveInput> = useMutation({\n mutationFn: async (params: ApproveInput) => {\n let encryptKey = params.params.encryptKey;\n\n // If usePasskey is true, authenticate with passkey to get encryptKey\n if (params.params.usePasskey) {\n if (!params.params.externalUserId) {\n throw new Error(\"externalUserId is required when usePasskey is true\");\n }\n try {\n const key = await passkeyAdapter.getWalletEncryptKey({\n externalUserId: params.params.externalUserId,\n });\n if (!key) {\n throw new Error(\"Passkey authentication was cancelled\");\n }\n encryptKey = key;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Passkey authentication failed: ${error.message}`);\n }\n throw new Error(\"Failed to authenticate with passkey\");\n }\n }\n\n if (!encryptKey) {\n throw new Error(\n \"encryptKey is required when usePasskey is false. Provide a PIN or enable usePasskey.\"\n );\n }\n\n const {\n usePasskey: _usePasskey,\n externalUserId: _externalUserId,\n ...approveParams\n } = params.params;\n return chipiSDK.approve({\n params: {\n ...approveParams,\n amount: String(approveParams.amount),\n encryptKey,\n },\n bearerToken: params.bearerToken,\n });\n },\n });\n\n return {\n approve: mutation.mutate,\n approveAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { PaginatedResponse, Transaction, GetTransactionListQuery } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype TransactionListInput = {\n query: GetTransactionListQuery;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<\n UseQueryOptions<PaginatedResponse<Transaction>, Error>,\n \"queryKey\" | \"queryFn\"\n >;\n};\n\ntype FetchTransactionListInput = {\n query: GetTransactionListQuery;\n getBearerToken: () => Promise<string | null | undefined>;\n};\n\nexport function useGetTransactionList(input?: TransactionListInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const buildQueryKey = (q?: GetTransactionListQuery) => [\n \"transaction-list\",\n q?.page ?? 1,\n q?.limit ?? 10,\n q?.calledFunction ?? null,\n q?.walletAddress,\n q?.day ?? null,\n q?.month ?? null,\n q?.year ?? null,\n ];\n\n const query = useQuery<PaginatedResponse<Transaction>, Error>({\n queryKey: buildQueryKey(input?.query),\n queryFn: async () => {\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransactionList(input.query, bearerToken);\n },\n enabled: Boolean(input?.getBearerToken),\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchTransactionList = async (newInput: FetchTransactionListInput) => {\n return queryClient.fetchQuery({\n queryKey: buildQueryKey(newInput.query),\n queryFn: async () => {\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransactionList(newInput.query, bearerToken);\n },\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchTransactionList,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { Transaction } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype GetTransactionInput = {\n hashOrId?: string;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<Transaction, Error>, \"queryKey\" | \"queryFn\">;\n};\n\ntype FetchTransactionInput = {\n hashOrId: string;\n getBearerToken: () => Promise<string | null | undefined>;\n};\n\nexport function useGetTransaction(input?: GetTransactionInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const buildQueryKey = (hashOrId?: string) => [\"transaction\", hashOrId ?? null];\n\n const query = useQuery<Transaction, Error>({\n queryKey: buildQueryKey(input?.hashOrId),\n queryFn: async () => {\n if (!input?.hashOrId) throw new Error(\"hashOrId is required\");\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransaction(input.hashOrId, bearerToken);\n },\n enabled: Boolean(input?.hashOrId && input?.getBearerToken),\n retry: (failureCount: number, error: Error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchTransaction = async (newInput: FetchTransactionInput) => {\n return queryClient.fetchQuery({\n queryKey: buildQueryKey(newInput.hashOrId),\n queryFn: async () => {\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransaction(newInput.hashOrId, bearerToken);\n },\n retry: (failureCount: number, error: Error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchTransaction,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { TransactionStatusResponse, OnChainTxStatus } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\n/** Terminal statuses that stop polling */\nconst TERMINAL_STATUSES: OnChainTxStatus[] = [\n OnChainTxStatus.ACCEPTED_ON_L1,\n OnChainTxStatus.REJECTED,\n OnChainTxStatus.REVERTED,\n];\n\ntype GetTransactionStatusInput = {\n hash?: string;\n getBearerToken?: () => Promise<string | null | undefined>;\n /** Polling interval in ms. Defaults to 3000. Set to false to disable polling. */\n refetchInterval?: number | false;\n queryOptions?: Omit<\n UseQueryOptions<TransactionStatusResponse, Error>,\n \"queryKey\" | \"queryFn\" | \"refetchInterval\"\n >;\n};\n\ntype FetchTransactionStatusInput = {\n hash: string;\n getBearerToken: () => Promise<string | null | undefined>;\n};\n\nexport function useGetTransactionStatus(input?: GetTransactionStatusInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const buildQueryKey = (hash?: string) => [\"transaction-status\", hash ?? null];\n\n const query = useQuery<TransactionStatusResponse, Error>({\n queryKey: buildQueryKey(input?.hash),\n queryFn: async () => {\n if (!input?.hash) throw new Error(\"hash is required\");\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransactionStatus(input.hash, bearerToken);\n },\n enabled: Boolean(input?.hash && input?.getBearerToken),\n refetchInterval: (query) => {\n // Stop polling on terminal statuses\n const status = query.state.data?.status;\n if (status && TERMINAL_STATUSES.includes(status)) {\n return false;\n }\n return input?.refetchInterval ?? 3000;\n },\n retry: (failureCount: number, error: Error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchTransactionStatus = async (newInput: FetchTransactionStatusInput) => {\n return queryClient.fetchQuery({\n queryKey: buildQueryKey(newInput.hash),\n queryFn: async () => {\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransactionStatus(newInput.hash, bearerToken);\n },\n retry: (failureCount: number, error: Error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchTransactionStatus,\n };\n}\n","\"use client\";\n\nimport { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { SyncOnChainTransfersParams, SyncOnChainTransfersResponse } from \"@chipi-stack/types\";\n\ntype SyncOnChainInput = SyncOnChainTransfersParams & {\n bearerToken: string;\n};\n\n/**\n * Hook for syncing on-chain transfers from Voyager into the DB.\n *\n * Discovers transactions not made through the SDK (e.g., external USDC receives\n * from Argent X or other wallets). After sync, useGetTransactionList returns\n * the newly discovered transactions automatically.\n *\n * @example\n * ```tsx\n * const { syncTransfers, data, isLoading } = useSyncOnChainTransfers();\n *\n * // Sync on-chain transfers for a wallet\n * const result = await syncTransfersAsync({\n * walletAddress: wallet.publicKey,\n * bearerToken: await getToken(),\n * });\n * console.log(`Synced ${result.synced} new transfers`);\n * ```\n */\nexport function useSyncOnChainTransfers(): {\n syncTransfers: (input: SyncOnChainInput) => void;\n syncTransfersAsync: (input: SyncOnChainInput) => Promise<SyncOnChainTransfersResponse>;\n data: SyncOnChainTransfersResponse | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const mutation: UseMutationResult<SyncOnChainTransfersResponse, Error, SyncOnChainInput> =\n useMutation({\n mutationFn: async (input: SyncOnChainInput) => {\n const { bearerToken, ...params } = input;\n return chipiSDK.transactions.syncOnChainTransfers(params, bearerToken);\n },\n onSuccess: () => {\n // Invalidate transaction list cache so new txs appear immediately\n queryClient.invalidateQueries({\n predicate: (query) => query.queryKey[0] === \"transaction-list\",\n });\n },\n });\n\n return {\n syncTransfers: mutation.mutate,\n syncTransfersAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport { CreateSkuPurchaseParams, Transaction } from \"@chipi-stack/types\";\n\ntype PurchaseSkuInput = {\n params: CreateSkuPurchaseParams;\n bearerToken: string;\n};\n\n/**\n * Hook for purchasing SKUs\n */\nexport function usePurchaseSku(): {\n purchaseSku: (input: PurchaseSkuInput) => void;\n purchaseSkuAsync: (input: PurchaseSkuInput) => Promise<Transaction>;\n data: Transaction | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<Transaction, Error, PurchaseSkuInput> = useMutation({\n mutationFn: (input: PurchaseSkuInput) =>\n chipiSDK.purchaseSku({\n params: input.params,\n bearerToken: input.bearerToken,\n }),\n });\n\n return {\n purchaseSku: mutation.mutate,\n purchaseSkuAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { Transaction } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\n\ntype GetSkuPurchaseInput = {\n id: string;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<Transaction, Error>, \"queryKey\" | \"queryFn\">;\n};\n\nexport function useGetSkuPurchase(input?: GetSkuPurchaseInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const query = useQuery<Transaction, Error>({\n queryKey: [\"sku-purchase\", input?.id],\n queryFn: async () => {\n if (!input?.id) throw new Error(\"id is required\");\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSkuPurchase(input.id, bearerToken);\n },\n enabled: Boolean(input?.id && input?.getBearerToken),\n ...input?.queryOptions,\n });\n\n const fetchSkuPurchase = async (newInput: GetSkuPurchaseInput) => {\n return queryClient.fetchQuery({\n queryKey: [\"sku-purchase\", newInput?.id],\n queryFn: async () => {\n if (!newInput?.id) throw new Error(\"id is required\");\n if (!newInput?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSkuPurchase(newInput.id, bearerToken);\n },\n });\n };\n\n return {\n ...query,\n fetchSkuPurchase,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { PaginatedResponse, Sku, GetSkuListQuery } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype SkuListInput = {\n query: GetSkuListQuery;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<PaginatedResponse<Sku>, Error>, \"queryKey\" | \"queryFn\">;\n};\n\nexport function useGetSkuList(input?: SkuListInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const buildQueryKey = (q?: GetSkuListQuery) => [\n \"available-skus\",\n q?.page ?? 1,\n q?.limit ?? 10,\n q?.offset ?? 0,\n q?.provider ?? null,\n q?.category ?? null,\n ];\n\n const query = useQuery<PaginatedResponse<Sku>, Error>({\n queryKey: buildQueryKey(input?.query),\n queryFn: async () => {\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSkuList(input.query, bearerToken);\n },\n enabled: Boolean(input?.getBearerToken),\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchSkuList = async (newInput: SkuListInput) => {\n return queryClient.fetchQuery({\n queryKey: buildQueryKey(newInput?.query),\n queryFn: async () => {\n if (!newInput?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSkuList(newInput.query, bearerToken);\n },\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchSkuList,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { Sku } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype GetSkuInput = {\n id: string;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<Sku, Error>, \"queryKey\" | \"queryFn\">;\n};\n\nexport function useGetSku(input?: GetSkuInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const query = useQuery<Sku, Error>({\n queryKey: [\"sku\", input?.id],\n queryFn: async () => {\n if (!input?.id || !input?.getBearerToken)\n throw new Error(\"id and getBearerToken are required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSku(input.id, bearerToken);\n },\n enabled: Boolean(input?.id && input?.getBearerToken && input.id.trim() !== \"\"),\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchSku = async (input: GetSkuInput): Promise<Sku> => {\n return queryClient.fetchQuery({\n queryKey: [\"sku\", input?.id],\n queryFn: async () => {\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSku(input.id, bearerToken);\n },\n retry: (failureCount, error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchSku,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { CallAnyContractParams } from \"@chipi-stack/types\";\n\ntype CallAnyContractInput = {\n params: CallAnyContractParams;\n bearerToken: string;\n};\n\n/**\n * Hook for calling any contract method\n */\nexport function useCallAnyContract(): {\n callAnyContract: (params: CallAnyContractInput) => void;\n callAnyContractAsync: (params: CallAnyContractInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK, passkeyAdapter } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, CallAnyContractInput> = useMutation({\n mutationFn: async (params: CallAnyContractInput) => {\n let encryptKey = params.params.encryptKey;\n\n // If usePasskey is true, authenticate with passkey to get encryptKey\n if (params.params.usePasskey) {\n if (!params.params.externalUserId) {\n throw new Error(\"externalUserId is required when usePasskey is true\");\n }\n try {\n const key = await passkeyAdapter.getWalletEncryptKey({\n externalUserId: params.params.externalUserId,\n });\n if (!key) {\n throw new Error(\"Passkey authentication was cancelled\");\n }\n encryptKey = key;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotAllowedError\") {\n throw new Error(\"Passkey authentication was cancelled by the user\");\n }\n if (error instanceof Error) {\n throw error;\n }\n throw new Error(\"Failed to authenticate with passkey\");\n }\n }\n\n if (!encryptKey) {\n throw new Error(\"encryptKey is required when usePasskey is false\");\n }\n\n const {\n usePasskey: _usePasskey,\n externalUserId: _externalUserId,\n ...contractParams\n } = params.params;\n return chipiSDK.callAnyContract({\n params: {\n ...contractParams,\n encryptKey: encryptKey,\n },\n bearerToken: params.bearerToken,\n });\n },\n });\n\n return {\n callAnyContract: mutation.mutate,\n callAnyContractAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { RecordSendTransactionParams, Transaction } from \"@chipi-stack/types\";\n\ntype RecordSendTransactionInput = {\n params: RecordSendTransactionParams;\n bearerToken: string;\n};\n\nexport function useRecordSendTransaction(): {\n recordSendTransaction: (input: RecordSendTransactionInput) => void;\n recordSendTransactionAsync: (input: RecordSendTransactionInput) => Promise<Transaction>;\n data: Transaction | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<Transaction, Error, RecordSendTransactionInput> = useMutation({\n mutationFn: (input: RecordSendTransactionInput) =>\n chipiSDK.recordSendTransaction({\n params: input.params,\n bearerToken: input.bearerToken,\n }),\n });\n\n return {\n recordSendTransaction: mutation.mutate,\n recordSendTransactionAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { GetTokenBalanceParams, GetTokenBalanceResponse } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype GetTokenBalanceInput = {\n params?: GetTokenBalanceParams;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<GetTokenBalanceResponse, Error>, \"queryKey\" | \"queryFn\">;\n};\n\nexport function useGetTokenBalance(input?: GetTokenBalanceInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const buildQueryKey = (params?: GetTokenBalanceParams) => [\n \"chain-token-balance\",\n params?.chainToken ?? null,\n params?.chain ?? null,\n params?.walletPublicKey ?? null,\n params?.externalUserId ?? null,\n ];\n\n const query = useQuery<GetTokenBalanceResponse, Error>({\n queryKey: buildQueryKey(input?.params),\n queryFn: async () => {\n if (!input || !input.params || !input.getBearerToken) throw new Error(\"Input is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTokenBalance(input.params, bearerToken);\n },\n enabled: Boolean(input?.params && input?.getBearerToken),\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchTokenBalance = async (newInput: GetTokenBalanceInput) => {\n return queryClient.fetchQuery({\n queryKey: buildQueryKey(newInput?.params),\n queryFn: async () => {\n if (!newInput || !newInput.getBearerToken || !newInput.params)\n throw new Error(\"Input is required\");\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTokenBalance(newInput.params, bearerToken);\n },\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchTokenBalance,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { CreateSessionKeyParams, SessionKeyData } from \"@chipi-stack/types\";\n\n/**\n * Hook for creating a session keypair locally.\n *\n * This generates session keys but does NOT register them on-chain.\n * The returned SessionKeyData should be stored by the developer externally\n * (e.g., in Clerk metadata, database, etc.) - the SDK does NOT persist this.\n *\n * After generating, call `useAddSessionKeyToContract` to register the session on-chain.\n *\n * @example\n * ```typescript\n * const { createSessionKey, data: session } = useCreateSessionKey();\n *\n * // Generate session keypair\n * createSessionKey({\n * encryptKey: userEncryptKey,\n * durationSeconds: 21600 // 6 hours (optional, default)\n * });\n *\n * // Store session externally after creation\n * if (session) {\n * await saveToClerk(session);\n * }\n * ```\n */\nexport function useCreateSessionKey(): {\n createSessionKey: (params: CreateSessionKeyParams) => void;\n createSessionKeyAsync: (params: CreateSessionKeyParams) => Promise<SessionKeyData>;\n data: SessionKeyData | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<SessionKeyData, Error, CreateSessionKeyParams> = useMutation({\n mutationFn: async (params: CreateSessionKeyParams) =>\n chipiSDK.sessions.createSessionKey(params),\n });\n\n return {\n createSessionKey: mutation.mutate,\n createSessionKeyAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { AddSessionKeyParams } from \"@chipi-stack/types\";\n\ntype AddSessionKeyInput = {\n params: AddSessionKeyParams;\n bearerToken: string;\n};\n\n/**\n * Hook for registering a session key on the smart contract.\n *\n * This executes a sponsored transaction (using owner signature) to call\n * `add_or_update_session_key` on the CHIPI wallet contract.\n *\n * The session must be registered before it can be used for transactions.\n * Only works with CHIPI wallets.\n *\n * @example\n * ```typescript\n * const { addSessionKeyToContract, isLoading } = useAddSessionKeyToContract();\n *\n * // Register session on-chain\n * addSessionKeyToContract({\n * params: {\n * encryptKey: userEncryptKey,\n * wallet: userWallet,\n * sessionConfig: {\n * sessionPublicKey: session.publicKey,\n * validUntil: session.validUntil,\n * maxCalls: 1000,\n * allowedEntrypoints: [] // empty = all allowed\n * }\n * },\n * bearerToken\n * });\n * ```\n */\nexport function useAddSessionKeyToContract(): {\n addSessionKeyToContract: (input: AddSessionKeyInput) => void;\n addSessionKeyToContractAsync: (input: AddSessionKeyInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, AddSessionKeyInput> = useMutation({\n mutationFn: (input: AddSessionKeyInput) =>\n chipiSDK.sessions.addSessionKeyToContract(input.params, input.bearerToken),\n });\n\n return {\n addSessionKeyToContract: mutation.mutate,\n addSessionKeyToContractAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { RevokeSessionKeyParams } from \"@chipi-stack/types\";\n\ntype RevokeSessionKeyInput = {\n params: RevokeSessionKeyParams;\n bearerToken: string;\n};\n\n/**\n * Hook for revoking a session key from the smart contract.\n *\n * This executes a sponsored transaction (using owner signature) to call\n * `revoke_session_key` on the CHIPI wallet contract.\n *\n * After revocation, the session key can no longer be used for transactions.\n * Only works with CHIPI wallets.\n *\n * @example\n * ```typescript\n * const { revokeSessionKey, isLoading } = useRevokeSessionKey();\n *\n * // Revoke a session\n * revokeSessionKey({\n * params: {\n * encryptKey: userEncryptKey,\n * wallet: userWallet,\n * sessionPublicKey: session.publicKey\n * },\n * bearerToken\n * });\n * ```\n */\nexport function useRevokeSessionKey(): {\n revokeSessionKey: (input: RevokeSessionKeyInput) => void;\n revokeSessionKeyAsync: (input: RevokeSessionKeyInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, RevokeSessionKeyInput> = useMutation({\n mutationFn: (input: RevokeSessionKeyInput) =>\n chipiSDK.sessions.revokeSessionKey(input.params, input.bearerToken),\n });\n\n return {\n revokeSessionKey: mutation.mutate,\n revokeSessionKeyAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { GetSessionDataParams, SessionDataResponse } from \"@chipi-stack/types\";\n\n/**\n * Hook for querying session data from the smart contract.\n *\n * This is a read-only call that does not require signing or gas.\n * Returns the on-chain state of a session key including:\n * - Whether it's active\n * - When it expires\n * - Remaining calls\n * - Allowed entrypoints\n *\n * @example\n * ```typescript\n * const { data: sessionData, isLoading } = useGetSessionData({\n * walletAddress: userWallet.publicKey,\n * sessionPublicKey: session.publicKey\n * });\n *\n * if (sessionData?.isActive) {\n * console.log(`Session has ${sessionData.remainingCalls} calls remaining`);\n * }\n * ```\n */\nexport function useGetSessionData(\n params: GetSessionDataParams | null,\n options?: { enabled?: boolean }\n): {\n data: SessionDataResponse | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n refetch: UseQueryResult<SessionDataResponse, Error>[\"refetch\"];\n} {\n const { chipiSDK } = useChipiContext();\n\n const query: UseQueryResult<SessionDataResponse, Error> = useQuery({\n queryKey: [\"sessionData\", params?.walletAddress, params?.sessionPublicKey],\n queryFn: () => {\n if (!params) {\n throw new Error(\"Session data params are required\");\n }\n return chipiSDK.sessions.getSessionData(params);\n },\n enabled: options?.enabled !== false && params !== null,\n });\n\n return {\n data: query.data,\n isLoading: query.isLoading,\n isError: query.isError,\n error: query.error,\n isSuccess: query.isSuccess,\n refetch: query.refetch,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { ExecuteWithSessionParams } from \"@chipi-stack/types\";\n\ntype ExecuteWithSessionInput = {\n params: ExecuteWithSessionParams;\n bearerToken: string;\n};\n\n/**\n * Hook for executing a gasless transaction using a session key.\n *\n * This uses the 4-element session signature format instead of owner signature.\n * The session must be:\n * 1. Generated via `useCreateSessionKey`\n * 2. Registered on-chain via `useAddSessionKeyToContract`\n *\n * Only works with CHIPI wallets.\n *\n * @example\n * ```typescript\n * const { executeWithSession, isLoading } = useExecuteWithSession();\n *\n * // Execute a transfer using session key (no owner key needed)\n * executeWithSession({\n * params: {\n * encryptKey: userEncryptKey,\n * wallet: userWallet,\n * session: sessionKeyData,\n * calls: [{\n * contractAddress: USDC_ADDRESS,\n * entrypoint: 'transfer',\n * calldata: [recipient, amount, '0x0']\n * }]\n * },\n * bearerToken\n * });\n * ```\n */\nexport function useExecuteWithSession(): {\n executeWithSession: (input: ExecuteWithSessionInput) => void;\n executeWithSessionAsync: (input: ExecuteWithSessionInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, ExecuteWithSessionInput> = useMutation({\n mutationFn: (input: ExecuteWithSessionInput) =>\n chipiSDK.executeTransactionWithSession({\n params: input.params,\n bearerToken: input.bearerToken,\n }),\n });\n\n return {\n executeWithSession: mutation.mutate,\n executeWithSessionAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","\"use client\";\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type {\n WalletData,\n WalletType,\n PaymentRequirement,\n PaymentPayload,\n SessionKeyData,\n} from \"@chipi-stack/types\";\nimport { buildX402TypedData } from \"@chipi-stack/core\";\n\n/**\n * Configuration for useX402Payment hook\n */\nexport interface UseX402PaymentConfig {\n /** Wallet data */\n wallet: WalletData | null | undefined;\n /** Encryption key for signing */\n encryptKey: string;\n /** Function to get the bearer token for API calls */\n getBearerToken?: () => Promise<string | null | undefined>;\n /** Static bearer token string (alternative to getBearerToken) */\n bearerToken?: string;\n /** Max amount per payment (USDC, human-readable e.g. \"1.00\") */\n maxPaymentAmount?: string;\n /** Alias for maxPaymentAmount */\n maxAmount?: string;\n /** Allowed recipient addresses (whitelist). Empty = allow all. */\n allowedRecipients?: string[];\n /** Active session for automatic payments (optional) */\n session?: SessionKeyData | null;\n /** Callback on successful payment */\n onPaymentComplete?: (txHash: string, amount: string) => void | Promise<void>;\n}\n\n/**\n * Last payment info returned by the hook\n */\nexport interface LastPaymentInfo {\n txHash: string | null;\n amount: string | null;\n timestamp: number;\n}\n\n/**\n * Return type for useX402Payment hook\n */\nexport interface UseX402PaymentReturn {\n /** Fetch wrapper that auto-handles 402 payments */\n x402Fetch: (url: string, init?: Record<string, any>) => Promise<Response>;\n /** Alias for x402Fetch */\n payFetch: (url: string, init?: Record<string, any>) => Promise<Response>;\n /** Manual payment signing (for custom flows) */\n signPayment: (requirement: PaymentRequirement) => Promise<PaymentPayload>;\n /** Whether a payment is in progress */\n isPaying: boolean;\n /** Last payment transaction hash */\n lastTxHash: string | null;\n /** Last payment amount (human-readable USDC) */\n lastAmount: string | null;\n /** Last payment info (txHash + amount + timestamp) */\n lastPayment: LastPaymentInfo | null;\n /** Total USDC spent in this session (human-readable) */\n totalSpent: string;\n /** Error from last payment attempt */\n error: Error | null;\n /** Total payments made in this session */\n paymentCount: number;\n}\n\n/**\n * React hook for x402 payment protocol support.\n *\n * Wraps fetch calls with automatic HTTP 402 payment handling.\n * When a server returns 402, the hook:\n * 1. Parses the payment requirement\n * 2. Validates against configured limits\n * 3. Signs using the wallet (or session key for automatic payments)\n * 4. Retries with the X-PAYMENT header\n *\n * @example\n * ```tsx\n * const { x402Fetch, isPaying, lastTxHash, paymentCount } = useX402Payment({\n * wallet,\n * encryptKey: pin,\n * getBearerToken: getToken,\n * maxPaymentAmount: \"1.00\",\n * onPaymentComplete: (txHash, amount) => {\n * console.log(`Paid ${amount} USDC, tx: ${txHash}`);\n * },\n * });\n *\n * // Automatic 402 handling\n * const response = await x402Fetch(\"https://api.example.com/premium\");\n * const data = await response.json();\n * ```\n */\nexport function useX402Payment(config: UseX402PaymentConfig): UseX402PaymentReturn {\n const { chipiSDK } = useChipiContext();\n\n const {\n wallet,\n encryptKey,\n getBearerToken: getBearerTokenFn,\n bearerToken: staticBearerToken,\n maxPaymentAmount: maxPaymentAmountProp,\n maxAmount,\n allowedRecipients,\n session,\n onPaymentComplete,\n } = config;\n\n // Resolve maxPaymentAmount: explicit prop takes precedence over alias\n const maxPaymentAmount = maxPaymentAmountProp ?? maxAmount;\n\n // Resolve getBearerToken: function takes precedence over static string\n const getBearerToken = useMemo(\n () =>\n getBearerTokenFn ??\n (staticBearerToken\n ? () => Promise.resolve(staticBearerToken)\n : () => Promise.resolve(undefined)),\n [getBearerTokenFn, staticBearerToken]\n );\n\n const [lastTxHash, setLastTxHash] = useState<string | null>(null);\n const [lastAmount, setLastAmount] = useState<string | null>(null);\n const [lastPayment, setLastPayment] = useState<LastPaymentInfo | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const paymentCountRef = useRef(0);\n const [paymentCount, setPaymentCount] = useState(0);\n const totalSpentRef = useRef(0n);\n const [totalSpent, setTotalSpent] = useState(\"0.000000\");\n\n /**\n * Parse PAYMENT-REQUIRED header from a 402 response\n */\n const parsePaymentRequired = useCallback((response: Response): PaymentRequirement => {\n const headerValue = response.headers.get(\"payment-required\");\n\n if (!headerValue) {\n throw new Error(\n \"Server returned 402 but no PAYMENT-REQUIRED header. \" +\n \"The server may not support x402 or is misconfigured.\"\n );\n }\n\n try {\n return JSON.parse(headerValue);\n } catch {\n throw new Error(\"Malformed PAYMENT-REQUIRED header: invalid JSON\");\n }\n }, []);\n\n /**\n * Validate payment requirement against config limits and protocol constraints\n */\n const validateRequirement = useCallback(\n (requirement: PaymentRequirement): void => {\n // Validate protocol constraints\n if (requirement.scheme !== \"exact\") {\n throw new Error(\n `Unsupported payment scheme: \"${requirement.scheme}\". Only \"exact\" is supported.`\n );\n }\n if (requirement.network !== \"starknet-mainnet\") {\n throw new Error(\n `Unsupported network: \"${requirement.network}\". Only \"starknet-mainnet\" is supported.`\n );\n }\n\n // Validate asset is USDC\n const USDC_MAINNET = \"0x033068F6539f8e6e6b131e6B2B814e6c34A5224bC66947c47DaB9dFeE93b35fb\";\n const normalizeAddr = (a: string) => a.toLowerCase().replace(/^0x0+/, \"0x\");\n if (normalizeAddr(requirement.asset) !== normalizeAddr(USDC_MAINNET)) {\n throw new Error(`Unsupported asset: ${requirement.asset}. Only USDC is supported.`);\n }\n\n // Validate required fields\n if (!requirement.payTo) {\n throw new Error(\"Invalid payment requirement: missing payTo address\");\n }\n\n // Validate maxTimeoutSeconds\n const timeoutSeconds = Number(requirement.maxTimeoutSeconds);\n if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {\n throw new Error(\"Invalid payment requirement: maxTimeoutSeconds must be a positive number\");\n }\n\n // Validate maxAmountRequired\n let requiredAmount: bigint;\n try {\n requiredAmount = BigInt(requirement.maxAmountRequired);\n } catch {\n throw new Error(\"Invalid payment requirement: maxAmountRequired must be an integer string\");\n }\n if (requiredAmount <= 0n) {\n throw new Error(\"Invalid payment requirement: maxAmountRequired must be > 0\");\n }\n\n if (maxPaymentAmount) {\n const trimmed = maxPaymentAmount.trim();\n if (!/^\\d+(\\.\\d{1,6})?$/.test(trimmed)) {\n throw new Error(`Invalid maxPaymentAmount format: \"${maxPaymentAmount}\"`);\n }\n // String-based conversion to avoid floating-point precision issues\n const [whole, frac = \"\"] = trimmed.split(\".\");\n const fracPadded = (frac + \"000000\").slice(0, 6);\n const maxBaseUnits = BigInt((whole || \"0\") + fracPadded);\n\n if (requiredAmount > maxBaseUnits) {\n const requiredHuman = (Number(requiredAmount) / 1_000_000).toFixed(6);\n throw new Error(\n `Payment amount ${requiredHuman} USDC exceeds maximum allowed ${maxPaymentAmount} USDC`\n );\n }\n }\n\n if (allowedRecipients && allowedRecipients.length > 0) {\n const normalize = (a: string) => a.toLowerCase().replace(/^0x0+/, \"0x\");\n const normalized = normalize(requirement.payTo);\n const isAllowed = allowedRecipients.some((addr) => normalize(addr) === normalized);\n if (!isAllowed) {\n throw new Error(`Recipient ${requirement.payTo} is not in the allowed recipients list`);\n }\n }\n },\n [maxPaymentAmount, allowedRecipients]\n );\n\n /**\n * Sign a SNIP-12 typed data payment message.\n * Uses session key if available, otherwise signs locally via signTypedData().\n */\n const signPayment = useCallback(\n async (requirement: PaymentRequirement): Promise<PaymentPayload> => {\n if (!wallet) {\n throw new Error(\"Wallet is required for x402 payments\");\n }\n if (!encryptKey) {\n throw new Error(\"Encryption key (PIN) is required for x402 payments\");\n }\n\n validateRequirement(requirement);\n\n const nonce = crypto.randomUUID();\n const validUntil = Math.floor(Date.now() / 1000) + requirement.maxTimeoutSeconds;\n\n // Session key path: session keys use a 4-element signature format\n // [sessionPubKey, r, s, validUntil] that requires the full paymaster\n // execution flow (prepare-typed-data → sign → execute-sponsored-transaction).\n // We keep the executeTransactionWithSession flow here because the facilitator's\n // settle() is a no-op for session-executed payments (already on-chain).\n if (session) {\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.executeTransactionWithSession({\n params: {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n session,\n calls: [\n {\n contractAddress: requirement.asset,\n entrypoint: \"transfer\",\n calldata: [requirement.payTo, requirement.maxAmountRequired, \"0x0\"],\n },\n ],\n },\n bearerToken,\n });\n\n return {\n x402Version: 1,\n scheme: \"exact\",\n network: \"starknet-mainnet\",\n payload: {\n signature: { r: txHash, s: \"session\" },\n fromAddress: wallet.publicKey,\n toAddress: requirement.payTo,\n amount: requirement.maxAmountRequired,\n asset: requirement.asset,\n validUntil,\n nonce,\n },\n };\n }\n\n // Standard wallet path: sign SNIP-12 typed data locally without executing a transaction.\n const typedData = buildX402TypedData({\n from_address: wallet.publicKey,\n to_address: requirement.payTo,\n amount: requirement.maxAmountRequired,\n asset: requirement.asset,\n valid_until: String(validUntil),\n nonce,\n });\n\n const signature = await chipiSDK.signTypedData({\n params: {\n encryptKey,\n wallet,\n typedData,\n },\n });\n\n return {\n x402Version: 1,\n scheme: \"exact\",\n network: \"starknet-mainnet\",\n payload: {\n signature,\n fromAddress: wallet.publicKey,\n toAddress: requirement.payTo,\n amount: requirement.maxAmountRequired,\n asset: requirement.asset,\n validUntil,\n nonce,\n },\n };\n },\n [wallet, encryptKey, session, getBearerToken, chipiSDK, validateRequirement]\n );\n\n /**\n * Payment mutation for tracking state\n */\n const paymentMutation = useMutation<Response, Error, { url: string; init?: Record<string, any> }>(\n {\n mutationFn: async ({ url, init }) => {\n const response = await globalThis.fetch(url, init);\n\n if (response.status !== 402) {\n return response;\n }\n\n const requirement = parsePaymentRequired(response);\n const payment = await signPayment(requirement);\n\n // Track payment\n const humanAmount = (Number(BigInt(requirement.maxAmountRequired)) / 1_000_000).toFixed(6);\n // Session payments store txHash in signature.r with s=\"session\" marker.\n // Standard wallet payments have ECDSA signature components, not a txHash.\n const isSessionPayment = payment.payload.signature.s === \"session\";\n const txHash = isSessionPayment ? payment.payload.signature.r : null;\n\n setLastAmount(humanAmount);\n setLastTxHash(txHash);\n\n setLastPayment({ txHash, amount: humanAmount, timestamp: Date.now() });\n\n totalSpentRef.current += BigInt(requirement.maxAmountRequired);\n setTotalSpent((Number(totalSpentRef.current) / 1_000_000).toFixed(6));\n\n paymentCountRef.current += 1;\n setPaymentCount(paymentCountRef.current);\n\n // Retry with payment header\n const headers = new Headers(init?.headers);\n headers.set(\"X-PAYMENT\", JSON.stringify(payment));\n\n const paidResponse = await globalThis.fetch(url, { ...init, headers });\n if (paidResponse.status === 402) {\n throw new Error(\n \"Server returned 402 after payment was submitted. Payment may have failed verification.\"\n );\n }\n\n // Completion callback (fire-and-forget, don't block response)\n if (onPaymentComplete) {\n void Promise.resolve(onPaymentComplete(txHash ?? \"\", humanAmount)).catch(() => {});\n }\n\n return paidResponse;\n },\n onError: (err) => {\n setError(err);\n },\n onSuccess: () => {\n setError(null);\n },\n }\n );\n\n const x402Fetch = useCallback(\n async (url: string, init?: Record<string, any>): Promise<Response> => {\n return paymentMutation.mutateAsync({ url, init });\n },\n [paymentMutation]\n );\n\n return {\n x402Fetch,\n payFetch: x402Fetch,\n signPayment,\n isPaying: paymentMutation.isPending,\n lastTxHash,\n lastAmount,\n lastPayment,\n totalSpent,\n error: error || paymentMutation.error || null,\n paymentCount,\n };\n}\n"]}
1
+ {"version":3,"sources":["../src/context/ChipiProvider.tsx","../src/hooks/useCreateWallet.ts","../src/hooks/useGetWallet.ts","../src/hooks/useChipiWallet.ts","../src/hooks/useChipiSession.ts","../src/hooks/useMigrateWalletToPasskey.ts","../src/hooks/useUpdateWalletEncryption.ts","../src/hooks/useMigrateWalletToShhh.ts","../src/hooks/useTransfer.ts","../src/hooks/useApprove.ts","../src/hooks/useGetTransactionList.ts","../src/hooks/useGetTransaction.ts","../src/hooks/useGetTransactionStatus.ts","../src/hooks/useSyncOnChainTransfers.ts","../src/hooks/usePurchaseSku.ts","../src/hooks/useGetSkuPurchase.ts","../src/hooks/useGetSkuList.ts","../src/hooks/useGetSku.ts","../src/hooks/useCallAnyContract.ts","../src/hooks/useRecordSendTransaction.ts","../src/hooks/useGetTokenBalance.ts","../src/hooks/useCreateSessionKey.ts","../src/hooks/useAddSessionKeyToContract.ts","../src/hooks/useRevokeSessionKey.ts","../src/hooks/useGetSessionData.ts","../src/hooks/useExecuteWithSession.ts","../src/hooks/useX402Payment.ts","../src/hooks/useShhhSigner.ts","../src/hooks/useGuardianRecovery.ts","../src/hooks/useThresholdSign.ts","../src/routes/Recover.tsx"],"names":["getWebWalletEncryptKey","useQueryClient","useQuery","ChipiApiError","useMutation","useMemo","useCallback","createWalletPasskey","query","input","useState","useRef","useEffect","jsx"],"mappings":";;;;;;;;;;;AAgBA,IAAM,YAAA,GAAe,cAAwC,IAAI,CAAA;AAQjE,IAAM,qBAAA,GAAwC;AAAA;AAAA,EAE5C,qBAAqB,YAAY;AAC/B,IAAA,IAAI;AACF,MAAA,OAAO,MAAMA,mBAAA,EAAuB;AAAA,IACtC,SAAS,KAAA,EAAO;AAGd,MAAA,OAAA,CAAQ,IAAA;AAAA,QACN,2DAAA;AAAA,QACA,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU;AAAA,OAC3C;AACA,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AACF,CAAA;AAGA,IAAM,wBAAA,GAA2B,MAC/B,IAAI,WAAA,CAAY;AAAA,EACd,cAAA,EAAgB;AAAA,IACd,OAAA,EAAS;AAAA,MACP,WAAW,EAAA,GAAK,GAAA;AAAA;AAAA,MAChB,MAAA,EAAQ,KAAK,EAAA,GAAK,GAAA;AAAA;AAAA,MAClB,KAAA,EAAO,CAAC,YAAA,EAAc,KAAA,KAAe;AAEnC,QAAA,IAAI,KAAA,EAAO,MAAA,IAAU,GAAA,IAAO,KAAA,EAAO,SAAS,GAAA,EAAK;AAC/C,UAAA,OAAO,KAAA;AAAA,QACT;AACA,QAAA,OAAO,YAAA,GAAe,CAAA;AAAA,MACxB;AAA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,OAAA,EACT;AAAA;AAAA;AAAA,GAEJ;AAEJ","file":"index.mjs","sourcesContent":["import React, { createContext, useContext, ReactNode } from \"react\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport { ChipiSDK } from \"@chipi-stack/backend\";\nimport type { ChipiSDKConfig } from \"@chipi-stack/types\";\nimport { getWalletEncryptKey as getWebWalletEncryptKey } from \"@chipi-stack/chipi-passkey\";\n\nexport interface PasskeyAdapter {\n getWalletEncryptKey: (input: { externalUserId: string }) => Promise<string | null>;\n}\n\ninterface ChipiContextValue {\n chipiSDK: ChipiSDK;\n config: ChipiSDKConfig;\n passkeyAdapter: PasskeyAdapter;\n}\n\nconst ChipiContext = createContext<ChipiContextValue | null>(null);\n\ninterface ChipiProviderProps {\n children: ReactNode;\n config: ChipiSDKConfig;\n passkeyAdapter?: PasskeyAdapter;\n}\n\nconst defaultPasskeyAdapter: PasskeyAdapter = {\n // Web default: attempts passkey auth, returns null on failure (caller uses PIN backup)\n getWalletEncryptKey: async () => {\n try {\n return await getWebWalletEncryptKey();\n } catch (error) {\n // Passkey failed (PRF unavailable, user cancelled, localStorage cleared)\n // Log for debugging — return null so caller can fall back to PIN backup\n console.warn(\n \"[ChipiProvider] Passkey auth failed, falling back to PIN:\",\n error instanceof Error ? error.message : error\n );\n return null;\n }\n },\n};\n\n// Default QueryClient configuration\nconst createDefaultQueryClient = () =>\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 60 * 1000, // 1 minute\n gcTime: 10 * 60 * 1000, // 10 minutes (formerly cacheTime)\n retry: (failureCount, error: any) => {\n // Don't retry on 4xx errors\n if (error?.status >= 400 && error?.status < 500) {\n return false;\n }\n return failureCount < 3;\n },\n },\n mutations: {\n retry: false,\n },\n },\n });\n\n/**\n * Provider component that wraps your app and provides Chipi SDK context with QueryClient\n */\nexport function ChipiProvider({ children, config, passkeyAdapter }: ChipiProviderProps) {\n // Create QueryClient\n const queryClient = React.useMemo(() => createDefaultQueryClient(), []);\n\n const chipiSDK = React.useMemo(() => new ChipiSDK(config), [config]);\n const resolvedPasskeyAdapter = passkeyAdapter ?? defaultPasskeyAdapter;\n\n const value = React.useMemo(\n () => ({\n chipiSDK,\n config,\n passkeyAdapter: resolvedPasskeyAdapter,\n }),\n [chipiSDK, config, resolvedPasskeyAdapter]\n );\n\n return (\n <QueryClientProvider client={queryClient}>\n <ChipiContext.Provider value={value}>{children}</ChipiContext.Provider>\n </QueryClientProvider>\n );\n}\n\n/**\n * Hook to access Chipi SDK context\n */\nexport function useChipiContext(): ChipiContextValue {\n const context = useContext(ChipiContext);\n\n if (!context) {\n throw new Error(\"useChipiContext must be used within a ChipiProvider\");\n }\n\n return context;\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { CreateWalletParams, CreateWalletResponse } from \"@chipi-stack/types\";\nimport { createWalletPasskey } from \"@chipi-stack/chipi-passkey\";\n\ntype CreateWalletInput = {\n params: CreateWalletParams;\n bearerToken: string;\n};\n\n/**\n * Hook for creating a new wallet.\n *\n * Supports dual-key wrapping: when `usePasskey: true` AND `encryptKey` (PIN) provided,\n * the private key is encrypted twice — once with the passkey-derived key (primary) and\n * once with the PIN (backup). If passkey fails later, PIN recovers the wallet.\n *\n * @example\n * ```tsx\n * // Passkey + PIN (recommended)\n * await createWalletAsync({\n * params: {\n * encryptKey: pin, // PIN backup\n * externalUserId: userId,\n * chain: Chain.STARKNET,\n * usePasskey: true, // Creates passkey + dual encryption\n * },\n * bearerToken,\n * });\n *\n * // PIN only (backward compatible)\n * await createWalletAsync({\n * params: {\n * encryptKey: pin,\n * externalUserId: userId,\n * chain: Chain.STARKNET,\n * },\n * bearerToken,\n * });\n * ```\n */\nexport function useCreateWallet(): {\n createWallet: (input: CreateWalletInput) => void;\n createWalletAsync: (input: CreateWalletInput) => Promise<CreateWalletResponse>;\n data: CreateWalletResponse | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<CreateWalletResponse, Error, CreateWalletInput> = useMutation({\n mutationFn: async (input: CreateWalletInput) => {\n let encryptKey = input.params.encryptKey;\n let encryptKeyBackup: string | undefined;\n let credentialId: string | undefined;\n let prfSupported: boolean | undefined;\n let authMethod: string | undefined;\n\n if (input.params.usePasskey) {\n if (!input.params.externalUserId) {\n throw new Error(\"externalUserId is required when using passkey\");\n }\n\n try {\n const passkeyResult = await createWalletPasskey(\n input.params.externalUserId,\n input.params.externalUserId\n );\n\n credentialId = passkeyResult.credentialId;\n prfSupported = passkeyResult.prfSupported;\n\n if (encryptKey) {\n // Dual-key mode: passkey is primary, PIN is backup\n encryptKeyBackup = encryptKey;\n encryptKey = passkeyResult.encryptKey;\n authMethod = \"passkey+pin\";\n } else {\n // Passkey-only mode (no PIN backup — not recommended)\n encryptKey = passkeyResult.encryptKey;\n authMethod = \"passkey\";\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Passkey creation failed: ${error.message}`);\n }\n throw new Error(\"Failed to create passkey for wallet\");\n }\n } else {\n // PIN-only mode\n authMethod = encryptKey ? \"pin\" : undefined;\n }\n\n if (!encryptKey) {\n throw new Error(\"encryptKey is required when usePasskey is false\");\n }\n\n return chipiSDK.createWallet({\n params: {\n ...input.params,\n encryptKey,\n encryptKeyBackup,\n authMethod: authMethod as any,\n credentialId,\n prfSupported,\n deviceType: \"web\",\n },\n bearerToken: input.bearerToken,\n });\n },\n });\n\n return {\n createWallet: mutation.mutate,\n createWalletAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { GetWalletParams, GetWalletResponse } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype GetWalletInput = {\n params?: GetWalletParams;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<GetWalletResponse | null, Error>, \"queryKey\" | \"queryFn\">;\n};\n\nexport function useGetWallet(input?: GetWalletInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const query = useQuery<GetWalletResponse | null, Error>({\n queryKey: [\"wallet\", input?.params?.externalUserId],\n queryFn: async () => {\n if (!input || !input.params || !input.getBearerToken) throw new Error(\"Input is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getWallet(input.params, bearerToken);\n },\n enabled: Boolean(\n input?.params?.externalUserId &&\n input?.getBearerToken &&\n input.params.externalUserId.trim() !== \"\"\n ),\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchWallet = async (newInput: GetWalletInput): Promise<GetWalletResponse | null> => {\n return queryClient.fetchQuery({\n queryKey: [\"wallet\", newInput?.params?.externalUserId],\n queryFn: async () => {\n if (!newInput || !newInput.getBearerToken || !newInput.params)\n throw new Error(\"Input is required\");\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getWallet(newInput.params, bearerToken);\n },\n retry: (failureCount, error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchWallet,\n };\n}\n","\"use client\";\n\nimport { useCallback, useMemo } from \"react\";\nimport { useQuery, useMutation, useQueryClient } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\nimport {\n type WalletType,\n type GetWalletResponse,\n type CreateWalletResponse,\n type GetTokenBalanceResponse,\n Chain,\n ChainToken,\n} from \"@chipi-stack/types\";\n\n/**\n * Configuration for useChipiWallet hook\n */\nexport interface UseChipiWalletConfig {\n /** External user ID (e.g., from Clerk, Firebase, etc.) */\n externalUserId: string | null | undefined;\n /** Function to get the bearer token for API calls */\n getBearerToken: () => Promise<string | null | undefined>;\n /** Default token for balance display (defaults to USDC) */\n defaultToken?: ChainToken;\n /** Whether to automatically fetch wallet on mount */\n enabled?: boolean;\n}\n\n/**\n * Extended wallet response with additional computed properties\n */\nexport interface ChipiWalletData extends GetWalletResponse {\n /** Whether this wallet supports session keys */\n supportsSessionKeys: boolean;\n /** Formatted short address for display */\n shortAddress: string;\n}\n\n/**\n * Return type for useChipiWallet hook\n */\nexport interface UseChipiWalletReturn {\n // Wallet data\n /** The user's wallet data, null if not found, undefined if loading */\n wallet: ChipiWalletData | null | undefined;\n /** Whether the user has a wallet */\n hasWallet: boolean;\n /** Whether the wallet is currently being fetched */\n isLoadingWallet: boolean;\n /** Error from fetching wallet */\n walletError: Error | null;\n\n // Balance data\n /** The wallet's balance for the default token */\n balance: GetTokenBalanceResponse | undefined;\n /** Formatted balance string (e.g., \"100.50\") */\n formattedBalance: string;\n /** Whether balance is loading */\n isLoadingBalance: boolean;\n\n // Create wallet\n /** Create a new wallet */\n\n createWallet: (params: {\n encryptKey: string;\n walletType?: WalletType;\n }) => Promise<CreateWalletResponse>;\n /** Whether wallet creation is in progress */\n isCreating: boolean;\n /** Data from the last wallet creation */\n createdWallet: CreateWalletResponse | undefined;\n\n // Actions\n /** Refetch the wallet data */\n refetchWallet: () => Promise<void>;\n /** Refetch the balance */\n refetchBalance: () => Promise<void>;\n /** Refetch both wallet and balance */\n refetchAll: () => Promise<void>;\n}\n\n/**\n * All-in-one wallet hook for Chipi SDK.\n *\n * Combines wallet fetching, creation, and balance checking into a single hook\n * for simplified wallet management.\n *\n * @example\n * ```tsx\n * import { useAuth } from \"@clerk/nextjs\";\n * import { useChipiWallet } from \"@chipi-stack/nextjs\";\n *\n * function WalletComponent() {\n * const { userId, getToken } = useAuth();\n * const {\n * wallet,\n * hasWallet,\n * balance,\n * formattedBalance,\n * createWallet,\n * isCreating,\n * isLoadingWallet,\n * } = useChipiWallet({\n * externalUserId: userId,\n * getBearerToken: getToken,\n * });\n *\n * if (isLoadingWallet) return <div>Loading...</div>;\n *\n * if (!hasWallet) {\n * return (\n * <button\n * onClick={() => createWallet({ encryptKey: \"1234\" })}\n * disabled={isCreating}\n * >\n * {isCreating ? \"Creating...\" : \"Create Wallet\"}\n * </button>\n * );\n * }\n *\n * return (\n * <div>\n * <p>Address: {wallet?.shortAddress}</p>\n * <p>Balance: ${formattedBalance} USDC</p>\n * <p>Session Keys: {wallet?.supportsSessionKeys ? \"Yes\" : \"No\"}</p>\n * </div>\n * );\n * }\n * ```\n */\nexport function useChipiWallet(config: UseChipiWalletConfig): UseChipiWalletReturn {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const { externalUserId, getBearerToken, defaultToken = \"USDC\", enabled = true } = config;\n\n const trimmedUserId = externalUserId?.trim() || null;\n\n const isEnabled = Boolean(enabled && trimmedUserId);\n\n // ============ Wallet Query ============\n const walletQuery = useQuery<GetWalletResponse | null, Error>({\n queryKey: [\"chipi-wallet\", trimmedUserId],\n queryFn: async () => {\n if (!trimmedUserId) return null;\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getWallet({ externalUserId: trimmedUserId }, bearerToken);\n },\n enabled: isEnabled,\n retry: (failureCount, error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n });\n\n // ============ Balance Query ============\n const walletPublicKey = walletQuery.data?.publicKey;\n\n const balanceQuery = useQuery<GetTokenBalanceResponse, Error>({\n queryKey: [\"chipi-wallet-balance\", walletPublicKey, defaultToken],\n queryFn: async () => {\n if (!walletPublicKey) throw new Error(\"No wallet\");\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTokenBalance(\n {\n chain: Chain.STARKNET,\n chainToken: defaultToken as ChainToken,\n walletPublicKey,\n },\n bearerToken\n );\n },\n enabled: Boolean(isEnabled && walletPublicKey),\n retry: (failureCount, error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n });\n\n // ============ Create Wallet Mutation ============\n const createWalletMutation = useMutation<\n CreateWalletResponse,\n Error,\n { encryptKey: string; walletType?: WalletType }\n >({\n mutationFn: async ({ encryptKey, walletType = \"CHIPI\" }) => {\n if (!trimmedUserId) throw new Error(\"External user ID is required\");\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n return chipiSDK.createWallet({\n params: {\n chain: Chain.STARKNET,\n encryptKey,\n externalUserId: trimmedUserId,\n walletType,\n },\n bearerToken,\n });\n },\n onSuccess: () => {\n // Invalidate wallet query to refetch\n queryClient.invalidateQueries({\n queryKey: [\"chipi-wallet\", trimmedUserId],\n });\n },\n });\n\n // ============ Computed Values ============\n const wallet = useMemo<ChipiWalletData | null | undefined>(() => {\n if (walletQuery.isLoading) return undefined;\n if (!walletQuery.data) return null;\n\n const data = walletQuery.data;\n return {\n ...data,\n supportsSessionKeys: data.walletType === \"CHIPI\",\n shortAddress: formatAddress(data.publicKey),\n };\n }, [walletQuery.data, walletQuery.isLoading]);\n\n const formattedBalance = useMemo(() => {\n if (!balanceQuery.data?.balance) return \"0.00\";\n const num = Number(balanceQuery.data.balance);\n return num.toLocaleString(undefined, {\n minimumFractionDigits: 2,\n maximumFractionDigits:\n defaultToken === ChainToken.ETH || defaultToken === ChainToken.STRK ? 6 : 2,\n });\n }, [balanceQuery.data, defaultToken]);\n\n // ============ Actions ============\n const refetchWallet = useCallback(async () => {\n await walletQuery.refetch();\n }, [walletQuery]);\n\n const refetchBalance = useCallback(async () => {\n await balanceQuery.refetch();\n }, [balanceQuery]);\n\n const refetchAll = useCallback(async () => {\n await Promise.all([walletQuery.refetch(), balanceQuery.refetch()]);\n }, [walletQuery, balanceQuery]);\n\n const createWallet = useCallback(\n async (params: { encryptKey: string; walletType?: WalletType }) => {\n return createWalletMutation.mutateAsync(params);\n },\n [createWalletMutation]\n );\n\n return {\n // Wallet data\n wallet,\n hasWallet: wallet !== null && wallet !== undefined,\n isLoadingWallet: walletQuery.isLoading,\n walletError: walletQuery.error,\n\n // Balance data\n balance: balanceQuery.data,\n formattedBalance,\n isLoadingBalance: balanceQuery.isLoading,\n\n // Create wallet\n createWallet,\n isCreating: createWalletMutation.isPending,\n createdWallet: createWalletMutation.data,\n\n // Actions\n refetchWallet,\n refetchBalance,\n refetchAll,\n };\n}\n\n/**\n * Format a wallet address for display\n */\nfunction formatAddress(address: string, chars = 6): string {\n if (!address || address.length < chars * 2) return address;\n return `${address.slice(0, chars + 2)}...${address.slice(-chars)}`;\n}\n","\"use client\";\n\nimport { useCallback, useMemo, useState, useEffect } from \"react\";\nimport { useMutation, useQuery, useQueryClient } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type {\n SessionKeyData,\n SessionConfig,\n SessionDataResponse,\n WalletData,\n WalletType,\n CreateSessionKeyParams,\n Call,\n SpendingPolicyConfig,\n SpendingPolicyData,\n} from \"@chipi-stack/types\";\n\n/**\n * Wallet data with optional wallet type for session operations\n */\nexport interface SessionWallet extends WalletData {\n walletType?: WalletType;\n}\n\n/**\n * Configuration for useChipiSession hook\n */\nexport interface UseChipiSessionConfig {\n /** Wallet data (must be a CHIPI wallet for session support) */\n wallet: SessionWallet | null | undefined;\n /** Encryption key (user's PIN) for signing operations */\n encryptKey: string;\n /** Function to get the bearer token for API calls */\n getBearerToken: () => Promise<string | null | undefined>;\n /** Previously stored session data (from Clerk metadata, database, etc.) */\n storedSession?: SessionKeyData | null;\n /** Callback fired when a new session is created (for persistence) */\n onSessionCreated?: (session: SessionKeyData) => void | Promise<void>;\n /** Session duration in seconds (default: 6 hours) */\n defaultDurationSeconds?: number;\n /** Default max calls for session registration (default: 1000) */\n defaultMaxCalls?: number;\n /** Whether to auto-check session status on mount */\n autoCheckStatus?: boolean;\n}\n\n/**\n * Session lifecycle state\n */\nexport type SessionState =\n | \"none\" // No session exists\n | \"created\" // Session created locally, not registered on-chain\n | \"active\" // Session registered and active on-chain\n | \"expired\" // Session has expired\n | \"revoked\"; // Session has been revoked\n\n/**\n * Return type for useChipiSession hook\n */\nexport interface UseChipiSessionReturn {\n // Session data\n /** Current session key data */\n session: SessionKeyData | null;\n /** On-chain session status (from contract query) */\n sessionStatus: SessionDataResponse | undefined;\n /** Current session lifecycle state */\n sessionState: SessionState;\n /** Whether there is an active, usable session */\n hasActiveSession: boolean;\n /** Whether the session has expired */\n isSessionExpired: boolean;\n /** Remaining calls available for the session */\n remainingCalls: number | undefined;\n /** Whether the wallet supports sessions (CHIPI wallet) */\n supportsSession: boolean;\n\n // Actions\n /** Create a new session keypair locally (does NOT register on-chain) */\n createSession: (config?: Partial<CreateSessionKeyParams>) => Promise<SessionKeyData>;\n /** Register the current session on the blockchain */\n registerSession: (config?: Partial<SessionConfig>) => Promise<string>;\n /** Revoke the current session from the blockchain */\n revokeSession: () => Promise<string>;\n /** Execute calls using the session key (no owner signature needed) */\n executeWithSession: (calls: Call[]) => Promise<string>;\n /** Clear the current session from local state */\n clearSession: () => void;\n /** Refresh the on-chain session status */\n refetchStatus: () => Promise<void>;\n\n // Spending Policy Actions\n /** Set a spending policy for the current session + token pair */\n setSpendingPolicy: (config: Omit<SpendingPolicyConfig, \"sessionPublicKey\">) => Promise<string>;\n /** Query the spending policy for a token (read-only, no gas) */\n getSpendingPolicy: (token: string) => Promise<SpendingPolicyData>;\n /** Remove a spending policy for a token */\n removeSpendingPolicy: (token: string) => Promise<string>;\n\n // Loading states\n isCreating: boolean;\n isRegistering: boolean;\n isRevoking: boolean;\n isExecuting: boolean;\n isLoadingStatus: boolean;\n isSettingSpendingPolicy: boolean;\n isRemovingSpendingPolicy: boolean;\n\n // Errors\n error: Error | null;\n}\n\n/**\n * All-in-one session management hook for Chipi SDK.\n *\n * Combines session creation, registration, execution, and revocation\n * into a single unified API. Session keys enable gasless transactions\n * without requiring the owner's private key for each operation.\n *\n * **Important:** Sessions only work with CHIPI wallets. ARGENT wallets\n * do not support session keys.\n *\n * @example\n * ```tsx\n * import { useAuth } from \"@clerk/nextjs\";\n * import { useChipiWallet, useChipiSession } from \"@chipi-stack/nextjs\";\n *\n * function SessionComponent() {\n * const { userId, getToken } = useAuth();\n * const [pin, setPin] = useState(\"\");\n * const { wallet } = useChipiWallet({ externalUserId: userId, getBearerToken: getToken });\n *\n * const {\n * session,\n * hasActiveSession,\n * sessionState,\n * createSession,\n * registerSession,\n * executeWithSession,\n * isCreating,\n * isRegistering,\n * } = useChipiSession({\n * wallet,\n * encryptKey: pin,\n * getBearerToken: getToken,\n * onSessionCreated: async (newSession) => {\n * // Persist to Clerk metadata or database\n * await saveSessionToClerk(newSession);\n * },\n * });\n *\n * const handleSetupSession = async () => {\n * // Step 1: Create session locally\n * await createSession();\n * // Step 2: Register on-chain\n * await registerSession();\n * };\n *\n * const handleTransfer = async () => {\n * // Execute transfer using session (no PIN needed after setup)\n * await executeWithSession([{\n * contractAddress: USDC_ADDRESS,\n * entrypoint: \"transfer\",\n * calldata: [recipient, amount, \"0x0\"],\n * }]);\n * };\n *\n * return (\n * <div>\n * <p>Session State: {sessionState}</p>\n * {!hasActiveSession ? (\n * <button onClick={handleSetupSession} disabled={isCreating || isRegistering}>\n * Setup Session\n * </button>\n * ) : (\n * <button onClick={handleTransfer}>\n * Transfer (Gasless)\n * </button>\n * )}\n * </div>\n * );\n * }\n * ```\n */\nexport function useChipiSession(config: UseChipiSessionConfig): UseChipiSessionReturn {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const {\n wallet,\n encryptKey,\n getBearerToken,\n storedSession,\n onSessionCreated,\n defaultDurationSeconds = 21600, // 6 hours\n defaultMaxCalls = 1000,\n autoCheckStatus = true,\n } = config;\n\n // ============ Local Session State ============\n const [localSession, setLocalSession] = useState<SessionKeyData | null>(storedSession ?? null);\n const [error, setError] = useState<Error | null>(null);\n\n // Sync stored session when it changes\n useEffect(() => {\n setLocalSession(storedSession ?? null);\n }, [storedSession]);\n\n // ============ Computed Values ============\n const supportsSession = useMemo(() => {\n if (!wallet) return false;\n // CHIPI wallets support sessions, ARGENT wallets don't\n // If walletType is undefined (legacy), assume it doesn't support sessions\n return wallet.walletType === \"CHIPI\";\n }, [wallet]);\n\n // ============ Session Status Query ============\n const sessionStatusQuery = useQuery<SessionDataResponse | null, Error>({\n queryKey: [\"chipi-session-status\", wallet?.publicKey, localSession?.publicKey],\n queryFn: async () => {\n if (!wallet?.publicKey || !localSession?.publicKey) return null;\n return chipiSDK.sessions.getSessionData({\n walletAddress: wallet.publicKey,\n sessionPublicKey: localSession.publicKey,\n });\n },\n enabled: Boolean(\n autoCheckStatus && wallet?.publicKey && localSession?.publicKey && supportsSession\n ),\n staleTime: 30000, // 30 seconds\n });\n\n // ============ Session State Computation ============\n const sessionState = useMemo<SessionState>(() => {\n if (!localSession) return \"none\";\n\n const status = sessionStatusQuery.data;\n\n // If we have status data from the contract\n if (status) {\n if (!status.isActive) return \"revoked\";\n if (status.validUntil * 1000 < Date.now()) return \"expired\";\n if (status.remainingCalls <= 0) return \"expired\";\n return \"active\";\n }\n\n // No status data yet - check local expiration\n if (localSession.validUntil * 1000 < Date.now()) return \"expired\";\n\n // Session exists locally but no on-chain status - assume created but not registered\n return \"created\";\n }, [localSession, sessionStatusQuery.data]);\n\n const hasActiveSession = sessionState === \"active\";\n const isSessionExpired = sessionState === \"expired\";\n const remainingCalls = sessionStatusQuery.data?.remainingCalls;\n\n // ============ Create Session Mutation ============\n const createSessionMutation = useMutation<SessionKeyData, Error, Partial<CreateSessionKeyParams>>(\n {\n mutationFn: async (params = {}) => {\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!supportsSession)\n throw new Error(\n \"Wallet does not support sessions. Only CHIPI wallets support session keys.\"\n );\n\n const sessionData = chipiSDK.sessions.createSessionKey({\n encryptKey,\n durationSeconds: params.durationSeconds ?? defaultDurationSeconds,\n });\n\n return sessionData;\n },\n onSuccess: async (sessionData) => {\n setLocalSession(sessionData);\n setError(null);\n\n // Call the persistence callback if provided\n if (onSessionCreated) {\n await onSessionCreated(sessionData);\n }\n },\n onError: (err) => {\n setError(err);\n },\n }\n );\n\n // ============ Register Session Mutation ============\n const registerSessionMutation = useMutation<string, Error, Partial<SessionConfig>>({\n mutationFn: async (sessionConfig = {}) => {\n if (!wallet) throw new Error(\"Wallet is required\");\n if (!localSession) throw new Error(\"No session to register. Call createSession first.\");\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!supportsSession) throw new Error(\"Wallet does not support sessions\");\n\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.sessions.addSessionKeyToContract(\n {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n sessionConfig: {\n sessionPublicKey: localSession.publicKey,\n validUntil: sessionConfig.validUntil ?? localSession.validUntil,\n maxCalls: sessionConfig.maxCalls ?? defaultMaxCalls,\n allowedEntrypoints: sessionConfig.allowedEntrypoints ?? [],\n },\n },\n bearerToken\n );\n\n return txHash;\n },\n onSuccess: () => {\n setError(null);\n // Invalidate session status to refetch\n queryClient.invalidateQueries({\n queryKey: [\"chipi-session-status\", wallet?.publicKey, localSession?.publicKey],\n });\n },\n onError: (err) => {\n setError(err);\n },\n });\n\n // ============ Revoke Session Mutation ============\n const revokeSessionMutation = useMutation<string, Error, void>({\n mutationFn: async () => {\n if (!wallet) throw new Error(\"Wallet is required\");\n if (!localSession) throw new Error(\"No session to revoke\");\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!supportsSession) throw new Error(\"Wallet does not support sessions\");\n\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.sessions.revokeSessionKey(\n {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n sessionPublicKey: localSession.publicKey,\n },\n bearerToken\n );\n\n return txHash;\n },\n onSuccess: () => {\n setError(null);\n // Invalidate session status\n queryClient.invalidateQueries({\n queryKey: [\"chipi-session-status\", wallet?.publicKey, localSession?.publicKey],\n });\n },\n onError: (err) => {\n setError(err);\n },\n });\n\n // ============ Execute With Session Mutation ============\n const executeWithSessionMutation = useMutation<string, Error, Call[]>({\n mutationFn: async (calls) => {\n if (!wallet) throw new Error(\"Wallet is required\");\n if (!localSession) throw new Error(\"No active session\");\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!hasActiveSession) throw new Error(\"Session is not active. Register the session first.\");\n\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.executeTransactionWithSession({\n params: {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n session: localSession,\n calls,\n },\n bearerToken,\n });\n\n return txHash;\n },\n onSuccess: () => {\n setError(null);\n // Refetch status to update remaining calls\n queryClient.invalidateQueries({\n queryKey: [\"chipi-session-status\", wallet?.publicKey, localSession?.publicKey],\n });\n },\n onError: (err) => {\n setError(err);\n },\n });\n\n // ============ Set Spending Policy Mutation ============\n const setSpendingPolicyMutation = useMutation<\n string,\n Error,\n Omit<SpendingPolicyConfig, \"sessionPublicKey\">\n >({\n mutationFn: async (policyConfig) => {\n if (!wallet) throw new Error(\"Wallet is required\");\n if (!localSession)\n throw new Error(\"No session to set policy on. Create and register a session first.\");\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!supportsSession) throw new Error(\"Wallet does not support sessions\");\n\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.sessions.setSpendingPolicy(\n {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n spendingPolicyConfig: {\n sessionPublicKey: localSession.publicKey,\n ...policyConfig,\n },\n },\n bearerToken\n );\n\n return txHash;\n },\n onSuccess: () => {\n setError(null);\n },\n onError: (err) => {\n setError(err);\n },\n });\n\n // ============ Remove Spending Policy Mutation ============\n const removeSpendingPolicyMutation = useMutation<string, Error, string>({\n mutationFn: async (token) => {\n if (!wallet) throw new Error(\"Wallet is required\");\n if (!localSession) throw new Error(\"No session to remove policy from\");\n if (!encryptKey) throw new Error(\"Encryption key (PIN) is required\");\n if (!supportsSession) throw new Error(\"Wallet does not support sessions\");\n\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.sessions.removeSpendingPolicy(\n {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n sessionPublicKey: localSession.publicKey,\n token,\n },\n bearerToken\n );\n\n return txHash;\n },\n onSuccess: () => {\n setError(null);\n },\n onError: (err) => {\n setError(err);\n },\n });\n\n // ============ Actions ============\n const createSession = useCallback(\n async (params?: Partial<CreateSessionKeyParams>) => {\n return createSessionMutation.mutateAsync(params ?? {});\n },\n [createSessionMutation]\n );\n\n const registerSession = useCallback(\n async (sessionConfig?: Partial<SessionConfig>) => {\n return registerSessionMutation.mutateAsync(sessionConfig ?? {});\n },\n [registerSessionMutation]\n );\n\n const revokeSession = useCallback(async () => {\n return revokeSessionMutation.mutateAsync();\n }, [revokeSessionMutation]);\n\n const executeWithSession = useCallback(\n async (calls: Call[]) => {\n return executeWithSessionMutation.mutateAsync(calls);\n },\n [executeWithSessionMutation]\n );\n\n const clearSession = useCallback(() => {\n setLocalSession(null);\n setError(null);\n }, []);\n\n const refetchStatus = useCallback(async () => {\n await sessionStatusQuery.refetch();\n }, [sessionStatusQuery]);\n\n const setSpendingPolicy = useCallback(\n async (policyConfig: Omit<SpendingPolicyConfig, \"sessionPublicKey\">) => {\n return setSpendingPolicyMutation.mutateAsync(policyConfig);\n },\n [setSpendingPolicyMutation]\n );\n\n const getSpendingPolicy = useCallback(\n async (token: string): Promise<SpendingPolicyData> => {\n if (!wallet?.publicKey) throw new Error(\"Wallet is required\");\n if (!localSession?.publicKey) throw new Error(\"No session to query policy for\");\n return chipiSDK.sessions.getSpendingPolicy({\n walletAddress: wallet.publicKey,\n sessionPublicKey: localSession.publicKey,\n token,\n });\n },\n [chipiSDK, wallet, localSession]\n );\n\n const removeSpendingPolicy = useCallback(\n async (token: string) => {\n return removeSpendingPolicyMutation.mutateAsync(token);\n },\n [removeSpendingPolicyMutation]\n );\n\n // ============ Combined Error ============\n const combinedError = useMemo(() => {\n return (\n error ||\n createSessionMutation.error ||\n registerSessionMutation.error ||\n revokeSessionMutation.error ||\n executeWithSessionMutation.error ||\n setSpendingPolicyMutation.error ||\n removeSpendingPolicyMutation.error ||\n sessionStatusQuery.error ||\n null\n );\n }, [\n error,\n createSessionMutation.error,\n registerSessionMutation.error,\n revokeSessionMutation.error,\n executeWithSessionMutation.error,\n setSpendingPolicyMutation.error,\n removeSpendingPolicyMutation.error,\n sessionStatusQuery.error,\n ]);\n\n return {\n // Session data\n session: localSession,\n sessionStatus: sessionStatusQuery.data ?? undefined,\n sessionState,\n hasActiveSession,\n isSessionExpired,\n remainingCalls,\n supportsSession,\n\n // Actions\n createSession,\n registerSession,\n revokeSession,\n executeWithSession,\n clearSession,\n refetchStatus,\n\n // Spending Policy Actions\n setSpendingPolicy,\n getSpendingPolicy,\n removeSpendingPolicy,\n\n // Loading states\n isCreating: createSessionMutation.isPending,\n isRegistering: registerSessionMutation.isPending,\n isRevoking: revokeSessionMutation.isPending,\n isExecuting: executeWithSessionMutation.isPending,\n isLoadingStatus: sessionStatusQuery.isLoading,\n isSettingSpendingPolicy: setSpendingPolicyMutation.isPending,\n isRemovingSpendingPolicy: removeSpendingPolicyMutation.isPending,\n\n // Errors\n error: combinedError,\n };\n}\n","import { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { MigrateWalletToPasskeyParams, WalletData } from \"@chipi-stack/types\";\nimport { createWalletPasskey } from \"@chipi-stack/chipi-passkey\";\nimport { decryptPrivateKey, encryptPrivateKey, type ChipiWallets } from \"@chipi-stack/backend\";\n\ntype MigrateWalletToPasskeyInput = MigrateWalletToPasskeyParams & {\n bearerToken: string;\n};\n\ninterface MigrateWalletToPasskeyResult {\n success: boolean;\n wallet: WalletData;\n credentialId: string;\n}\n\n/**\n * Hook for migrating a wallet from encryptKey (PIN) to passkey authentication\n */\nexport function useMigrateWalletToPasskey(): {\n migrateWalletToPasskey: (input: MigrateWalletToPasskeyInput) => void;\n migrateWalletToPasskeyAsync: (\n input: MigrateWalletToPasskeyInput\n ) => Promise<MigrateWalletToPasskeyResult>;\n data: MigrateWalletToPasskeyResult | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const mutation: UseMutationResult<\n MigrateWalletToPasskeyResult,\n Error,\n MigrateWalletToPasskeyInput\n > = useMutation({\n mutationFn: async (input: MigrateWalletToPasskeyInput) => {\n const { wallet, oldEncryptKey, externalUserId, bearerToken } = input;\n\n try {\n // Step 1: Validate old encryptKey by decrypting first (before creating passkey)\n let decryptedPrivateKey: string;\n try {\n decryptedPrivateKey = decryptPrivateKey(wallet.encryptedPrivateKey, oldEncryptKey);\n } catch {\n throw new Error(\n \"Failed to decrypt wallet with provided encryptKey. Please verify your PIN/password is correct.\"\n );\n }\n\n // Step 2: Create new passkey only after PIN is confirmed valid\n const passkeyResult = await createWalletPasskey(\n externalUserId,\n externalUserId // Using externalUserId as userName\n );\n\n // Step 3: Re-encrypt with new passkey-derived encryptKey\n const newEncryptedPrivateKey = encryptPrivateKey(\n decryptedPrivateKey,\n passkeyResult.encryptKey\n );\n\n // Step 4: Persist new encrypted key to backend\n const updateResult = await (chipiSDK.wallets as ChipiWallets).updateWalletEncryption(\n {\n externalUserId,\n newEncryptedPrivateKey,\n publicKey: wallet.publicKey,\n },\n bearerToken\n );\n\n if (updateResult?.success === false) {\n throw new Error(\"Backend rejected wallet encryption update\");\n }\n\n const updatedWallet: WalletData = {\n ...wallet,\n encryptedPrivateKey: newEncryptedPrivateKey,\n };\n\n // Invalidate cached wallet so useChipiWallet/useGetWallet refetch\n queryClient.invalidateQueries({\n queryKey: [\"chipi-wallet\", externalUserId],\n });\n queryClient.invalidateQueries({\n queryKey: [\"wallet\", externalUserId],\n });\n\n return {\n success: true,\n wallet: updatedWallet,\n credentialId: passkeyResult.credentialId,\n };\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Migration failed: ${error.message}`);\n }\n throw new Error(\"Failed to migrate wallet to passkey\");\n }\n },\n });\n\n return {\n migrateWalletToPasskey: mutation.mutate,\n migrateWalletToPasskeyAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type {\n UpdateWalletEncryptionParams,\n UpdateWalletEncryptionResponse,\n} from \"@chipi-stack/types\";\nimport { ChipiWallets } from \"@chipi-stack/backend\";\n\ntype UpdateWalletEncryptionInput = UpdateWalletEncryptionParams & {\n bearerToken: string;\n};\n\n/**\n * Hook for updating a wallet's encrypted private key.\n * Use when the user changes their passkey or PIN; the client re-encrypts the private key\n * and sends the new ciphertext here.\n */\nexport function useUpdateWalletEncryption(): {\n updateWalletEncryption: (input: UpdateWalletEncryptionInput) => void;\n updateWalletEncryptionAsync: (\n input: UpdateWalletEncryptionInput\n ) => Promise<UpdateWalletEncryptionResponse>;\n data: UpdateWalletEncryptionResponse | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const mutation: UseMutationResult<\n UpdateWalletEncryptionResponse,\n Error,\n UpdateWalletEncryptionInput\n > = useMutation({\n mutationFn: async (input: UpdateWalletEncryptionInput) => {\n const { bearerToken, ...params } = input;\n return (chipiSDK.wallets as ChipiWallets).updateWalletEncryption(params, bearerToken);\n },\n onSuccess: (_, variables) => {\n queryClient.invalidateQueries({\n queryKey: [\"chipi-wallet\", variables.externalUserId],\n });\n },\n });\n\n return {\n updateWalletEncryption: mutation.mutate,\n updateWalletEncryptionAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { MigrateChipiWalletToShhhParams, MigrationOutcome } from \"@chipi-stack/backend\";\n\n/**\n * Input for the migration mutation.\n *\n * Drops `client` and `bearerToken` from the SDK-level params (the\n * hook reads them from context + the input below) and treats the\n * rest the same as the SDK call. The hook does NOT touch passkey /\n * PIN orchestration — callers are responsible for handing in the\n * already-resolved `encryptKey`. For the dashboard flow this means\n * showing the PIN/passkey prompt yourself and passing the result\n * here.\n */\ntype MigrateInput = Omit<MigrateChipiWalletToShhhParams, \"client\" | \"bearerToken\"> & {\n bearerToken: string;\n};\n\n/**\n * Hook for migrating a CHIPI v29 wallet to SHHH V8.4.\n *\n * Wraps the `migrateChipiWalletToShhh` backend SDK function (which\n * itself composes chipi-back's prepare + execute endpoints with\n * client-side V8.4 OE signing). The PIN/passkey unwrap step happens\n * before this hook is called; the migration multicall is signed\n * locally with the resulting STARK key and the cleartext key never\n * leaves the device.\n *\n * Two terminal outcomes the consumer must handle:\n * - `{ kind: \"MIGRATED\", transactionHash, ... }` — happy path,\n * on-chain tx landed and DB row is patched. If `partial: true`,\n * the on-chain tx succeeded but the chipi-back DB patch failed;\n * the operator runbook's reconciler cron (task #30) will catch\n * up automatically. Dashboard should surface \"wallet upgraded;\n * refresh in a moment\" copy in both sub-cases.\n * - `{ kind: \"ALREADY_MIGRATED\", primaryKind, ... }` — chipi-back\n * detected the wallet was already SHHH on chain and patched the\n * DB row on the way out. No on-chain tx fired. Dashboard should\n * surface \"this wallet is already on V8.4\" and refresh the\n * wallet shape.\n *\n * Throws (surfaces via `error`) on:\n * - STRANDED-state recovery (different signing flow, not in PR A)\n * - UNDEPLOYED wallets (caller should redirect to createWallet)\n * - DEFERRED legacy versions (v28/v33; not yet supported)\n * - Mismatched encryptKey (decryption fails)\n * - chipi-back kill switch off (`CHIPI_MIGRATION_ENABLED` not set)\n *\n * @example\n * ```tsx\n * const { migrateAsync, isLoading, error } = useMigrateWalletToShhh();\n *\n * async function onClickMigrate() {\n * const encryptKey = await promptForPin(); // or passkey unlock\n * const outcome = await migrateAsync({\n * walletId: wallet.id,\n * externalUserId: user.id,\n * wallet: { publicKey: wallet.publicKey, encryptedPrivateKey: wallet.encryptedPrivateKey },\n * encryptKey,\n * bearerToken,\n * });\n * if (outcome.kind === \"MIGRATED\") {\n * showToast(`Wallet upgraded — tx ${outcome.transactionHash}`);\n * } else {\n * showToast(`Wallet was already on V8.4 (${outcome.primaryKind})`);\n * }\n * }\n * ```\n */\nexport function useMigrateWalletToShhh(): {\n migrate: (input: MigrateInput) => void;\n migrateAsync: (input: MigrateInput) => Promise<MigrationOutcome>;\n data: MigrationOutcome | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<MigrationOutcome, Error, MigrateInput> = useMutation({\n mutationFn: async (input: MigrateInput) => {\n const { bearerToken, ...rest } = input;\n return chipiSDK.wallets.migrateToShhh(rest, bearerToken);\n },\n });\n\n return {\n migrate: mutation.mutate,\n migrateAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { TransferHookInput, WalletData } from \"@chipi-stack/types\";\n\ntype TransferInput = {\n params: TransferHookInput;\n bearerToken: string;\n};\n\n/**\n * Configuration for useTransfer hook.\n */\nexport interface UseTransferConfig {\n /**\n * Callback to prompt user for PIN when passkey fails.\n * Should show a PIN input dialog and return the PIN, or null to cancel.\n * Only called when usePasskey: true and passkey auth fails.\n */\n onPinRequired?: () => Promise<string | null>;\n}\n\n/**\n * Hook for transferring tokens.\n *\n * When `usePasskey: true`:\n * 1. Tries passkey authentication first\n * 2. If passkey fails and wallet has `encryptedPrivateKeyBackup`:\n * calls `onPinRequired` to get PIN, uses PIN to decrypt backup\n * 3. If no backup or no `onPinRequired`, throws\n *\n * @example\n * ```tsx\n * const { transferAsync } = useTransfer({\n * onPinRequired: async () => {\n * // Show PIN dialog, return PIN or null to cancel\n * return await showPinDialog();\n * },\n * });\n * ```\n */\nexport function useTransfer(config?: UseTransferConfig): {\n transfer: (input: TransferInput) => void;\n transferAsync: (input: TransferInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK, passkeyAdapter } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, TransferInput> = useMutation({\n mutationFn: async (input: TransferInput) => {\n let encryptKey = input.params.encryptKey;\n let walletForTransfer = input.params.wallet;\n\n // If usePasskey is true, try passkey first, fall back to PIN\n if (input.params.usePasskey) {\n if (!input.params.externalUserId) {\n throw new Error(\"externalUserId is required when usePasskey is true\");\n }\n\n // Try passkey authentication\n const passkeyKey = await passkeyAdapter.getWalletEncryptKey({\n externalUserId: input.params.externalUserId,\n });\n\n if (passkeyKey) {\n // Passkey succeeded — use passkey key with primary encryptedPrivateKey\n encryptKey = passkeyKey;\n } else {\n // Passkey failed (PRF unavailable, user cancelled, etc.)\n // Try PIN backup if wallet has encryptedPrivateKeyBackup\n const wallet = input.params.wallet as WalletData & {\n encryptedPrivateKeyBackup?: string;\n };\n\n if (wallet.encryptedPrivateKeyBackup && config?.onPinRequired) {\n const pin = await config.onPinRequired();\n if (!pin) {\n throw new Error(\"Transfer cancelled — PIN required as passkey fallback\");\n }\n encryptKey = pin;\n // Use the backup encrypted key for decryption\n walletForTransfer = {\n ...wallet,\n encryptedPrivateKey: wallet.encryptedPrivateKeyBackup,\n };\n } else if (wallet.encryptedPrivateKeyBackup) {\n throw new Error(\n \"Passkey authentication failed. Provide an onPinRequired callback to use PIN backup.\"\n );\n } else {\n throw new Error(\"Passkey authentication failed and no PIN backup available.\");\n }\n }\n }\n\n if (!encryptKey) {\n throw new Error(\"encryptKey is required when usePasskey is false\");\n }\n\n const {\n usePasskey: _usePasskey,\n externalUserId: _externalUserId,\n ...transferParams\n } = input.params;\n return chipiSDK.transfer({\n params: {\n ...transferParams,\n wallet: walletForTransfer,\n amount: String(transferParams.amount),\n encryptKey: encryptKey,\n },\n bearerToken: input.bearerToken,\n });\n },\n });\n\n return {\n transfer: mutation.mutate,\n transferAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { ApproveHookInput } from \"@chipi-stack/types\";\n\ntype ApproveInput = {\n params: ApproveHookInput;\n bearerToken: string;\n};\n\n/**\n * Hook for approving token spending\n */\nexport function useApprove(): {\n approve: (params: ApproveInput) => void;\n approveAsync: (params: ApproveInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK, passkeyAdapter } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, ApproveInput> = useMutation({\n mutationFn: async (params: ApproveInput) => {\n let encryptKey = params.params.encryptKey;\n\n // If usePasskey is true, authenticate with passkey to get encryptKey\n if (params.params.usePasskey) {\n if (!params.params.externalUserId) {\n throw new Error(\"externalUserId is required when usePasskey is true\");\n }\n try {\n const key = await passkeyAdapter.getWalletEncryptKey({\n externalUserId: params.params.externalUserId,\n });\n if (!key) {\n throw new Error(\"Passkey authentication was cancelled\");\n }\n encryptKey = key;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Passkey authentication failed: ${error.message}`);\n }\n throw new Error(\"Failed to authenticate with passkey\");\n }\n }\n\n if (!encryptKey) {\n throw new Error(\n \"encryptKey is required when usePasskey is false. Provide a PIN or enable usePasskey.\"\n );\n }\n\n const {\n usePasskey: _usePasskey,\n externalUserId: _externalUserId,\n ...approveParams\n } = params.params;\n return chipiSDK.approve({\n params: {\n ...approveParams,\n amount: String(approveParams.amount),\n encryptKey,\n },\n bearerToken: params.bearerToken,\n });\n },\n });\n\n return {\n approve: mutation.mutate,\n approveAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { PaginatedResponse, Transaction, GetTransactionListQuery } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype TransactionListInput = {\n query: GetTransactionListQuery;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<\n UseQueryOptions<PaginatedResponse<Transaction>, Error>,\n \"queryKey\" | \"queryFn\"\n >;\n};\n\ntype FetchTransactionListInput = {\n query: GetTransactionListQuery;\n getBearerToken: () => Promise<string | null | undefined>;\n};\n\nexport function useGetTransactionList(input?: TransactionListInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const buildQueryKey = (q?: GetTransactionListQuery) => [\n \"transaction-list\",\n q?.page ?? 1,\n q?.limit ?? 10,\n q?.calledFunction ?? null,\n q?.walletAddress,\n q?.day ?? null,\n q?.month ?? null,\n q?.year ?? null,\n ];\n\n const query = useQuery<PaginatedResponse<Transaction>, Error>({\n queryKey: buildQueryKey(input?.query),\n queryFn: async () => {\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransactionList(input.query, bearerToken);\n },\n enabled: Boolean(input?.getBearerToken),\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchTransactionList = async (newInput: FetchTransactionListInput) => {\n return queryClient.fetchQuery({\n queryKey: buildQueryKey(newInput.query),\n queryFn: async () => {\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransactionList(newInput.query, bearerToken);\n },\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchTransactionList,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { Transaction } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype GetTransactionInput = {\n hashOrId?: string;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<Transaction, Error>, \"queryKey\" | \"queryFn\">;\n};\n\ntype FetchTransactionInput = {\n hashOrId: string;\n getBearerToken: () => Promise<string | null | undefined>;\n};\n\nexport function useGetTransaction(input?: GetTransactionInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const buildQueryKey = (hashOrId?: string) => [\"transaction\", hashOrId ?? null];\n\n const query = useQuery<Transaction, Error>({\n queryKey: buildQueryKey(input?.hashOrId),\n queryFn: async () => {\n if (!input?.hashOrId) throw new Error(\"hashOrId is required\");\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransaction(input.hashOrId, bearerToken);\n },\n enabled: Boolean(input?.hashOrId && input?.getBearerToken),\n retry: (failureCount: number, error: Error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchTransaction = async (newInput: FetchTransactionInput) => {\n return queryClient.fetchQuery({\n queryKey: buildQueryKey(newInput.hashOrId),\n queryFn: async () => {\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransaction(newInput.hashOrId, bearerToken);\n },\n retry: (failureCount: number, error: Error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchTransaction,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { TransactionStatusResponse, OnChainTxStatus } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\n/** Terminal statuses that stop polling */\nconst TERMINAL_STATUSES: OnChainTxStatus[] = [\n OnChainTxStatus.ACCEPTED_ON_L1,\n OnChainTxStatus.REJECTED,\n OnChainTxStatus.REVERTED,\n];\n\ntype GetTransactionStatusInput = {\n hash?: string;\n getBearerToken?: () => Promise<string | null | undefined>;\n /** Polling interval in ms. Defaults to 3000. Set to false to disable polling. */\n refetchInterval?: number | false;\n queryOptions?: Omit<\n UseQueryOptions<TransactionStatusResponse, Error>,\n \"queryKey\" | \"queryFn\" | \"refetchInterval\"\n >;\n};\n\ntype FetchTransactionStatusInput = {\n hash: string;\n getBearerToken: () => Promise<string | null | undefined>;\n};\n\nexport function useGetTransactionStatus(input?: GetTransactionStatusInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const buildQueryKey = (hash?: string) => [\"transaction-status\", hash ?? null];\n\n const query = useQuery<TransactionStatusResponse, Error>({\n queryKey: buildQueryKey(input?.hash),\n queryFn: async () => {\n if (!input?.hash) throw new Error(\"hash is required\");\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransactionStatus(input.hash, bearerToken);\n },\n enabled: Boolean(input?.hash && input?.getBearerToken),\n refetchInterval: (query) => {\n // Stop polling on terminal statuses\n const status = query.state.data?.status;\n if (status && TERMINAL_STATUSES.includes(status)) {\n return false;\n }\n return input?.refetchInterval ?? 3000;\n },\n retry: (failureCount: number, error: Error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchTransactionStatus = async (newInput: FetchTransactionStatusInput) => {\n return queryClient.fetchQuery({\n queryKey: buildQueryKey(newInput.hash),\n queryFn: async () => {\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTransactionStatus(newInput.hash, bearerToken);\n },\n retry: (failureCount: number, error: Error) => {\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchTransactionStatus,\n };\n}\n","\"use client\";\n\nimport { useMutation, useQueryClient, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { SyncOnChainTransfersParams, SyncOnChainTransfersResponse } from \"@chipi-stack/types\";\n\ntype SyncOnChainInput = SyncOnChainTransfersParams & {\n bearerToken: string;\n};\n\n/**\n * Hook for syncing on-chain transfers from Voyager into the DB.\n *\n * Discovers transactions not made through the SDK (e.g., external USDC receives\n * from Argent X or other wallets). After sync, useGetTransactionList returns\n * the newly discovered transactions automatically.\n *\n * @example\n * ```tsx\n * const { syncTransfers, data, isLoading } = useSyncOnChainTransfers();\n *\n * // Sync on-chain transfers for a wallet\n * const result = await syncTransfersAsync({\n * walletAddress: wallet.publicKey,\n * bearerToken: await getToken(),\n * });\n * console.log(`Synced ${result.synced} new transfers`);\n * ```\n */\nexport function useSyncOnChainTransfers(): {\n syncTransfers: (input: SyncOnChainInput) => void;\n syncTransfersAsync: (input: SyncOnChainInput) => Promise<SyncOnChainTransfersResponse>;\n data: SyncOnChainTransfersResponse | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const mutation: UseMutationResult<SyncOnChainTransfersResponse, Error, SyncOnChainInput> =\n useMutation({\n mutationFn: async (input: SyncOnChainInput) => {\n const { bearerToken, ...params } = input;\n return chipiSDK.transactions.syncOnChainTransfers(params, bearerToken);\n },\n onSuccess: () => {\n // Invalidate transaction list cache so new txs appear immediately\n queryClient.invalidateQueries({\n predicate: (query) => query.queryKey[0] === \"transaction-list\",\n });\n },\n });\n\n return {\n syncTransfers: mutation.mutate,\n syncTransfersAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport { CreateSkuPurchaseParams, Transaction } from \"@chipi-stack/types\";\n\ntype PurchaseSkuInput = {\n params: CreateSkuPurchaseParams;\n bearerToken: string;\n};\n\n/**\n * Hook for purchasing SKUs\n */\nexport function usePurchaseSku(): {\n purchaseSku: (input: PurchaseSkuInput) => void;\n purchaseSkuAsync: (input: PurchaseSkuInput) => Promise<Transaction>;\n data: Transaction | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<Transaction, Error, PurchaseSkuInput> = useMutation({\n mutationFn: (input: PurchaseSkuInput) =>\n chipiSDK.purchaseSku({\n params: input.params,\n bearerToken: input.bearerToken,\n }),\n });\n\n return {\n purchaseSku: mutation.mutate,\n purchaseSkuAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { Transaction } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\n\ntype GetSkuPurchaseInput = {\n id: string;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<Transaction, Error>, \"queryKey\" | \"queryFn\">;\n};\n\nexport function useGetSkuPurchase(input?: GetSkuPurchaseInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const query = useQuery<Transaction, Error>({\n queryKey: [\"sku-purchase\", input?.id],\n queryFn: async () => {\n if (!input?.id) throw new Error(\"id is required\");\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSkuPurchase(input.id, bearerToken);\n },\n enabled: Boolean(input?.id && input?.getBearerToken),\n ...input?.queryOptions,\n });\n\n const fetchSkuPurchase = async (newInput: GetSkuPurchaseInput) => {\n return queryClient.fetchQuery({\n queryKey: [\"sku-purchase\", newInput?.id],\n queryFn: async () => {\n if (!newInput?.id) throw new Error(\"id is required\");\n if (!newInput?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSkuPurchase(newInput.id, bearerToken);\n },\n });\n };\n\n return {\n ...query,\n fetchSkuPurchase,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { PaginatedResponse, Sku, GetSkuListQuery } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype SkuListInput = {\n query: GetSkuListQuery;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<PaginatedResponse<Sku>, Error>, \"queryKey\" | \"queryFn\">;\n};\n\nexport function useGetSkuList(input?: SkuListInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const buildQueryKey = (q?: GetSkuListQuery) => [\n \"available-skus\",\n q?.page ?? 1,\n q?.limit ?? 10,\n q?.offset ?? 0,\n q?.provider ?? null,\n q?.category ?? null,\n ];\n\n const query = useQuery<PaginatedResponse<Sku>, Error>({\n queryKey: buildQueryKey(input?.query),\n queryFn: async () => {\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSkuList(input.query, bearerToken);\n },\n enabled: Boolean(input?.getBearerToken),\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchSkuList = async (newInput: SkuListInput) => {\n return queryClient.fetchQuery({\n queryKey: buildQueryKey(newInput?.query),\n queryFn: async () => {\n if (!newInput?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSkuList(newInput.query, bearerToken);\n },\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchSkuList,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { Sku } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype GetSkuInput = {\n id: string;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<Sku, Error>, \"queryKey\" | \"queryFn\">;\n};\n\nexport function useGetSku(input?: GetSkuInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const query = useQuery<Sku, Error>({\n queryKey: [\"sku\", input?.id],\n queryFn: async () => {\n if (!input?.id || !input?.getBearerToken)\n throw new Error(\"id and getBearerToken are required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSku(input.id, bearerToken);\n },\n enabled: Boolean(input?.id && input?.getBearerToken && input.id.trim() !== \"\"),\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchSku = async (input: GetSkuInput): Promise<Sku> => {\n return queryClient.fetchQuery({\n queryKey: [\"sku\", input?.id],\n queryFn: async () => {\n if (!input?.getBearerToken) throw new Error(\"getBearerToken is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getSku(input.id, bearerToken);\n },\n retry: (failureCount, error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchSku,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { CallAnyContractParams } from \"@chipi-stack/types\";\n\ntype CallAnyContractInput = {\n params: CallAnyContractParams;\n bearerToken: string;\n};\n\n/**\n * Hook for calling any contract method\n */\nexport function useCallAnyContract(): {\n callAnyContract: (params: CallAnyContractInput) => void;\n callAnyContractAsync: (params: CallAnyContractInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK, passkeyAdapter } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, CallAnyContractInput> = useMutation({\n mutationFn: async (params: CallAnyContractInput) => {\n let encryptKey = params.params.encryptKey;\n\n // If usePasskey is true, authenticate with passkey to get encryptKey\n if (params.params.usePasskey) {\n if (!params.params.externalUserId) {\n throw new Error(\"externalUserId is required when usePasskey is true\");\n }\n try {\n const key = await passkeyAdapter.getWalletEncryptKey({\n externalUserId: params.params.externalUserId,\n });\n if (!key) {\n throw new Error(\"Passkey authentication was cancelled\");\n }\n encryptKey = key;\n } catch (error) {\n if (error instanceof DOMException && error.name === \"NotAllowedError\") {\n throw new Error(\"Passkey authentication was cancelled by the user\");\n }\n if (error instanceof Error) {\n throw error;\n }\n throw new Error(\"Failed to authenticate with passkey\");\n }\n }\n\n if (!encryptKey) {\n throw new Error(\"encryptKey is required when usePasskey is false\");\n }\n\n const {\n usePasskey: _usePasskey,\n externalUserId: _externalUserId,\n ...contractParams\n } = params.params;\n return chipiSDK.callAnyContract({\n params: {\n ...contractParams,\n encryptKey: encryptKey,\n },\n bearerToken: params.bearerToken,\n });\n },\n });\n\n return {\n callAnyContract: mutation.mutate,\n callAnyContractAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { RecordSendTransactionParams, Transaction } from \"@chipi-stack/types\";\n\ntype RecordSendTransactionInput = {\n params: RecordSendTransactionParams;\n bearerToken: string;\n};\n\nexport function useRecordSendTransaction(): {\n recordSendTransaction: (input: RecordSendTransactionInput) => void;\n recordSendTransactionAsync: (input: RecordSendTransactionInput) => Promise<Transaction>;\n data: Transaction | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<Transaction, Error, RecordSendTransactionInput> = useMutation({\n mutationFn: (input: RecordSendTransactionInput) =>\n chipiSDK.recordSendTransaction({\n params: input.params,\n bearerToken: input.bearerToken,\n }),\n });\n\n return {\n recordSendTransaction: mutation.mutate,\n recordSendTransactionAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","\"use client\";\n\nimport { useQuery, useQueryClient, type UseQueryOptions } from \"@tanstack/react-query\";\nimport { GetTokenBalanceParams, GetTokenBalanceResponse } from \"@chipi-stack/types\";\nimport { useChipiContext } from \"../context\";\nimport { ChipiApiError } from \"@chipi-stack/shared\";\n\ntype GetTokenBalanceInput = {\n params?: GetTokenBalanceParams;\n getBearerToken?: () => Promise<string | null | undefined>;\n queryOptions?: Omit<UseQueryOptions<GetTokenBalanceResponse, Error>, \"queryKey\" | \"queryFn\">;\n};\n\nexport function useGetTokenBalance(input?: GetTokenBalanceInput) {\n const { chipiSDK } = useChipiContext();\n const queryClient = useQueryClient();\n\n const buildQueryKey = (params?: GetTokenBalanceParams) => [\n \"chain-token-balance\",\n params?.chainToken ?? null,\n params?.chain ?? null,\n params?.walletPublicKey ?? null,\n params?.externalUserId ?? null,\n ];\n\n const query = useQuery<GetTokenBalanceResponse, Error>({\n queryKey: buildQueryKey(input?.params),\n queryFn: async () => {\n if (!input || !input.params || !input.getBearerToken) throw new Error(\"Input is required\");\n const bearerToken = await input.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTokenBalance(input.params, bearerToken);\n },\n enabled: Boolean(input?.params && input?.getBearerToken),\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n ...input?.queryOptions,\n });\n\n const fetchTokenBalance = async (newInput: GetTokenBalanceInput) => {\n return queryClient.fetchQuery({\n queryKey: buildQueryKey(newInput?.params),\n queryFn: async () => {\n if (!newInput || !newInput.getBearerToken || !newInput.params)\n throw new Error(\"Input is required\");\n const bearerToken = await newInput.getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n return chipiSDK.getTokenBalance(newInput.params, bearerToken);\n },\n retry: (failureCount: number, error: Error) => {\n // Don't retry on API errors (errors with status codes like 404, 400, etc.)\n if (error instanceof ChipiApiError || (error as any)?.status) {\n return false;\n }\n // Retry on network errors (no status code) up to 3 times\n return failureCount < 3;\n },\n });\n };\n\n return {\n ...query,\n fetchTokenBalance,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { CreateSessionKeyParams, SessionKeyData } from \"@chipi-stack/types\";\n\n/**\n * Hook for creating a session keypair locally.\n *\n * This generates session keys but does NOT register them on-chain.\n * The returned SessionKeyData should be stored by the developer externally\n * (e.g., in Clerk metadata, database, etc.) - the SDK does NOT persist this.\n *\n * After generating, call `useAddSessionKeyToContract` to register the session on-chain.\n *\n * @example\n * ```typescript\n * const { createSessionKey, data: session } = useCreateSessionKey();\n *\n * // Generate session keypair\n * createSessionKey({\n * encryptKey: userEncryptKey,\n * durationSeconds: 21600 // 6 hours (optional, default)\n * });\n *\n * // Store session externally after creation\n * if (session) {\n * await saveToClerk(session);\n * }\n * ```\n */\nexport function useCreateSessionKey(): {\n createSessionKey: (params: CreateSessionKeyParams) => void;\n createSessionKeyAsync: (params: CreateSessionKeyParams) => Promise<SessionKeyData>;\n data: SessionKeyData | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<SessionKeyData, Error, CreateSessionKeyParams> = useMutation({\n mutationFn: async (params: CreateSessionKeyParams) =>\n chipiSDK.sessions.createSessionKey(params),\n });\n\n return {\n createSessionKey: mutation.mutate,\n createSessionKeyAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { AddSessionKeyParams } from \"@chipi-stack/types\";\n\ntype AddSessionKeyInput = {\n params: AddSessionKeyParams;\n bearerToken: string;\n};\n\n/**\n * Hook for registering a session key on the smart contract.\n *\n * This executes a sponsored transaction (using owner signature) to call\n * `add_or_update_session_key` on the CHIPI wallet contract.\n *\n * The session must be registered before it can be used for transactions.\n * Only works with CHIPI wallets.\n *\n * @example\n * ```typescript\n * const { addSessionKeyToContract, isLoading } = useAddSessionKeyToContract();\n *\n * // Register session on-chain\n * addSessionKeyToContract({\n * params: {\n * encryptKey: userEncryptKey,\n * wallet: userWallet,\n * sessionConfig: {\n * sessionPublicKey: session.publicKey,\n * validUntil: session.validUntil,\n * maxCalls: 1000,\n * allowedEntrypoints: [] // empty = all allowed\n * }\n * },\n * bearerToken\n * });\n * ```\n */\nexport function useAddSessionKeyToContract(): {\n addSessionKeyToContract: (input: AddSessionKeyInput) => void;\n addSessionKeyToContractAsync: (input: AddSessionKeyInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, AddSessionKeyInput> = useMutation({\n mutationFn: (input: AddSessionKeyInput) =>\n chipiSDK.sessions.addSessionKeyToContract(input.params, input.bearerToken),\n });\n\n return {\n addSessionKeyToContract: mutation.mutate,\n addSessionKeyToContractAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { RevokeSessionKeyParams } from \"@chipi-stack/types\";\n\ntype RevokeSessionKeyInput = {\n params: RevokeSessionKeyParams;\n bearerToken: string;\n};\n\n/**\n * Hook for revoking a session key from the smart contract.\n *\n * This executes a sponsored transaction (using owner signature) to call\n * `revoke_session_key` on the CHIPI wallet contract.\n *\n * After revocation, the session key can no longer be used for transactions.\n * Only works with CHIPI wallets.\n *\n * @example\n * ```typescript\n * const { revokeSessionKey, isLoading } = useRevokeSessionKey();\n *\n * // Revoke a session\n * revokeSessionKey({\n * params: {\n * encryptKey: userEncryptKey,\n * wallet: userWallet,\n * sessionPublicKey: session.publicKey\n * },\n * bearerToken\n * });\n * ```\n */\nexport function useRevokeSessionKey(): {\n revokeSessionKey: (input: RevokeSessionKeyInput) => void;\n revokeSessionKeyAsync: (input: RevokeSessionKeyInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, RevokeSessionKeyInput> = useMutation({\n mutationFn: (input: RevokeSessionKeyInput) =>\n chipiSDK.sessions.revokeSessionKey(input.params, input.bearerToken),\n });\n\n return {\n revokeSessionKey: mutation.mutate,\n revokeSessionKeyAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { GetSessionDataParams, SessionDataResponse } from \"@chipi-stack/types\";\n\n/**\n * Hook for querying session data from the smart contract.\n *\n * This is a read-only call that does not require signing or gas.\n * Returns the on-chain state of a session key including:\n * - Whether it's active\n * - When it expires\n * - Remaining calls\n * - Allowed entrypoints\n *\n * @example\n * ```typescript\n * const { data: sessionData, isLoading } = useGetSessionData({\n * walletAddress: userWallet.publicKey,\n * sessionPublicKey: session.publicKey\n * });\n *\n * if (sessionData?.isActive) {\n * console.log(`Session has ${sessionData.remainingCalls} calls remaining`);\n * }\n * ```\n */\nexport function useGetSessionData(\n params: GetSessionDataParams | null,\n options?: { enabled?: boolean }\n): {\n data: SessionDataResponse | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n refetch: UseQueryResult<SessionDataResponse, Error>[\"refetch\"];\n} {\n const { chipiSDK } = useChipiContext();\n\n const query: UseQueryResult<SessionDataResponse, Error> = useQuery({\n queryKey: [\"sessionData\", params?.walletAddress, params?.sessionPublicKey],\n queryFn: () => {\n if (!params) {\n throw new Error(\"Session data params are required\");\n }\n return chipiSDK.sessions.getSessionData(params);\n },\n enabled: options?.enabled !== false && params !== null,\n });\n\n return {\n data: query.data,\n isLoading: query.isLoading,\n isError: query.isError,\n error: query.error,\n isSuccess: query.isSuccess,\n refetch: query.refetch,\n };\n}\n","import { useMutation, type UseMutationResult } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type { ExecuteWithSessionParams } from \"@chipi-stack/types\";\n\ntype ExecuteWithSessionInput = {\n params: ExecuteWithSessionParams;\n bearerToken: string;\n};\n\n/**\n * Hook for executing a gasless transaction using a session key.\n *\n * This uses the 4-element session signature format instead of owner signature.\n * The session must be:\n * 1. Generated via `useCreateSessionKey`\n * 2. Registered on-chain via `useAddSessionKeyToContract`\n *\n * Only works with CHIPI wallets.\n *\n * @example\n * ```typescript\n * const { executeWithSession, isLoading } = useExecuteWithSession();\n *\n * // Execute a transfer using session key (no owner key needed)\n * executeWithSession({\n * params: {\n * encryptKey: userEncryptKey,\n * wallet: userWallet,\n * session: sessionKeyData,\n * calls: [{\n * contractAddress: USDC_ADDRESS,\n * entrypoint: 'transfer',\n * calldata: [recipient, amount, '0x0']\n * }]\n * },\n * bearerToken\n * });\n * ```\n */\nexport function useExecuteWithSession(): {\n executeWithSession: (input: ExecuteWithSessionInput) => void;\n executeWithSessionAsync: (input: ExecuteWithSessionInput) => Promise<string>;\n data: string | undefined;\n isLoading: boolean;\n isError: boolean;\n error: Error | null;\n isSuccess: boolean;\n reset: () => void;\n} {\n const { chipiSDK } = useChipiContext();\n\n const mutation: UseMutationResult<string, Error, ExecuteWithSessionInput> = useMutation({\n mutationFn: (input: ExecuteWithSessionInput) =>\n chipiSDK.executeTransactionWithSession({\n params: input.params,\n bearerToken: input.bearerToken,\n }),\n });\n\n return {\n executeWithSession: mutation.mutate,\n executeWithSessionAsync: mutation.mutateAsync,\n data: mutation.data,\n isLoading: mutation.isPending,\n isError: mutation.isError,\n error: mutation.error,\n isSuccess: mutation.isSuccess,\n reset: mutation.reset,\n };\n}\n","\"use client\";\n\nimport { useCallback, useMemo, useRef, useState } from \"react\";\nimport { useMutation } from \"@tanstack/react-query\";\nimport { useChipiContext } from \"../context\";\nimport type {\n WalletData,\n WalletType,\n PaymentRequirement,\n PaymentPayload,\n SessionKeyData,\n} from \"@chipi-stack/types\";\nimport { buildX402TypedData } from \"@chipi-stack/core\";\n\n/**\n * Configuration for useX402Payment hook\n */\nexport interface UseX402PaymentConfig {\n /** Wallet data */\n wallet: WalletData | null | undefined;\n /** Encryption key for signing */\n encryptKey: string;\n /** Function to get the bearer token for API calls */\n getBearerToken?: () => Promise<string | null | undefined>;\n /** Static bearer token string (alternative to getBearerToken) */\n bearerToken?: string;\n /** Max amount per payment (USDC, human-readable e.g. \"1.00\") */\n maxPaymentAmount?: string;\n /** Alias for maxPaymentAmount */\n maxAmount?: string;\n /** Allowed recipient addresses (whitelist). Empty = allow all. */\n allowedRecipients?: string[];\n /** Active session for automatic payments (optional) */\n session?: SessionKeyData | null;\n /** Callback on successful payment */\n onPaymentComplete?: (txHash: string, amount: string) => void | Promise<void>;\n}\n\n/**\n * Last payment info returned by the hook\n */\nexport interface LastPaymentInfo {\n txHash: string | null;\n amount: string | null;\n timestamp: number;\n}\n\n/**\n * Return type for useX402Payment hook\n */\nexport interface UseX402PaymentReturn {\n /** Fetch wrapper that auto-handles 402 payments */\n x402Fetch: (url: string, init?: Record<string, any>) => Promise<Response>;\n /** Alias for x402Fetch */\n payFetch: (url: string, init?: Record<string, any>) => Promise<Response>;\n /** Manual payment signing (for custom flows) */\n signPayment: (requirement: PaymentRequirement) => Promise<PaymentPayload>;\n /** Whether a payment is in progress */\n isPaying: boolean;\n /** Last payment transaction hash */\n lastTxHash: string | null;\n /** Last payment amount (human-readable USDC) */\n lastAmount: string | null;\n /** Last payment info (txHash + amount + timestamp) */\n lastPayment: LastPaymentInfo | null;\n /** Total USDC spent in this session (human-readable) */\n totalSpent: string;\n /** Error from last payment attempt */\n error: Error | null;\n /** Total payments made in this session */\n paymentCount: number;\n}\n\n/**\n * React hook for x402 payment protocol support.\n *\n * Wraps fetch calls with automatic HTTP 402 payment handling.\n * When a server returns 402, the hook:\n * 1. Parses the payment requirement\n * 2. Validates against configured limits\n * 3. Signs using the wallet (or session key for automatic payments)\n * 4. Retries with the X-PAYMENT header\n *\n * @example\n * ```tsx\n * const { x402Fetch, isPaying, lastTxHash, paymentCount } = useX402Payment({\n * wallet,\n * encryptKey: pin,\n * getBearerToken: getToken,\n * maxPaymentAmount: \"1.00\",\n * onPaymentComplete: (txHash, amount) => {\n * console.log(`Paid ${amount} USDC, tx: ${txHash}`);\n * },\n * });\n *\n * // Automatic 402 handling\n * const response = await x402Fetch(\"https://api.example.com/premium\");\n * const data = await response.json();\n * ```\n */\nexport function useX402Payment(config: UseX402PaymentConfig): UseX402PaymentReturn {\n const { chipiSDK } = useChipiContext();\n\n const {\n wallet,\n encryptKey,\n getBearerToken: getBearerTokenFn,\n bearerToken: staticBearerToken,\n maxPaymentAmount: maxPaymentAmountProp,\n maxAmount,\n allowedRecipients,\n session,\n onPaymentComplete,\n } = config;\n\n // Resolve maxPaymentAmount: explicit prop takes precedence over alias\n const maxPaymentAmount = maxPaymentAmountProp ?? maxAmount;\n\n // Resolve getBearerToken: function takes precedence over static string\n const getBearerToken = useMemo(\n () =>\n getBearerTokenFn ??\n (staticBearerToken\n ? () => Promise.resolve(staticBearerToken)\n : () => Promise.resolve(undefined)),\n [getBearerTokenFn, staticBearerToken]\n );\n\n const [lastTxHash, setLastTxHash] = useState<string | null>(null);\n const [lastAmount, setLastAmount] = useState<string | null>(null);\n const [lastPayment, setLastPayment] = useState<LastPaymentInfo | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const paymentCountRef = useRef(0);\n const [paymentCount, setPaymentCount] = useState(0);\n const totalSpentRef = useRef(0n);\n const [totalSpent, setTotalSpent] = useState(\"0.000000\");\n\n /**\n * Parse PAYMENT-REQUIRED header from a 402 response\n */\n const parsePaymentRequired = useCallback((response: Response): PaymentRequirement => {\n const headerValue = response.headers.get(\"payment-required\");\n\n if (!headerValue) {\n throw new Error(\n \"Server returned 402 but no PAYMENT-REQUIRED header. \" +\n \"The server may not support x402 or is misconfigured.\"\n );\n }\n\n try {\n return JSON.parse(headerValue);\n } catch {\n throw new Error(\"Malformed PAYMENT-REQUIRED header: invalid JSON\");\n }\n }, []);\n\n /**\n * Validate payment requirement against config limits and protocol constraints\n */\n const validateRequirement = useCallback(\n (requirement: PaymentRequirement): void => {\n // Validate protocol constraints\n if (requirement.scheme !== \"exact\") {\n throw new Error(\n `Unsupported payment scheme: \"${requirement.scheme}\". Only \"exact\" is supported.`\n );\n }\n if (requirement.network !== \"starknet-mainnet\") {\n throw new Error(\n `Unsupported network: \"${requirement.network}\". Only \"starknet-mainnet\" is supported.`\n );\n }\n\n // Validate asset is USDC\n const USDC_MAINNET = \"0x033068F6539f8e6e6b131e6B2B814e6c34A5224bC66947c47DaB9dFeE93b35fb\";\n const normalizeAddr = (a: string) => a.toLowerCase().replace(/^0x0+/, \"0x\");\n if (normalizeAddr(requirement.asset) !== normalizeAddr(USDC_MAINNET)) {\n throw new Error(`Unsupported asset: ${requirement.asset}. Only USDC is supported.`);\n }\n\n // Validate required fields\n if (!requirement.payTo) {\n throw new Error(\"Invalid payment requirement: missing payTo address\");\n }\n\n // Validate maxTimeoutSeconds\n const timeoutSeconds = Number(requirement.maxTimeoutSeconds);\n if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {\n throw new Error(\"Invalid payment requirement: maxTimeoutSeconds must be a positive number\");\n }\n\n // Validate maxAmountRequired\n let requiredAmount: bigint;\n try {\n requiredAmount = BigInt(requirement.maxAmountRequired);\n } catch {\n throw new Error(\"Invalid payment requirement: maxAmountRequired must be an integer string\");\n }\n if (requiredAmount <= 0n) {\n throw new Error(\"Invalid payment requirement: maxAmountRequired must be > 0\");\n }\n\n if (maxPaymentAmount) {\n const trimmed = maxPaymentAmount.trim();\n if (!/^\\d+(\\.\\d{1,6})?$/.test(trimmed)) {\n throw new Error(`Invalid maxPaymentAmount format: \"${maxPaymentAmount}\"`);\n }\n // String-based conversion to avoid floating-point precision issues\n const [whole, frac = \"\"] = trimmed.split(\".\");\n const fracPadded = (frac + \"000000\").slice(0, 6);\n const maxBaseUnits = BigInt((whole || \"0\") + fracPadded);\n\n if (requiredAmount > maxBaseUnits) {\n const requiredHuman = (Number(requiredAmount) / 1_000_000).toFixed(6);\n throw new Error(\n `Payment amount ${requiredHuman} USDC exceeds maximum allowed ${maxPaymentAmount} USDC`\n );\n }\n }\n\n if (allowedRecipients && allowedRecipients.length > 0) {\n const normalize = (a: string) => a.toLowerCase().replace(/^0x0+/, \"0x\");\n const normalized = normalize(requirement.payTo);\n const isAllowed = allowedRecipients.some((addr) => normalize(addr) === normalized);\n if (!isAllowed) {\n throw new Error(`Recipient ${requirement.payTo} is not in the allowed recipients list`);\n }\n }\n },\n [maxPaymentAmount, allowedRecipients]\n );\n\n /**\n * Sign a SNIP-12 typed data payment message.\n * Uses session key if available, otherwise signs locally via signTypedData().\n */\n const signPayment = useCallback(\n async (requirement: PaymentRequirement): Promise<PaymentPayload> => {\n if (!wallet) {\n throw new Error(\"Wallet is required for x402 payments\");\n }\n if (!encryptKey) {\n throw new Error(\"Encryption key (PIN) is required for x402 payments\");\n }\n\n validateRequirement(requirement);\n\n const nonce = crypto.randomUUID();\n const validUntil = Math.floor(Date.now() / 1000) + requirement.maxTimeoutSeconds;\n\n // Session key path: session keys use a 4-element signature format\n // [sessionPubKey, r, s, validUntil] that requires the full paymaster\n // execution flow (prepare-typed-data → sign → execute-sponsored-transaction).\n // We keep the executeTransactionWithSession flow here because the facilitator's\n // settle() is a no-op for session-executed payments (already on-chain).\n if (session) {\n const bearerToken = await getBearerToken();\n if (!bearerToken) throw new Error(\"Bearer token is required\");\n\n const txHash = await chipiSDK.executeTransactionWithSession({\n params: {\n encryptKey,\n wallet: wallet as WalletData & { walletType?: WalletType },\n session,\n calls: [\n {\n contractAddress: requirement.asset,\n entrypoint: \"transfer\",\n calldata: [requirement.payTo, requirement.maxAmountRequired, \"0x0\"],\n },\n ],\n },\n bearerToken,\n });\n\n return {\n x402Version: 1,\n scheme: \"exact\",\n network: \"starknet-mainnet\",\n payload: {\n signature: { r: txHash, s: \"session\" },\n fromAddress: wallet.publicKey,\n toAddress: requirement.payTo,\n amount: requirement.maxAmountRequired,\n asset: requirement.asset,\n validUntil,\n nonce,\n },\n };\n }\n\n // Standard wallet path: sign SNIP-12 typed data locally without executing a transaction.\n const typedData = buildX402TypedData({\n from_address: wallet.publicKey,\n to_address: requirement.payTo,\n amount: requirement.maxAmountRequired,\n asset: requirement.asset,\n valid_until: String(validUntil),\n nonce,\n });\n\n const signature = await chipiSDK.signTypedData({\n params: {\n encryptKey,\n wallet,\n typedData,\n },\n });\n\n return {\n x402Version: 1,\n scheme: \"exact\",\n network: \"starknet-mainnet\",\n payload: {\n signature,\n fromAddress: wallet.publicKey,\n toAddress: requirement.payTo,\n amount: requirement.maxAmountRequired,\n asset: requirement.asset,\n validUntil,\n nonce,\n },\n };\n },\n [wallet, encryptKey, session, getBearerToken, chipiSDK, validateRequirement]\n );\n\n /**\n * Payment mutation for tracking state\n */\n const paymentMutation = useMutation<Response, Error, { url: string; init?: Record<string, any> }>(\n {\n mutationFn: async ({ url, init }) => {\n const response = await globalThis.fetch(url, init);\n\n if (response.status !== 402) {\n return response;\n }\n\n const requirement = parsePaymentRequired(response);\n const payment = await signPayment(requirement);\n\n // Track payment\n const humanAmount = (Number(BigInt(requirement.maxAmountRequired)) / 1_000_000).toFixed(6);\n // Session payments store txHash in signature.r with s=\"session\" marker.\n // Standard wallet payments have ECDSA signature components, not a txHash.\n const isSessionPayment = payment.payload.signature.s === \"session\";\n const txHash = isSessionPayment ? payment.payload.signature.r : null;\n\n setLastAmount(humanAmount);\n setLastTxHash(txHash);\n\n setLastPayment({ txHash, amount: humanAmount, timestamp: Date.now() });\n\n totalSpentRef.current += BigInt(requirement.maxAmountRequired);\n setTotalSpent((Number(totalSpentRef.current) / 1_000_000).toFixed(6));\n\n paymentCountRef.current += 1;\n setPaymentCount(paymentCountRef.current);\n\n // Retry with payment header\n const headers = new Headers(init?.headers);\n headers.set(\"X-PAYMENT\", JSON.stringify(payment));\n\n const paidResponse = await globalThis.fetch(url, { ...init, headers });\n if (paidResponse.status === 402) {\n throw new Error(\n \"Server returned 402 after payment was submitted. Payment may have failed verification.\"\n );\n }\n\n // Completion callback (fire-and-forget, don't block response)\n if (onPaymentComplete) {\n void Promise.resolve(onPaymentComplete(txHash ?? \"\", humanAmount)).catch(() => {});\n }\n\n return paidResponse;\n },\n onError: (err) => {\n setError(err);\n },\n onSuccess: () => {\n setError(null);\n },\n }\n );\n\n const x402Fetch = useCallback(\n async (url: string, init?: Record<string, any>): Promise<Response> => {\n return paymentMutation.mutateAsync({ url, init });\n },\n [paymentMutation]\n );\n\n return {\n x402Fetch,\n payFetch: x402Fetch,\n signPayment,\n isPaying: paymentMutation.isPending,\n lastTxHash,\n lastAmount,\n lastPayment,\n totalSpent,\n error: error || paymentMutation.error || null,\n paymentCount,\n };\n}\n","import { useMemo } from \"react\";\nimport {\n buildStarkEnvelope,\n buildEd25519Envelope,\n buildEip191EnvelopeFromSignature,\n buildWebAuthnEnvelopeFromAssertion,\n buildJwtAppleSubEnvelopeFromTokenResponse,\n type Eip191Pubkey,\n type WebAuthnPubkey,\n type JwtAppleSubPubkey,\n} from \"@chipi-stack/backend\";\n\n/**\n * SHHH V8.4 envelope builders surfaced as a single hook for React\n * integrators. Each helper returns the `signature: felt252[]` span\n * ready to pass to `paymaster_executeSponsoredRaw.calldata`.\n *\n * Most helpers take the OE `messageHash` plus kind-specific inputs.\n * `signWithMetaMask` is the exception: the `messageHash` is already\n * baked into the user-signed payload upstream, so it takes only the\n * 65-byte `personal_sign` signature and the registered pubkey.\n *\n * The hook is intentionally a thin facade over the\n * `@chipi-stack/backend` builders: it adds semantic names that map\n * to the user-facing wallet (`signWithMetaMask` = EIP-191,\n * `signWithPhantom` = Ed25519, `signWithPasskey` = WebAuthn P-256)\n * and stable React refs, but does NOT do browser-glue (no\n * `window.ethereum`, `window.solana`, or `navigator.credentials.get`\n * calls). Integrators retain full control of the user-prompt step:\n *\n * 1. Integrator calls their wallet adapter to get the raw signature\n * (or assertion / id_token).\n * 2. Integrator passes that into the matching helper to wrap it into\n * the V2_SNIP12 envelope.\n *\n * Pair with `useGuardianRecovery` or `useThresholdSign` (B6/B7) for\n * on-chain execution flows that need the recovery/governance builders.\n */\nexport interface UseShhhSignerReturn {\n /**\n * STARK ECDSA signer (legacy CHIPI v29 keys, fastest path).\n * Pure-local: no wallet prompt.\n */\n signWithStark: (params: { privateKey: bigint | string; messageHash: bigint }) => bigint[];\n\n /**\n * Phantom-shape Ed25519 signer (Solana users importing to Starknet).\n * The 32-byte private key is the Solana keypair's secret material;\n * the public key is recovered inside the builder.\n */\n signWithPhantom: (params: { privateKey: Uint8Array; messageHash: bigint }) => Promise<bigint[]>;\n\n /**\n * MetaMask-shape EIP-191 (`personal_sign`) signer. The signature\n * MUST come from a `personal_sign` over the 32-byte big-endian\n * messageHash; the pubkey was registered at wallet creation time.\n */\n signWithMetaMask: (params: { signatureHex: string; pubkey: Eip191Pubkey }) => bigint[];\n\n /**\n * WebAuthn P-256 signer (passkey). Takes a completed\n * `navigator.credentials.get()` assertion split into its three\n * fields (authenticatorData, clientDataJSON, signature DER) plus\n * the pubkey registered at credential creation time.\n */\n signWithPasskey: (params: {\n authenticatorData: Uint8Array;\n clientDataJSON: Uint8Array;\n signatureDer: Uint8Array;\n pubkey: WebAuthnPubkey;\n messageHash: bigint;\n yParity?: 0n | 1n;\n }) => bigint[];\n\n /**\n * Apple Sign In signer (`JWT_ES256_APPLE_SUB`). Takes the\n * `id_token` from Apple's OAuth response. The nonce claim MUST\n * encode `messageHash` (see `messageHashToNonceB64url`).\n */\n signWithAppleIdToken: (params: {\n idToken: string;\n pubkey: JwtAppleSubPubkey;\n messageHash: bigint;\n }) => bigint[];\n}\n\nexport function useShhhSigner(): UseShhhSignerReturn {\n // Stable refs: the builders are pure, so memoizing once per\n // component is sufficient. Integrators can pass these into effects\n // / callbacks without retriggering on every render.\n return useMemo<UseShhhSignerReturn>(\n () => ({\n signWithStark: (params) =>\n buildStarkEnvelope({\n privateKey: params.privateKey,\n messageHash: params.messageHash,\n }),\n\n signWithPhantom: (params) =>\n buildEd25519Envelope({\n privateKey: params.privateKey,\n messageHash: params.messageHash,\n }),\n\n signWithMetaMask: (params) =>\n buildEip191EnvelopeFromSignature({\n signatureHex: params.signatureHex,\n pubkey: params.pubkey,\n }),\n\n signWithPasskey: (params) =>\n buildWebAuthnEnvelopeFromAssertion({\n authenticatorData: params.authenticatorData,\n clientDataJSON: params.clientDataJSON,\n signatureDer: params.signatureDer,\n pubkey: params.pubkey,\n messageHash: params.messageHash,\n yParity: params.yParity ?? 0n,\n }),\n\n signWithAppleIdToken: (params) =>\n buildJwtAppleSubEnvelopeFromTokenResponse({\n idToken: params.idToken,\n pubkey: params.pubkey,\n messageHash: params.messageHash,\n }),\n }),\n []\n );\n}\n","import { useMemo } from \"react\";\nimport {\n buildProposeAddOwnerCall,\n buildExecuteAddOwnerCall,\n buildProposeRemoveOwnerCall,\n buildExecuteRemoveOwnerCall,\n buildProposeRotateOwnerCall,\n buildExecuteRotateOwnerCall,\n buildProposeSetThresholdCall,\n buildExecuteSetThresholdCall,\n buildCancelPendingOpCall,\n buildInitiateRecoveryCall,\n buildCancelRecoveryCall,\n buildFinalizeRecoveryCall,\n isReadyToExecute,\n secondsUntilExecutable,\n TIMELOCK_SECONDS,\n DEFAULT_OP_EXPIRY_SECONDS,\n ROLE_OWNER,\n ROLE_GUARDIAN,\n OP_ADD_OWNER,\n OP_REMOVE_OWNER,\n OP_ROTATE_OWNER,\n OP_SET_THRESHOLD,\n type NewOwnerInput,\n} from \"@chipi-stack/backend\";\n\n// `Call` is the Starknet invoke shape `{contractAddress, entrypoint, calldata}`.\n// We derive it from the backend builder's return type so chipi-react avoids a\n// direct `starknet` import (and the peer-dep that would imply).\ntype Call = ReturnType<typeof buildProposeAddOwnerCall>;\n\n/**\n * SHHH V8.4 multi-owner governance + guardian-recovery builders\n * surfaced as a single React hook. Each helper returns a Starknet\n * `Call` object (NOT a signature envelope); callers compose those\n * calls into an OutsideExecution and submit them via the paymaster\n * adapter, signing the OE with `useShhhSigner`.\n *\n * Two top-level flows are intended:\n *\n * 1. ADD DEVICE (user has wallet access, wants a second owner)\n * a. `proposeAddOwner` (owner-signed OE)\n * b. wait 48h timelock\n * c. `executeAddOwner` (owner-signed OE, with the opId from 1a)\n *\n * 2. RECOVER VIA GUARDIAN (user lost key)\n * a. `initiateRecovery` (guardian-signed OE)\n * b. wait 7 days\n * c. `finalizeRecovery` (anyone can submit, no signature required\n * beyond Cairo-side state checks)\n *\n * Read-only timelock helpers (`isReady`, `secondsRemaining`) take a\n * `validAfter` timestamp pulled from chain state and a clock reading;\n * they don't query the chain themselves. Pair this hook with whatever\n * mechanism your app already uses for on-chain state reads\n * (`useGetWallet`, RPC, multicall, etc.).\n *\n * The full controlled-component `<Recover />` route that wires this\n * hook into a state machine + UI ships as B6.2.\n */\nexport interface UseGuardianRecoveryReturn {\n // ============================================================\n // ADD OWNER (multi-device, also reused as the second leg of\n // the guardian-recovery happy path when guardian = new device)\n // ============================================================\n buildProposeAddOwner: (args: {\n walletAddress: bigint | string;\n proposer: number;\n newOwner: NewOwnerInput;\n }) => Call;\n buildExecuteAddOwner: (args: {\n walletAddress: bigint | string;\n opId: bigint | string;\n newOwner: NewOwnerInput;\n }) => Call;\n\n // ============================================================\n // REMOVE OWNER (revoke a compromised device)\n // ============================================================\n buildProposeRemoveOwner: (args: {\n walletAddress: bigint | string;\n proposer: number;\n ownerId: number;\n }) => Call;\n buildExecuteRemoveOwner: (args: {\n walletAddress: bigint | string;\n opId: bigint | string;\n ownerId: number;\n }) => Call;\n\n // ============================================================\n // ROTATE OWNER (replace an existing owner's pubkey in-place)\n // ============================================================\n buildProposeRotateOwner: (args: {\n walletAddress: bigint | string;\n proposer: number;\n ownerId: number;\n newPubkeyBytes: bigint[];\n }) => Call;\n buildExecuteRotateOwner: (args: {\n walletAddress: bigint | string;\n opId: bigint | string;\n ownerId: number;\n newPubkeyBytes: bigint[];\n }) => Call;\n\n // ============================================================\n // SET THRESHOLD (change N for N-of-M)\n // ============================================================\n buildProposeSetThreshold: (args: {\n walletAddress: bigint | string;\n proposer: number;\n newThreshold: number;\n }) => Call;\n buildExecuteSetThreshold: (args: {\n walletAddress: bigint | string;\n opId: bigint | string;\n newThreshold: number;\n }) => Call;\n\n // ============================================================\n // CANCEL pending op (mistake recovery within the timelock window)\n // ============================================================\n buildCancelPendingOp: (args: { walletAddress: bigint | string; opId: bigint | string }) => Call;\n\n // ============================================================\n // GUARDIAN RECOVERY (lost-key flow, 7d timelock)\n // ============================================================\n buildInitiateRecovery: (args: {\n walletAddress: bigint | string;\n /** owner_id of the guardian that's signing the initiation OE */\n proposer: number;\n newOwner: NewOwnerInput;\n }) => Call;\n buildCancelRecovery: (args: { walletAddress: bigint | string; ownerId: number }) => Call;\n buildFinalizeRecovery: (args: {\n walletAddress: bigint | string;\n newOwner: NewOwnerInput;\n }) => Call;\n\n // ============================================================\n // TIMELOCK STATE HELPERS (compute \"ready / remaining\" from a\n // chain-read `valid_after` timestamp)\n // ============================================================\n isReady: (validAfterSecs: number | bigint, nowSecs?: number) => boolean;\n secondsRemaining: (validAfterSecs: number | bigint, nowSecs?: number) => number;\n\n // ============================================================\n // CONSTANTS (re-exported for UI display + opTag matching)\n // ============================================================\n TIMELOCK_SECONDS: typeof TIMELOCK_SECONDS;\n DEFAULT_OP_EXPIRY_SECONDS: typeof DEFAULT_OP_EXPIRY_SECONDS;\n ROLE_OWNER: typeof ROLE_OWNER;\n ROLE_GUARDIAN: typeof ROLE_GUARDIAN;\n OP_ADD_OWNER: typeof OP_ADD_OWNER;\n OP_REMOVE_OWNER: typeof OP_REMOVE_OWNER;\n OP_ROTATE_OWNER: typeof OP_ROTATE_OWNER;\n OP_SET_THRESHOLD: typeof OP_SET_THRESHOLD;\n}\n\nexport function useGuardianRecovery(): UseGuardianRecoveryReturn {\n return useMemo<UseGuardianRecoveryReturn>(\n () => ({\n buildProposeAddOwner: (args) => buildProposeAddOwnerCall(args),\n buildExecuteAddOwner: (args) => buildExecuteAddOwnerCall(args),\n buildProposeRemoveOwner: (args) => buildProposeRemoveOwnerCall(args),\n buildExecuteRemoveOwner: (args) => buildExecuteRemoveOwnerCall(args),\n buildProposeRotateOwner: (args) => buildProposeRotateOwnerCall(args),\n buildExecuteRotateOwner: (args) => buildExecuteRotateOwnerCall(args),\n buildProposeSetThreshold: (args) => buildProposeSetThresholdCall(args),\n buildExecuteSetThreshold: (args) => buildExecuteSetThresholdCall(args),\n buildCancelPendingOp: (args) => buildCancelPendingOpCall(args),\n buildInitiateRecovery: (args) => buildInitiateRecoveryCall(args),\n buildCancelRecovery: (args) => buildCancelRecoveryCall(args),\n buildFinalizeRecovery: (args) => buildFinalizeRecoveryCall(args),\n\n isReady: (validAfterSecs, nowSecs) =>\n isReadyToExecute(validAfterSecs, nowSecs ?? Math.floor(Date.now() / 1000)),\n secondsRemaining: (validAfterSecs, nowSecs) =>\n secondsUntilExecutable(validAfterSecs, nowSecs ?? Math.floor(Date.now() / 1000)),\n\n TIMELOCK_SECONDS,\n DEFAULT_OP_EXPIRY_SECONDS,\n ROLE_OWNER,\n ROLE_GUARDIAN,\n OP_ADD_OWNER,\n OP_REMOVE_OWNER,\n OP_ROTATE_OWNER,\n OP_SET_THRESHOLD,\n }),\n []\n );\n}\n","import { useCallback, useMemo, useRef, useState } from \"react\";\nimport {\n buildThresholdEnvelope,\n parseThresholdEnvelope,\n estimateThresholdGasOverhead,\n assertValidV2Snip12Envelope,\n MIN_THRESHOLD_OWNERS,\n type ShhhSignerKind,\n} from \"@chipi-stack/backend\";\n\n/**\n * SHHH V8.4 N-of-M threshold sign coordinator surfaced as a React\n * hook. Two complementary surfaces:\n *\n * 1. **Stateless helpers** — `assemble`, `parse`, and\n * `estimateGasOverhead` are pure facades over the matching\n * `@chipi-stack/backend` builders. Use them when you already\n * have all the inner envelopes in one render and just want to\n * ship the final V2_THRESHOLD span.\n *\n * 2. **Stateful collector** — for UI flows where N owners sign\n * asynchronously (passkey on phone → MetaMask on laptop, agent\n * auto-co-signing while a human reviews, etc.) the hook keeps\n * a queue of collected inner envelopes, exposes a \"X of N\n * signed\" state for UI display, validates each new envelope at\n * add-time (duplicate owner_id detection, structural shape),\n * and assembles the final span once the threshold is met via\n * `finalize()`.\n *\n * The collector validates each envelope inline using\n * `assertValidV2Snip12Envelope` from the backend — the same check the\n * `buildThresholdEnvelope` builder runs at assembly time. That way an\n * integrator's UI can show \"owner 3 envelope rejected: duplicate\n * owner_id\" before submitting the V2_THRESHOLD span on chain, instead\n * of after the paymaster reverts.\n *\n * Threshold governance (`propose_set_threshold` / `execute_set_threshold`)\n * lives in `useGuardianRecovery` because the multi-owner signing\n * here and the threshold-change proposals there share the same\n * Cairo SHHH wallet but are operationally separate flows.\n */\nexport interface UseThresholdSignReturn {\n // ============================================================\n // Stateless helpers — thin facades over @chipi-stack/backend\n // ============================================================\n\n /**\n * Assemble an N-of-M V2_THRESHOLD envelope from a pre-collected\n * list of inner V2_SNIP12 envelopes. Pure; no internal state used.\n * Throws on duplicate owner_id, structural mismatch, or negative\n * felts — same validation the on-chain dispatch would apply.\n */\n assemble: (args: { innerEnvelopes: bigint[][] }) => bigint[];\n\n /**\n * Inverse of `assemble`. Re-derives the constituent inner envelopes\n * from a V2_THRESHOLD span. Useful for UI flows showing \"owners X,\n * Y, Z signed\" from a stored envelope without re-walking the\n * collection state.\n */\n parse: (args: { envelope: bigint[] }) => { innerEnvelopes: bigint[][] };\n\n /**\n * Sum the per-kind paymaster gas overhead across the owners that\n * will participate. Use this to surface \"this 2-of-3 mixed-kind\n * tx will cost X l2_gas to verify\" copy in a UI.\n *\n * Per [services/gasless/signer-kinds#gas-overhead], a STARK +\n * EIP-191 pair budgets 2M + 10M = 12M l2_gas for verification on\n * top of the call's own cost.\n */\n estimateGasOverhead: (args: { owners: Array<{ signerKind: ShhhSignerKind }> }) => number;\n\n // ============================================================\n // Stateful collector — async multi-owner sign flow\n // ============================================================\n\n /**\n * Live state machine. Re-renders the consuming component when an\n * envelope is added, removed, or the collection is reset.\n */\n state: ThresholdSignState;\n\n /**\n * Add one owner's inner V2_SNIP12 envelope to the collection.\n * Validates structurally + checks duplicate owner_id against\n * already-collected envelopes.\n *\n * Returns `true` on success, `false` on rejection. On rejection\n * the failure reason lands on `state.error` for inline UI display;\n * the collection is NOT mutated. A subsequent successful add\n * clears `state.error`.\n *\n * Idempotent in the sense that a second add of an already-rejected\n * envelope produces the same error; an already-collected envelope\n * (same owner_id) is treated as a duplicate.\n */\n addEnvelope: (envelope: bigint[]) => boolean;\n\n /**\n * Drop a previously-added envelope by its owner_id. Useful when\n * an owner signs but the integrator's review UI rejects their\n * specific tx and needs to ask them to re-sign with corrected\n * payload.\n */\n removeEnvelope: (ownerId: bigint) => void;\n\n /** Clear the entire collection (cancel + restart the sign flow). */\n reset: () => void;\n\n /**\n * Assemble the final V2_THRESHOLD envelope from collected inner\n * envelopes. Throws if fewer than `threshold` have been collected\n * (with a clear error so the caller's UI knows to keep prompting).\n */\n finalize: () => bigint[];\n\n // ============================================================\n // Re-exported constants\n // ============================================================\n MIN_THRESHOLD_OWNERS: typeof MIN_THRESHOLD_OWNERS;\n}\n\nexport interface ThresholdSignState {\n /** Threshold N this flow is collecting toward. */\n threshold: number;\n /** Inner envelopes collected so far, in arrival order. */\n collected: bigint[][];\n /**\n * Owner ids that have signed, in arrival order. Pre-derived from\n * `collected` so the UI doesn't have to re-parse each envelope.\n */\n signedOwnerIds: bigint[];\n /** Has the threshold been met? `collected.length >= threshold`. */\n isReady: boolean;\n /**\n * The most recent validation error from `addEnvelope`, if any.\n * Cleared on successful add or `reset()`. Use for inline UI error\n * display (\"Owner X already signed\", \"envelope is malformed\").\n */\n error: Error | null;\n}\n\nexport interface UseThresholdSignOptions {\n /**\n * Threshold N this flow targets. Must be at least\n * `MIN_THRESHOLD_OWNERS` (2). Changes to this value after first\n * render are honored — `isReady` re-evaluates against the new N\n * without dropping already-collected envelopes (use `reset` if\n * you need to start over).\n */\n threshold: number;\n}\n\n/**\n * SHHH V8.4 threshold sign coordinator.\n *\n * @example Pure assembly (all envelopes ready in one render)\n *\n * ```tsx\n * const t = useThresholdSign({ threshold: 2 });\n * const envelope = t.assemble({\n * innerEnvelopes: [starkInner, eip191Inner],\n * });\n * await submitThroughPaymaster(envelope);\n * ```\n *\n * @example Async sign flow (owners sign one at a time)\n *\n * ```tsx\n * const t = useThresholdSign({ threshold: 2 });\n *\n * // After owner 1 signs:\n * t.addEnvelope(owner1Envelope);\n *\n * // After owner 2 signs:\n * t.addEnvelope(owner2Envelope);\n *\n * // UI shows \"Signed by: owner_id_1, owner_id_2\" via t.state.signedOwnerIds.\n * // When t.state.isReady is true, submit:\n * if (t.state.isReady) {\n * const envelope = t.finalize();\n * await submitThroughPaymaster(envelope);\n * }\n * ```\n */\nexport function useThresholdSign(opts: UseThresholdSignOptions): UseThresholdSignReturn {\n const { threshold } = opts;\n const [collected, setCollected] = useState<bigint[][]>([]);\n const [signedOwnerIds, setSignedOwnerIds] = useState<bigint[]>([]);\n const [error, setError] = useState<Error | null>(null);\n\n // Mirror of signedOwnerIds for synchronous read inside addEnvelope.\n // Without this ref, two synchronous addEnvelope(a) calls in one\n // React batch both see the SAME stale closure value of\n // signedOwnerIds — the dedup check on the second call would miss\n // the first call's addition (its setState hasn't committed yet)\n // and a duplicate would slip through. The ref is the live source\n // of truth; setState calls keep state in sync for the render-time\n // reads (`state.signedOwnerIds`).\n const signedOwnerIdsRef = useRef<bigint[]>([]);\n\n const addEnvelope = useCallback((envelope: bigint[]): boolean => {\n // Validate (structural shape + duplicate owner_id). Failure\n // surfaces via state.error, NOT via throw — React batches\n // setError + setCollected within a single render; a throw\n // partway through would abort the batch and lose the\n // setError schedule. The on-chain dispatch + the backend\n // builder would raise the same errors at assemble or execute\n // time; surfacing them here keeps the UI honest.\n let ownerId: bigint;\n try {\n ownerId = assertValidV2Snip12Envelope(envelope);\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n setError(err);\n return false;\n }\n\n // Read from the ref so synchronous-batch dedup works (see ref\n // comment above).\n if (signedOwnerIdsRef.current.some((id) => id === ownerId)) {\n const err = new Error(\n `THRESH: owner_id 0x${ownerId.toString(16)} has already signed; ` +\n \"use removeEnvelope first if you want to replace their envelope.\"\n );\n setError(err);\n return false;\n }\n\n // Validation passed — commit to the ref FIRST so a sync next-call\n // dedup sees it, then schedule the state update.\n signedOwnerIdsRef.current = [...signedOwnerIdsRef.current, ownerId];\n setCollected((prev) => [...prev, envelope]);\n setSignedOwnerIds(signedOwnerIdsRef.current);\n setError(null);\n return true;\n }, []);\n\n const removeEnvelope = useCallback((ownerId: bigint) => {\n const matchIndex = signedOwnerIdsRef.current.findIndex((id) => id === ownerId);\n if (matchIndex < 0) return;\n signedOwnerIdsRef.current = signedOwnerIdsRef.current.filter((id) => id !== ownerId);\n setCollected((prev) => prev.filter((_, i) => i !== matchIndex));\n setSignedOwnerIds(signedOwnerIdsRef.current);\n setError(null);\n }, []);\n\n const reset = useCallback(() => {\n signedOwnerIdsRef.current = [];\n setCollected([]);\n setSignedOwnerIds([]);\n setError(null);\n }, []);\n\n const finalize = useCallback((): bigint[] => {\n if (collected.length < threshold) {\n throw new Error(\n `THRESH: cannot finalize — need ${threshold} envelopes, ` +\n `have ${collected.length}. Wait for more owners to sign.`\n );\n }\n // Re-validates duplicate owner_id + structural shape at assembly\n // time; the per-add validation is the fast path for UI but the\n // builder is the source of truth.\n return buildThresholdEnvelope({ innerEnvelopes: collected });\n }, [collected, threshold]);\n\n const state = useMemo<ThresholdSignState>(\n () => ({\n threshold,\n collected,\n signedOwnerIds,\n isReady: collected.length >= threshold,\n error,\n }),\n [threshold, collected, signedOwnerIds, error]\n );\n\n // Stateless helpers are stable across renders.\n const stateless = useMemo(\n () =>\n ({\n assemble: (args: { innerEnvelopes: bigint[][] }) => buildThresholdEnvelope(args),\n parse: (args: { envelope: bigint[] }) => parseThresholdEnvelope(args.envelope),\n estimateGasOverhead: (args: { owners: Array<{ signerKind: ShhhSignerKind }> }) =>\n estimateThresholdGasOverhead(args.owners),\n MIN_THRESHOLD_OWNERS,\n }) as const,\n []\n );\n\n return {\n ...stateless,\n state,\n addEnvelope,\n removeEnvelope,\n reset,\n finalize,\n };\n}\n","import React, { useCallback, useEffect, useMemo, useState } from \"react\";\nimport type { NewOwnerInput } from \"@chipi-stack/backend\";\nimport { useGuardianRecovery } from \"../hooks/useGuardianRecovery\";\n\n/**\n * SHHH V8.4 standalone recovery component (Wave B B6.2).\n *\n * Controlled + headless: chipi-react owns the phase state machine and\n * renders semantic HTML with `data-chipi-recover-*` attributes for CSS\n * targeting. The integrator brings styling and supplies the side-effect\n * callbacks (sign + execute against the paymaster). The component does\n * NOT read chain state; the caller passes `pendingOp` from their own\n * chain-read transport (multicall / view selectors / indexer).\n *\n * Two flows:\n *\n * mode=\"add-device\" propose_add_owner (48h) execute_add_owner\n * mode=\"guardian-recovery\" initiate_recovery (7d) finalize_recovery\n *\n * The wallet-connect ceremony that produces the new owner's pubkey\n * (MetaMask connect, passkey enrollment, Apple Sign In) is intentionally\n * out of scope: caller computes `newOwner` upstream and passes it in.\n */\nexport interface RecoverProps {\n /** Which flow this component renders. */\n mode: \"add-device\" | \"guardian-recovery\";\n\n /** The SHHH wallet being modified. */\n walletAddress: bigint | string;\n\n /**\n * The new owner to add (or rotate the wallet to). Caller computes\n * this upstream from whichever wallet-connect ceremony they ran.\n */\n newOwner: NewOwnerInput;\n\n /**\n * Pending op state read from chain by the caller. `null` (or omitted)\n * means no op in flight; the propose form is shown. When set, the\n * component switches to the countdown / execute panel.\n */\n pendingOp?: {\n opId: bigint | string;\n /** UNIX seconds when the op becomes executable. */\n validAfter: number | bigint;\n } | null;\n\n /**\n * Submits the propose (add-device) or initiate (guardian-recovery)\n * OE through whatever paymaster / sign path the integrator wires.\n * Returns the resulting opId + validAfter so the component can\n * transition to \"awaiting timelock\" without waiting for the next\n * chain read.\n */\n onPropose: () => Promise<{\n opId: bigint | string;\n validAfter: number | bigint;\n }>;\n\n /**\n * Submits the execute (add-device) or finalize (guardian-recovery)\n * OE once the timelock has elapsed.\n */\n onExecute: (opId: bigint | string) => Promise<void>;\n\n /**\n * Optional cancel handler. When omitted the cancel button is hidden.\n * Add-device uses `cancel_pending_op` (any owner); guardian-recovery\n * uses `cancel_recovery` (the original owner, if they resurface).\n */\n onCancel?: (opId: bigint | string) => Promise<void>;\n\n /**\n * Optional className for the root element. Compose with the\n * `data-chipi-recover-*` selectors for styling.\n */\n className?: string;\n\n /**\n * Clock override for tests / chain-time logic. Defaults to\n * `Math.floor(Date.now() / 1000)`.\n */\n nowSecs?: number;\n}\n\ntype Phase =\n | \"form-idle\"\n | \"submitting-propose\"\n | \"awaiting-timelock\"\n | \"ready-to-execute\"\n | \"submitting-execute\"\n | \"submitting-cancel\"\n | \"done\";\n\nfunction deriveStaticPhase(\n pendingOp: RecoverProps[\"pendingOp\"],\n executed: boolean,\n isReady: (after: number | bigint, now?: number) => boolean,\n nowSecs?: number\n): Phase {\n if (executed) return \"done\";\n if (!pendingOp) return \"form-idle\";\n return isReady(pendingOp.validAfter, nowSecs) ? \"ready-to-execute\" : \"awaiting-timelock\";\n}\n\nfunction shortPubkey(bytes: readonly bigint[]): string {\n if (bytes.length === 0) return \"(empty)\";\n const first = bytes[0].toString(16);\n return first.length > 12 ? `0x${first.slice(0, 8)}…${first.slice(-4)}` : `0x${first}`;\n}\n\nexport function Recover(props: RecoverProps): React.ReactElement {\n const { mode, walletAddress, newOwner, pendingOp, onCancel, className, nowSecs } = props;\n\n const recovery = useGuardianRecovery();\n const [executed, setExecuted] = useState(false);\n const [submittingAction, setSubmittingAction] = useState<\"propose\" | \"execute\" | \"cancel\" | null>(\n null\n );\n const [error, setError] = useState<Error | null>(null);\n\n // Optimistic op state captured from `onPropose`'s return value. Lets\n // the UI transition into \"awaiting-timelock\" immediately on submit\n // success without waiting for the parent to refresh `pendingOp`\n // from chain. Prop pendingOp wins if/when it lands (it's the\n // authoritative chain-read value).\n const [optimisticPendingOp, setOptimisticPendingOp] = useState<RecoverProps[\"pendingOp\"]>(null);\n // Clear the optimistic copy if the parent passes its own non-null\n // pendingOp (chain-read replaced our optimistic guess).\n useEffect(() => {\n if (pendingOp) setOptimisticPendingOp(null);\n }, [pendingOp]);\n const activePendingOp = pendingOp ?? optimisticPendingOp ?? null;\n\n // Tick once per second while a timelock is active so the countdown\n // updates without forcing the caller to re-render. Avoids ticking\n // when there's no pending op or when the lock has already elapsed.\n const [tick, setTick] = useState(0);\n useEffect(() => {\n if (!activePendingOp || executed) return;\n const ready = recovery.isReady(activePendingOp.validAfter, nowSecs);\n if (ready) return;\n const id = setInterval(() => setTick((t) => t + 1), 1000);\n return () => clearInterval(id);\n // `tick` is the dependency that re-evaluates `ready` each second.\n }, [activePendingOp, executed, recovery, nowSecs, tick]);\n\n // Resolve the visible phase from props + local state.\n // `tick` is included in deps so the countdown re-evaluates each\n // second when the live-countdown interval fires (Date.now-driven).\n const phase: Phase = useMemo(() => {\n if (submittingAction === \"propose\") return \"submitting-propose\";\n if (submittingAction === \"execute\") return \"submitting-execute\";\n if (submittingAction === \"cancel\") return \"submitting-cancel\";\n return deriveStaticPhase(activePendingOp, executed, recovery.isReady, nowSecs);\n }, [submittingAction, activePendingOp, executed, recovery, nowSecs, tick]);\n\n const secondsRemaining = useMemo(() => {\n if (!activePendingOp) return 0;\n return recovery.secondsRemaining(activePendingOp.validAfter, nowSecs);\n }, [activePendingOp, recovery, nowSecs, tick]);\n\n const handlePropose = useCallback(async () => {\n setError(null);\n setSubmittingAction(\"propose\");\n try {\n const result = await props.onPropose();\n // Drive immediate phase transition off the result. If the parent\n // also passes an updated `pendingOp` prop later, the effect\n // above clears this optimistic copy so the prop wins.\n setOptimisticPendingOp({\n opId: result.opId,\n validAfter: result.validAfter,\n });\n } catch (e) {\n setError(e instanceof Error ? e : new Error(String(e)));\n } finally {\n setSubmittingAction(null);\n }\n }, [props]);\n\n const handleExecute = useCallback(async () => {\n if (!activePendingOp) return;\n setError(null);\n setSubmittingAction(\"execute\");\n try {\n await props.onExecute(activePendingOp.opId);\n setExecuted(true);\n } catch (e) {\n setError(e instanceof Error ? e : new Error(String(e)));\n } finally {\n setSubmittingAction(null);\n }\n }, [activePendingOp, props]);\n\n const handleCancel = useCallback(async () => {\n if (!activePendingOp || !onCancel) return;\n setError(null);\n setSubmittingAction(\"cancel\");\n try {\n await onCancel(activePendingOp.opId);\n } catch (e) {\n setError(e instanceof Error ? e : new Error(String(e)));\n } finally {\n setSubmittingAction(null);\n }\n }, [activePendingOp, onCancel]);\n\n const isAddDevice = mode === \"add-device\";\n const proposeLabel = isAddDevice ? \"Propose new device\" : \"Initiate recovery\";\n const executeLabel = isAddDevice ? \"Execute add-owner\" : \"Finalize recovery\";\n const timelockDescription = isAddDevice\n ? \"48-hour timelock before this device becomes active.\"\n : \"7-day timelock before the recovered wallet becomes active.\";\n\n return (\n <div\n data-chipi-recover-root=\"\"\n data-chipi-recover-mode={mode}\n data-chipi-recover-phase={phase}\n className={className}\n >\n <header data-chipi-recover-header=\"\">\n <p data-chipi-recover-wallet-address=\"\">{String(walletAddress)}</p>\n <p data-chipi-recover-new-owner-kind=\"\">{newOwner.kind}</p>\n <p data-chipi-recover-new-owner-label=\"\">{newOwner.label}</p>\n <p data-chipi-recover-new-owner-pubkey=\"\">{shortPubkey(newOwner.pubkeyBytes)}</p>\n </header>\n\n {phase === \"form-idle\" && (\n <section data-chipi-recover-section=\"propose\">\n <p data-chipi-recover-description=\"\">{timelockDescription}</p>\n <button\n type=\"button\"\n data-chipi-recover-action=\"propose\"\n onClick={handlePropose}\n disabled={submittingAction !== null}\n >\n {proposeLabel}\n </button>\n </section>\n )}\n\n {phase === \"submitting-propose\" && (\n <section data-chipi-recover-section=\"propose\">\n <p data-chipi-recover-status=\"submitting\">Submitting…</p>\n </section>\n )}\n\n {phase === \"awaiting-timelock\" && activePendingOp && (\n <section data-chipi-recover-section=\"awaiting\">\n <p data-chipi-recover-status=\"awaiting\">{timelockDescription}</p>\n <p\n data-chipi-recover-countdown=\"\"\n data-chipi-recover-seconds-remaining={String(secondsRemaining)}\n >\n {secondsRemaining}s remaining\n </p>\n <p data-chipi-recover-op-id=\"\">{String(activePendingOp.opId)}</p>\n {onCancel && (\n <button\n type=\"button\"\n data-chipi-recover-action=\"cancel\"\n onClick={handleCancel}\n disabled={submittingAction !== null}\n >\n Cancel pending op\n </button>\n )}\n </section>\n )}\n\n {(phase === \"ready-to-execute\" || phase === \"submitting-execute\") && activePendingOp && (\n <section data-chipi-recover-section=\"execute\">\n <p data-chipi-recover-status=\"ready\">Timelock elapsed.</p>\n <button\n type=\"button\"\n data-chipi-recover-action=\"execute\"\n onClick={handleExecute}\n disabled={submittingAction !== null}\n >\n {executeLabel}\n </button>\n {onCancel && (\n <button\n type=\"button\"\n data-chipi-recover-action=\"cancel\"\n onClick={handleCancel}\n disabled={submittingAction !== null}\n >\n Cancel pending op\n </button>\n )}\n </section>\n )}\n\n {phase === \"submitting-cancel\" && (\n <section data-chipi-recover-section=\"cancel\">\n <p data-chipi-recover-status=\"submitting\">Cancelling…</p>\n </section>\n )}\n\n {phase === \"done\" && (\n <section data-chipi-recover-section=\"done\">\n <p data-chipi-recover-status=\"done\">\n {isAddDevice ? \"New device added.\" : \"Wallet recovered.\"}\n </p>\n </section>\n )}\n\n {error && (\n <p data-chipi-recover-error=\"\" role=\"alert\">\n {error.message}\n </p>\n )}\n </div>\n );\n}\n"]}