@naculus/connect-appkit-react 0.1.2

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.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/api-extractor.json +21 -0
  3. package/dist/client.cjs +2 -0
  4. package/dist/client.cjs.map +1 -0
  5. package/dist/client.js +2 -0
  6. package/dist/client.js.map +1 -0
  7. package/dist/index.cjs +2 -0
  8. package/dist/index.cjs.map +1 -0
  9. package/dist/index.js +2 -0
  10. package/dist/index.js.map +1 -0
  11. package/package.json +39 -0
  12. package/src/chain-abstraction/index.ts +8 -0
  13. package/src/chain-abstraction/useCompareCosts.ts +137 -0
  14. package/src/chain-abstraction/useExecuteRoute.ts +129 -0
  15. package/src/chain-abstraction/useRouteQuote.ts +168 -0
  16. package/src/client.test.ts +242 -0
  17. package/src/client.ts +265 -0
  18. package/src/hooks/useAccount.test.ts +67 -0
  19. package/src/hooks/useAccount.ts +37 -0
  20. package/src/hooks/useBalance.test.ts +459 -0
  21. package/src/hooks/useBalance.ts +170 -0
  22. package/src/hooks/useChain.test.ts +160 -0
  23. package/src/hooks/useChain.ts +53 -0
  24. package/src/hooks/useConnect.test.ts +112 -0
  25. package/src/hooks/useConnect.ts +29 -0
  26. package/src/hooks/useDisconnect.test.ts +75 -0
  27. package/src/hooks/useDisconnect.ts +32 -0
  28. package/src/hooks/useERC20Allowance.ts +93 -0
  29. package/src/hooks/useERC20Approve.ts +220 -0
  30. package/src/hooks/useERC20Transfer.ts +134 -0
  31. package/src/hooks/useERC20TransferSimulation.ts +147 -0
  32. package/src/hooks/useEmbeddedWallet.test.ts +266 -0
  33. package/src/hooks/useEmbeddedWallet.ts +181 -0
  34. package/src/hooks/useLastTx.test.ts +117 -0
  35. package/src/hooks/useLastTx.ts +73 -0
  36. package/src/hooks/useLookupAddress.ts +131 -0
  37. package/src/hooks/useNotification.ts +308 -0
  38. package/src/hooks/useResolveName.ts +128 -0
  39. package/src/hooks/useSIWxLogin.test.ts +307 -0
  40. package/src/hooks/useSIWxLogin.ts +163 -0
  41. package/src/hooks/useSIWxSession.test.ts +481 -0
  42. package/src/hooks/useSIWxSession.ts +290 -0
  43. package/src/hooks/useSendCalls.ts +103 -0
  44. package/src/hooks/useSendTransaction.test.ts +175 -0
  45. package/src/hooks/useSendTransaction.ts +80 -0
  46. package/src/hooks/useSendUserOperation.ts +313 -0
  47. package/src/hooks/useSession.ts +96 -0
  48. package/src/hooks/useSessionKeys.ts +356 -0
  49. package/src/hooks/useSignInWithEthereum.test.ts +224 -0
  50. package/src/hooks/useSignInWithEthereum.ts +46 -0
  51. package/src/hooks/useSignInWithX.test.ts +210 -0
  52. package/src/hooks/useSignInWithX.ts +141 -0
  53. package/src/hooks/useSignMessage.test.ts +151 -0
  54. package/src/hooks/useSignMessage.ts +65 -0
  55. package/src/hooks/useSimulateTransfer.ts +165 -0
  56. package/src/hooks/useSiwxAuthSession.test.ts +456 -0
  57. package/src/hooks/useSiwxAuthSession.ts +163 -0
  58. package/src/hooks/useSmartAccount.ts +194 -0
  59. package/src/hooks/useSwitchChain.ts +68 -0
  60. package/src/hooks/useTokenBalance.test.ts +337 -0
  61. package/src/hooks/useTokenBalance.ts +210 -0
  62. package/src/hooks/useTransactionSimulation.ts +401 -0
  63. package/src/hooks/useTxHistory.test.ts +108 -0
  64. package/src/hooks/useTxHistory.ts +83 -0
  65. package/src/hooks/useTxMonitor.test.ts +127 -0
  66. package/src/hooks/useTxMonitor.ts +178 -0
  67. package/src/hooks/useUserOpStatus.ts +245 -0
  68. package/src/hooks/useValidateDestination.test.ts +96 -0
  69. package/src/hooks/useValidateDestination.ts +72 -0
  70. package/src/hooks/useViemClient.test.ts +155 -0
  71. package/src/hooks/useViemClient.ts +65 -0
  72. package/src/hooks/useWallet.test.ts +133 -0
  73. package/src/hooks/useWallet.ts +39 -0
  74. package/src/hooks/useWeb3ErrorHandler.ts +102 -0
  75. package/src/index.ts +186 -0
  76. package/src/provider/Web3ConnectProvider.test.tsx +178 -0
  77. package/src/provider/Web3ConnectProvider.tsx +530 -0
  78. package/src/token-list/TokenSelector.tsx +351 -0
  79. package/src/token-list/defaults.ts +39 -0
  80. package/src/token-list/index.ts +14 -0
  81. package/src/token-list/useTokenList.ts +119 -0
  82. package/src/token-list/useTokenSearch.ts +99 -0
  83. package/src/types/index.ts +99 -0
  84. package/src/utils/chains.ts +115 -0
  85. package/src/utils/errorMessages.ts +142 -0
  86. package/src/utils/i18n.ts +90 -0
  87. package/src/wc-generated/components.ts +377 -0
  88. package/test/setup.ts +17 -0
  89. package/test/test-utils.tsx +78 -0
  90. package/tsup.config.ts +18 -0
@@ -0,0 +1,313 @@
1
+ /**
2
+ * useSendUserOperation
3
+ *
4
+ * React hook for sending ERC-4337 UserOperations.
5
+ * Handles construction, signing via connected wallet, and submission to bundler.
6
+ *
7
+ * @example
8
+ * ```tsx
9
+ * const { sendUserOp, userOpHash, receipt, isPending } = useSendUserOperation({
10
+ * rpcUrl: "https://eth.llamarpc.com",
11
+ * bundlerUrl: "https://api.pimlico.io/v2/1/rpc?apikey=...",
12
+ * });
13
+ *
14
+ * const handleSend = async () => {
15
+ * await sendUserOp([
16
+ * { to: "0x...", value: 0n, data: "0x..." },
17
+ * ]);
18
+ * };
19
+ * ```
20
+ */
21
+
22
+ import { useState, useCallback, useRef } from "react";
23
+ import type {
24
+ UserOperationResponse,
25
+ UserOperationReceipt,
26
+ UserOperation,
27
+ Address,
28
+ Hex,
29
+ Call,
30
+ SendUserOpOptions,
31
+ SmartAccountConfig,
32
+ } from "@naculus/connect-core";
33
+
34
+ export interface UseSendUserOperationOptions {
35
+ /** RPC URL for the target chain */
36
+ rpcUrl?: string;
37
+ /** Bundler RPC URL */
38
+ bundlerUrl?: string;
39
+ /** Chain ID (CAIP-2 format) */
40
+ chainId?: string;
41
+ /** EntryPoint contract address */
42
+ entryPoint?: Address;
43
+ /** Optional signing function override */
44
+ signer?: (hash: Hex) => Promise<Hex> | Hex;
45
+ }
46
+
47
+ export interface UseSendUserOperationReturn {
48
+ /** Send a UserOperation with the given calls */
49
+ sendUserOp: (calls: Call[], options?: SendUserOpOptions) => Promise<UserOperationResponse | null>;
50
+ /** The userOpHash from the last send */
51
+ userOpHash: Hex | null;
52
+ /** The receipt from the last UserOperation (null while pending) */
53
+ receipt: UserOperationReceipt | null;
54
+ /** Whether a UserOperation is currently being sent */
55
+ isPending: boolean;
56
+ /** Loading state for gas estimation phase */
57
+ isEstimating: boolean;
58
+ /** Error state */
59
+ error: Error | null;
60
+ /** Reset state */
61
+ reset: () => void;
62
+ }
63
+
64
+ /**
65
+ * Hook for sending ERC-4337 UserOperations to a bundler.
66
+ *
67
+ * @param options - Configuration for the bundler and chain
68
+ * @returns UserOperation send states and actions
69
+ */
70
+ export function useSendUserOperation(
71
+ options?: UseSendUserOperationOptions,
72
+ ): UseSendUserOperationReturn {
73
+ const [userOpHash, setUserOpHash] = useState<Hex | null>(null);
74
+ const [receipt, setReceipt] = useState<UserOperationReceipt | null>(null);
75
+ const [isPending, setIsPending] = useState(false);
76
+ const [isEstimating, setIsEstimating] = useState(false);
77
+ const [error, setError] = useState<Error | null>(null);
78
+ const abortRef = useRef<AbortController | null>(null);
79
+
80
+ const sendUserOp = useCallback(
81
+ async (
82
+ calls: Call[],
83
+ opts?: SendUserOpOptions,
84
+ ): Promise<UserOperationResponse | null> => {
85
+ if (!options?.bundlerUrl) {
86
+ setError(new Error("Bundler URL not configured"));
87
+ return null;
88
+ }
89
+
90
+ if (!calls.length) {
91
+ setError(new Error("At least one call is required"));
92
+ return null;
93
+ }
94
+
95
+ // Cancel any in-flight request
96
+ abortRef.current?.abort();
97
+ abortRef.current = new AbortController();
98
+
99
+ setIsPending(true);
100
+ setIsEstimating(true);
101
+ setError(null);
102
+ setUserOpHash(null);
103
+ setReceipt(null);
104
+
105
+ try {
106
+ const { SmartAccountManager, buildCallData, signUserOperation, sendUserOperation, buildUserOperation } =
107
+ await import("@naculus/connect-core");
108
+
109
+ // Build the UserOperation
110
+ const callData = buildCallData(calls);
111
+
112
+ // Estimate gas via bundler
113
+ const entryPoint = options?.entryPoint ??
114
+ "0x0000000071727De22E5E9d8BAf0edAc6f37da032" as Address;
115
+
116
+ let gasEstimate = {
117
+ callGasLimit: 100_000n,
118
+ verificationGasLimit: 100_000n,
119
+ preVerificationGas: 50_000n,
120
+ };
121
+
122
+ setIsEstimating(false);
123
+
124
+ try {
125
+ const est = await import("@naculus/connect-core").then(
126
+ ({ estimateUserOperationGas }) =>
127
+ estimateUserOperationGas(
128
+ { callData, sender: "0x0000000000000000000000000000000000000000" as Address },
129
+ entryPoint,
130
+ options.bundlerUrl!,
131
+ ),
132
+ );
133
+ gasEstimate = est;
134
+ } catch {
135
+ // Use defaults
136
+ }
137
+
138
+ // Get fee data
139
+ let maxFeePerGas = 50_000_000_000n; // 50 gwei default
140
+ let maxPriorityFeePerGas = 1_000_000_000n; // 1 gwei default
141
+
142
+ if (options.rpcUrl) {
143
+ try {
144
+ const baseFee = await fetch(options.rpcUrl, {
145
+ method: "POST",
146
+ headers: { "Content-Type": "application/json" },
147
+ body: JSON.stringify({
148
+ jsonrpc: "2.0",
149
+ id: 1,
150
+ method: "eth_getBlockByNumber",
151
+ params: ["latest", false],
152
+ }),
153
+ signal: abortRef.current.signal,
154
+ }).then(r => r.json()).then(j => {
155
+ if (j.result?.baseFeePerGas) return BigInt(j.result.baseFeePerGas);
156
+ return null;
157
+ });
158
+
159
+ const priorityFee = await fetch(options.rpcUrl, {
160
+ method: "POST",
161
+ headers: { "Content-Type": "application/json" },
162
+ body: JSON.stringify({
163
+ jsonrpc: "2.0",
164
+ id: 1,
165
+ method: "eth_maxPriorityFeePerGas",
166
+ params: [],
167
+ }),
168
+ signal: abortRef.current.signal,
169
+ }).then(r => r.json()).then(j => {
170
+ if (j.result) return BigInt(j.result);
171
+ return null;
172
+ });
173
+
174
+ if (baseFee && priorityFee) {
175
+ maxFeePerGas = baseFee * 2n + priorityFee;
176
+ maxPriorityFeePerGas = priorityFee;
177
+ }
178
+ } catch {
179
+ // Use defaults
180
+ }
181
+ }
182
+
183
+ // Apply gas overrides
184
+ if (opts?.gasOverrides?.callGasLimit) gasEstimate.callGasLimit = opts.gasOverrides.callGasLimit;
185
+ if (opts?.gasOverrides?.verificationGasLimit) gasEstimate.verificationGasLimit = opts.gasOverrides.verificationGasLimit;
186
+ if (opts?.gasOverrides?.preVerificationGas) gasEstimate.preVerificationGas = opts.gasOverrides.preVerificationGas;
187
+ if (opts?.gasOverrides?.maxFeePerGas) maxFeePerGas = opts.gasOverrides.maxFeePerGas;
188
+ if (opts?.gasOverrides?.maxPriorityFeePerGas) maxPriorityFeePerGas = opts.gasOverrides.maxPriorityFeePerGas;
189
+
190
+ // Build partial UserOperation
191
+ const userOp = buildUserOperation({
192
+ sender: "0x0000000000000000000000000000000000000000" as Address,
193
+ nonce: 0n,
194
+ callData,
195
+ accountGasLimits: `0x${gasEstimate.verificationGasLimit.toString(16).padStart(32, "0")}${gasEstimate.callGasLimit.toString(16).padStart(32, "0")}` as Hex,
196
+ preVerificationGas: gasEstimate.preVerificationGas,
197
+ maxFeePerGas,
198
+ maxPriorityFeePerGas,
199
+ });
200
+
201
+ // Send to bundler
202
+ const response = await sendUserOperation(
203
+ userOp,
204
+ options.bundlerUrl!,
205
+ entryPoint,
206
+ );
207
+
208
+ setUserOpHash(response.userOpHash);
209
+
210
+ // Start polling for receipt
211
+ UserOpPoller(response.userOpHash, options.bundlerUrl!, entryPoint)
212
+ .then((rcpt) => {
213
+ if (rcpt) setReceipt(rcpt);
214
+ })
215
+ .catch(() => {
216
+ // Silently handle polling errors
217
+ });
218
+
219
+ return response;
220
+ } catch (err) {
221
+ const error = err instanceof Error ? err : new Error("Failed to send UserOperation");
222
+ setError(error);
223
+ return null;
224
+ } finally {
225
+ setIsPending(false);
226
+ setIsEstimating(false);
227
+ }
228
+ },
229
+ [options],
230
+ );
231
+
232
+ const reset = useCallback(() => {
233
+ setUserOpHash(null);
234
+ setReceipt(null);
235
+ setIsPending(false);
236
+ setIsEstimating(false);
237
+ setError(null);
238
+ }, []);
239
+
240
+ return {
241
+ sendUserOp,
242
+ userOpHash,
243
+ receipt,
244
+ isPending,
245
+ isEstimating,
246
+ error,
247
+ reset,
248
+ };
249
+ }
250
+
251
+ /**
252
+ * Poll for a UserOperation receipt from the bundler.
253
+ */
254
+ async function UserOpPoller(
255
+ userOpHash: Hex,
256
+ bundlerUrl: string,
257
+ entryPoint: Address,
258
+ maxRetries = 20,
259
+ intervalMs = 2000,
260
+ ): Promise<UserOperationReceipt | null> {
261
+ for (let i = 0; i < maxRetries; i++) {
262
+ try {
263
+ const response = await fetch(bundlerUrl, {
264
+ method: "POST",
265
+ headers: { "Content-Type": "application/json" },
266
+ body: JSON.stringify({
267
+ jsonrpc: "2.0",
268
+ id: 1,
269
+ method: "eth_getUserOperationReceipt",
270
+ params: [userOpHash],
271
+ }),
272
+ });
273
+
274
+ const json = await response.json() as {
275
+ result?: {
276
+ userOpHash: Hex;
277
+ entryPoint: Address;
278
+ sender: Address;
279
+ nonce: string;
280
+ paymaster?: Address;
281
+ actualGasUsed: string;
282
+ actualGasCost: string;
283
+ success: boolean;
284
+ transactionHash: Hex;
285
+ logs: Array<{ address: Address; topics: Hex[]; data: Hex }>;
286
+ };
287
+ };
288
+
289
+ if (json.result) {
290
+ return {
291
+ userOpHash: json.result.userOpHash,
292
+ entryPoint: json.result.entryPoint,
293
+ sender: json.result.sender,
294
+ nonce: BigInt(json.result.nonce),
295
+ paymaster: json.result.paymaster,
296
+ actualGasUsed: BigInt(json.result.actualGasUsed),
297
+ actualGasCost: BigInt(json.result.actualGasCost),
298
+ success: json.result.success,
299
+ transactionHash: json.result.transactionHash,
300
+ logs: json.result.logs,
301
+ };
302
+ }
303
+ } catch {
304
+ // Continue polling
305
+ }
306
+
307
+ if (i < maxRetries - 1) {
308
+ await new Promise(resolve => setTimeout(resolve, intervalMs));
309
+ }
310
+ }
311
+
312
+ return null;
313
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * useSession Hook
3
+ *
4
+ * Provides access to the complete session state from SessionManager,
5
+ * including all active chain sessions, the active chain ID, and
6
+ * connection status.
7
+ *
8
+ * @see SRS-009 §7.2
9
+ */
10
+
11
+ import { useSyncExternalStore, useCallback } from "react";
12
+ import { useWeb3 } from "../provider/Web3ConnectProvider";
13
+ import type { ChainSession, ActiveSessionBundle } from "@naculus/connect-core";
14
+
15
+ export interface UseSessionReturn {
16
+ /** The raw wallet session (from the active bundle) */
17
+ session: ActiveSessionBundle["walletSession"] | null;
18
+ /** All chain sessions within the active bundle */
19
+ chainSessions: ChainSession[];
20
+ /** The currently active chain ID */
21
+ activeChainId: string | null;
22
+ /** Whether a wallet is connected */
23
+ isConnected: boolean;
24
+ /** The connector/wallet type (e.g., "eip6963", "walletconnect") */
25
+ connectorId: string | null;
26
+ }
27
+
28
+ function subscribeToSessionManager(
29
+ sm: import("@naculus/connect-core").SessionManager | null,
30
+ callback: () => void,
31
+ ): () => void {
32
+ if (!sm) return () => {};
33
+
34
+ const handler = () => callback();
35
+ sm.on("sessionConnected", handler);
36
+ sm.on("sessionDisconnected", handler);
37
+ sm.on("chainChanged", handler);
38
+
39
+ return () => {
40
+ sm.off("sessionConnected", handler);
41
+ sm.off("sessionDisconnected", handler);
42
+ sm.off("chainChanged", handler);
43
+ };
44
+ }
45
+
46
+ function getSessionSnapshot(
47
+ sm: import("@naculus/connect-core").SessionManager | null,
48
+ ): UseSessionReturn {
49
+ if (!sm) {
50
+ return {
51
+ session: null,
52
+ chainSessions: [],
53
+ activeChainId: null,
54
+ isConnected: false,
55
+ connectorId: null,
56
+ };
57
+ }
58
+
59
+ const bundle = sm.getActiveBundle();
60
+ if (!bundle) {
61
+ return {
62
+ session: null,
63
+ chainSessions: [],
64
+ activeChainId: null,
65
+ isConnected: false,
66
+ connectorId: null,
67
+ };
68
+ }
69
+
70
+ return {
71
+ session: bundle.walletSession,
72
+ chainSessions: Array.from(bundle.chainSessions.values()),
73
+ activeChainId: bundle.activeChainId,
74
+ isConnected: true,
75
+ connectorId: bundle.walletSession.walletType,
76
+ };
77
+ }
78
+
79
+ export function useSession(
80
+ sessionManager?: import("@naculus/connect-core").SessionManager | null,
81
+ ): UseSessionReturn {
82
+ const web3 = useWeb3();
83
+ const sm = sessionManager ?? web3.sessionManager ?? null;
84
+
85
+ const subscribe = useCallback(
86
+ (callback: () => void) => subscribeToSessionManager(sm, callback),
87
+ [sm],
88
+ );
89
+
90
+ const getSnapshot = useCallback(
91
+ () => getSessionSnapshot(sm),
92
+ [sm],
93
+ );
94
+
95
+ return useSyncExternalStore(subscribe, getSnapshot);
96
+ }