@diviswap/sdk 1.7.6

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 (66) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +510 -0
  3. package/bin/create-diviswap-app.js +25 -0
  4. package/bin/diviswap-sdk.js +4 -0
  5. package/dist/cli/index.js +1888 -0
  6. package/dist/cli/templates/nextjs-app/actions.ts.hbs +259 -0
  7. package/dist/cli/templates/nextjs-app/api-hooks.ts.hbs +439 -0
  8. package/dist/cli/templates/nextjs-app/api-route.ts.hbs +502 -0
  9. package/dist/cli/templates/nextjs-app/auth-context.tsx.hbs +59 -0
  10. package/dist/cli/templates/nextjs-app/client.ts.hbs +116 -0
  11. package/dist/cli/templates/nextjs-app/dashboard-hooks.ts.hbs +180 -0
  12. package/dist/cli/templates/nextjs-app/example-page.tsx.hbs +276 -0
  13. package/dist/cli/templates/nextjs-app/hooks.ts.hbs +252 -0
  14. package/dist/cli/templates/nextjs-app/kyc-hooks.ts.hbs +87 -0
  15. package/dist/cli/templates/nextjs-app/kyc-wizard.css.hbs +433 -0
  16. package/dist/cli/templates/nextjs-app/kyc-wizard.tsx.hbs +711 -0
  17. package/dist/cli/templates/nextjs-app/layout-wrapper.tsx.hbs +13 -0
  18. package/dist/cli/templates/nextjs-app/layout.tsx.hbs +13 -0
  19. package/dist/cli/templates/nextjs-app/middleware.ts.hbs +49 -0
  20. package/dist/cli/templates/nextjs-app/provider-wrapper.tsx.hbs +8 -0
  21. package/dist/cli/templates/nextjs-app/provider.tsx.hbs +408 -0
  22. package/dist/cli/templates/nextjs-app/setup-provider.tsx.hbs +25 -0
  23. package/dist/cli/templates/nextjs-app/types.ts.hbs +159 -0
  24. package/dist/cli/templates/react/api-client-wrapper.ts.hbs +89 -0
  25. package/dist/cli/templates/react/example.tsx.hbs +69 -0
  26. package/dist/cli/templates/react/tanstack-hooks.ts.hbs +185 -0
  27. package/dist/cli/templates/webhooks/nextjs.hbs +98 -0
  28. package/dist/index.d.mts +91 -0
  29. package/dist/index.d.ts +91 -0
  30. package/dist/index.js +2339 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/index.mjs +2313 -0
  33. package/dist/index.mjs.map +1 -0
  34. package/dist/react/index.d.mts +192 -0
  35. package/dist/react/index.d.ts +192 -0
  36. package/dist/react/index.js +1083 -0
  37. package/dist/react/index.js.map +1 -0
  38. package/dist/react/index.mjs +1064 -0
  39. package/dist/react/index.mjs.map +1 -0
  40. package/dist/wallet-BEGvzNtB.d.mts +1614 -0
  41. package/dist/wallet-BEGvzNtB.d.ts +1614 -0
  42. package/package.json +102 -0
  43. package/src/cli/templates/index.ts +65 -0
  44. package/src/cli/templates/nextjs-app/actions.ts.hbs +259 -0
  45. package/src/cli/templates/nextjs-app/api-hooks.ts.hbs +439 -0
  46. package/src/cli/templates/nextjs-app/api-route.ts.hbs +502 -0
  47. package/src/cli/templates/nextjs-app/auth-context.tsx.hbs +59 -0
  48. package/src/cli/templates/nextjs-app/client.ts.hbs +116 -0
  49. package/src/cli/templates/nextjs-app/dashboard-hooks.ts.hbs +180 -0
  50. package/src/cli/templates/nextjs-app/example-page.tsx.hbs +276 -0
  51. package/src/cli/templates/nextjs-app/hooks.ts.hbs +252 -0
  52. package/src/cli/templates/nextjs-app/kyc-hooks.ts.hbs +87 -0
  53. package/src/cli/templates/nextjs-app/kyc-wizard.css.hbs +433 -0
  54. package/src/cli/templates/nextjs-app/kyc-wizard.tsx.hbs +711 -0
  55. package/src/cli/templates/nextjs-app/layout-wrapper.tsx.hbs +13 -0
  56. package/src/cli/templates/nextjs-app/layout.tsx.hbs +13 -0
  57. package/src/cli/templates/nextjs-app/middleware.ts.hbs +49 -0
  58. package/src/cli/templates/nextjs-app/provider-wrapper.tsx.hbs +8 -0
  59. package/src/cli/templates/nextjs-app/provider.tsx.hbs +408 -0
  60. package/src/cli/templates/nextjs-app/setup-provider.tsx.hbs +25 -0
  61. package/src/cli/templates/nextjs-app/types.ts.hbs +159 -0
  62. package/src/cli/templates/react/api-client-wrapper.ts.hbs +89 -0
  63. package/src/cli/templates/react/example.tsx.hbs +69 -0
  64. package/src/cli/templates/react/tanstack-hooks.ts.hbs +185 -0
  65. package/src/cli/templates/shared/client.ts +78 -0
  66. package/src/cli/templates/webhooks/nextjs.hbs +98 -0
@@ -0,0 +1,1083 @@
1
+ 'use strict';
2
+
3
+ var React = require('react');
4
+
5
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
+
7
+ var React__default = /*#__PURE__*/_interopDefault(React);
8
+
9
+ // src/react/provider.tsx
10
+ var DiviswapContext = React.createContext(null);
11
+ function DiviswapProvider({
12
+ children
13
+ }) {
14
+ const [user, setUser] = React.useState(null);
15
+ const [loading, setLoading] = React.useState(false);
16
+ const [error, setError] = React.useState(null);
17
+ React.useEffect(() => {
18
+ checkSession();
19
+ }, []);
20
+ const checkSession = async () => {
21
+ try {
22
+ const response = await fetch("/api/diviswap?resource=session");
23
+ if (response.ok) {
24
+ const user2 = await response.json();
25
+ if (user2) {
26
+ setUser(user2);
27
+ }
28
+ }
29
+ } catch (error2) {
30
+ console.error("Session check failed:", error2);
31
+ }
32
+ };
33
+ const login = async (email, password) => {
34
+ setLoading(true);
35
+ setError(null);
36
+ try {
37
+ const response = await fetch("/api/diviswap", {
38
+ method: "POST",
39
+ headers: { "Content-Type": "application/json" },
40
+ body: JSON.stringify({ action: "login", email, password })
41
+ });
42
+ if (!response.ok) {
43
+ throw new Error("Login failed");
44
+ }
45
+ const data = await response.json();
46
+ setUser(data.user);
47
+ } catch (err) {
48
+ setError(err);
49
+ throw err;
50
+ } finally {
51
+ setLoading(false);
52
+ }
53
+ };
54
+ const logout = async () => {
55
+ setLoading(true);
56
+ try {
57
+ await fetch("/api/diviswap", {
58
+ method: "POST",
59
+ headers: { "Content-Type": "application/json" },
60
+ body: JSON.stringify({ action: "logout" })
61
+ });
62
+ setUser(null);
63
+ } catch (err) {
64
+ setError(err);
65
+ throw err;
66
+ } finally {
67
+ setLoading(false);
68
+ }
69
+ };
70
+ const register = async (data) => {
71
+ setLoading(true);
72
+ setError(null);
73
+ try {
74
+ const response = await fetch("/api/diviswap", {
75
+ method: "POST",
76
+ headers: { "Content-Type": "application/json" },
77
+ body: JSON.stringify({ action: "register", ...data })
78
+ });
79
+ if (!response.ok) {
80
+ throw new Error("Registration failed");
81
+ }
82
+ const result = await response.json();
83
+ setUser(result.user);
84
+ } catch (err) {
85
+ setError(err);
86
+ throw err;
87
+ } finally {
88
+ setLoading(false);
89
+ }
90
+ };
91
+ const createTransaction = async (data) => {
92
+ const response = await fetch("/api/diviswap", {
93
+ method: "POST",
94
+ headers: { "Content-Type": "application/json" },
95
+ body: JSON.stringify({ action: "createTransaction", ...data })
96
+ });
97
+ if (!response.ok) {
98
+ throw new Error("Transaction creation failed");
99
+ }
100
+ return response.json();
101
+ };
102
+ const getTransactions = async (filters) => {
103
+ const params = new URLSearchParams({ resource: "transactions", ...filters });
104
+ const response = await fetch(`/api/diviswap?${params}`);
105
+ if (!response.ok) {
106
+ throw new Error("Failed to fetch transactions");
107
+ }
108
+ return response.json();
109
+ };
110
+ const createPayee = async (data) => {
111
+ const response = await fetch("/api/diviswap", {
112
+ method: "POST",
113
+ headers: { "Content-Type": "application/json" },
114
+ body: JSON.stringify({ action: "createPayee", ...data })
115
+ });
116
+ if (!response.ok) {
117
+ throw new Error("Payee creation failed");
118
+ }
119
+ return response.json();
120
+ };
121
+ const getPayees = async () => {
122
+ const response = await fetch("/api/diviswap?resource=payees");
123
+ if (!response.ok) {
124
+ throw new Error("Failed to fetch payees");
125
+ }
126
+ return response.json();
127
+ };
128
+ const deletePayee = async (id) => {
129
+ const response = await fetch(`/api/diviswap?resource=payee&id=${id}`, {
130
+ method: "DELETE"
131
+ });
132
+ if (!response.ok) {
133
+ throw new Error("Failed to delete payee");
134
+ }
135
+ };
136
+ const calculateFees = async (amount) => {
137
+ const response = await fetch("/api/diviswap", {
138
+ method: "POST",
139
+ headers: { "Content-Type": "application/json" },
140
+ body: JSON.stringify({ action: "calculateFees", amount })
141
+ });
142
+ if (!response.ok) {
143
+ throw new Error("Fee calculation failed");
144
+ }
145
+ return response.json();
146
+ };
147
+ const getIntegratorFees = async () => {
148
+ const response = await fetch("/api/diviswap", {
149
+ method: "POST",
150
+ headers: { "Content-Type": "application/json" },
151
+ body: JSON.stringify({ action: "getIntegratorFees" })
152
+ });
153
+ if (!response.ok) {
154
+ throw new Error("Failed to fetch integrator fees");
155
+ }
156
+ return response.json();
157
+ };
158
+ const value = {
159
+ user,
160
+ loading,
161
+ error,
162
+ login,
163
+ logout,
164
+ register,
165
+ createTransaction,
166
+ getTransactions,
167
+ createPayee,
168
+ getPayees,
169
+ deletePayee,
170
+ calculateFees,
171
+ getIntegratorFees
172
+ };
173
+ return /* @__PURE__ */ React__default.default.createElement(DiviswapContext.Provider, { value }, children);
174
+ }
175
+ function useDiviswap() {
176
+ const context = React.useContext(DiviswapContext);
177
+ if (!context) {
178
+ throw new Error("useDiviswap must be used within a DiviswapProvider");
179
+ }
180
+ return context;
181
+ }
182
+ var LiberExProvider = DiviswapProvider;
183
+ var DiviswapContext2 = React.createContext(null);
184
+ function DiviswapFarcasterProvider({
185
+ children,
186
+ tokenStorage = "memory"
187
+ }) {
188
+ const [user, setUser] = React.useState(null);
189
+ const [loading, setLoading] = React.useState(false);
190
+ const [error, setError] = React.useState(null);
191
+ const [sessionToken, setSessionToken] = React.useState(null);
192
+ React.useEffect(() => {
193
+ if (tokenStorage === "localStorage" && typeof window !== "undefined") {
194
+ const storedToken = localStorage.getItem("diviswap_session_token");
195
+ if (storedToken) {
196
+ setSessionToken(storedToken);
197
+ checkSession(storedToken);
198
+ }
199
+ }
200
+ }, [tokenStorage]);
201
+ React.useEffect(() => {
202
+ if (tokenStorage === "localStorage" && typeof window !== "undefined") {
203
+ if (sessionToken) {
204
+ localStorage.setItem("diviswap_session_token", sessionToken);
205
+ } else {
206
+ localStorage.removeItem("diviswap_session_token");
207
+ }
208
+ }
209
+ }, [sessionToken, tokenStorage]);
210
+ const getAuthHeaders = () => {
211
+ const headers = { "Content-Type": "application/json" };
212
+ if (sessionToken) {
213
+ headers["Authorization"] = `Bearer ${sessionToken}`;
214
+ }
215
+ return headers;
216
+ };
217
+ const checkSession = async (token) => {
218
+ try {
219
+ const headers = token ? { "Authorization": `Bearer ${token}` } : {};
220
+ const response = await fetch("/api/diviswap?resource=session", { headers });
221
+ if (response.ok) {
222
+ const userData = await response.json();
223
+ if (userData) {
224
+ setUser(userData);
225
+ }
226
+ }
227
+ } catch (error2) {
228
+ console.error("Session check failed:", error2);
229
+ }
230
+ };
231
+ const login = async (email, password) => {
232
+ setLoading(true);
233
+ setError(null);
234
+ try {
235
+ const response = await fetch("/api/diviswap", {
236
+ method: "POST",
237
+ headers: { "Content-Type": "application/json" },
238
+ body: JSON.stringify({ action: "login", email, password })
239
+ });
240
+ if (!response.ok) {
241
+ throw new Error("Login failed");
242
+ }
243
+ const data = await response.json();
244
+ const token = data.sessionToken || data.accessToken || data.access_token;
245
+ if (token) {
246
+ setSessionToken(token);
247
+ }
248
+ setUser(data.user);
249
+ } catch (err) {
250
+ setError(err);
251
+ throw err;
252
+ } finally {
253
+ setLoading(false);
254
+ }
255
+ };
256
+ const logout = async () => {
257
+ setLoading(true);
258
+ try {
259
+ await fetch("/api/diviswap", {
260
+ method: "POST",
261
+ headers: getAuthHeaders(),
262
+ body: JSON.stringify({ action: "logout", sessionToken })
263
+ });
264
+ setUser(null);
265
+ setSessionToken(null);
266
+ } catch (err) {
267
+ setError(err);
268
+ throw err;
269
+ } finally {
270
+ setLoading(false);
271
+ }
272
+ };
273
+ const register = async (data) => {
274
+ setLoading(true);
275
+ setError(null);
276
+ try {
277
+ const response = await fetch("/api/diviswap", {
278
+ method: "POST",
279
+ headers: { "Content-Type": "application/json" },
280
+ body: JSON.stringify({ action: "register", ...data })
281
+ });
282
+ if (!response.ok) {
283
+ throw new Error("Registration failed");
284
+ }
285
+ const result = await response.json();
286
+ const token = result.sessionToken || result.accessToken || result.access_token;
287
+ if (token) {
288
+ setSessionToken(token);
289
+ }
290
+ setUser(result.user);
291
+ } catch (err) {
292
+ setError(err);
293
+ throw err;
294
+ } finally {
295
+ setLoading(false);
296
+ }
297
+ };
298
+ const createTransaction = async (data) => {
299
+ const response = await fetch("/api/diviswap", {
300
+ method: "POST",
301
+ headers: getAuthHeaders(),
302
+ body: JSON.stringify({ action: "createTransaction", sessionToken, ...data })
303
+ });
304
+ if (!response.ok) {
305
+ throw new Error("Transaction creation failed");
306
+ }
307
+ return response.json();
308
+ };
309
+ const getTransactions = async (filters) => {
310
+ const params = new URLSearchParams({
311
+ resource: "transactions",
312
+ ...sessionToken && { sessionToken },
313
+ ...filters
314
+ });
315
+ const response = await fetch(`/api/diviswap?${params}`, {
316
+ headers: sessionToken ? { "Authorization": `Bearer ${sessionToken}` } : {}
317
+ });
318
+ if (!response.ok) {
319
+ throw new Error("Failed to fetch transactions");
320
+ }
321
+ return response.json();
322
+ };
323
+ const createPayee = async (data) => {
324
+ const response = await fetch("/api/diviswap", {
325
+ method: "POST",
326
+ headers: getAuthHeaders(),
327
+ body: JSON.stringify({ action: "createPayee", sessionToken, ...data })
328
+ });
329
+ if (!response.ok) {
330
+ throw new Error("Payee creation failed");
331
+ }
332
+ return response.json();
333
+ };
334
+ const getPayees = async () => {
335
+ const params = new URLSearchParams({ resource: "payees" });
336
+ if (sessionToken) {
337
+ params.append("sessionToken", sessionToken);
338
+ }
339
+ const response = await fetch(`/api/diviswap?${params}`, {
340
+ headers: sessionToken ? { "Authorization": `Bearer ${sessionToken}` } : {}
341
+ });
342
+ if (!response.ok) {
343
+ throw new Error("Failed to fetch payees");
344
+ }
345
+ return response.json();
346
+ };
347
+ const deletePayee = async (id) => {
348
+ const params = new URLSearchParams({
349
+ resource: "payee",
350
+ id,
351
+ ...sessionToken && { sessionToken }
352
+ });
353
+ const response = await fetch(`/api/diviswap?${params}`, {
354
+ method: "DELETE",
355
+ headers: sessionToken ? { "Authorization": `Bearer ${sessionToken}` } : {}
356
+ });
357
+ if (!response.ok) {
358
+ throw new Error("Failed to delete payee");
359
+ }
360
+ };
361
+ const calculateFees = async (amount) => {
362
+ const response = await fetch("/api/diviswap", {
363
+ method: "POST",
364
+ headers: getAuthHeaders(),
365
+ body: JSON.stringify({ action: "calculateFees", sessionToken, amount })
366
+ });
367
+ if (!response.ok) {
368
+ throw new Error("Fee calculation failed");
369
+ }
370
+ return response.json();
371
+ };
372
+ const getIntegratorFees = async () => {
373
+ const response = await fetch("/api/diviswap", {
374
+ method: "POST",
375
+ headers: getAuthHeaders(),
376
+ body: JSON.stringify({ action: "getIntegratorFees", sessionToken })
377
+ });
378
+ if (!response.ok) {
379
+ throw new Error("Failed to fetch integrator fees");
380
+ }
381
+ return response.json();
382
+ };
383
+ const value = {
384
+ user,
385
+ loading,
386
+ error,
387
+ sessionToken,
388
+ login,
389
+ logout,
390
+ register,
391
+ createTransaction,
392
+ getTransactions,
393
+ createPayee,
394
+ getPayees,
395
+ deletePayee,
396
+ calculateFees,
397
+ getIntegratorFees
398
+ };
399
+ return /* @__PURE__ */ React__default.default.createElement(DiviswapContext2.Provider, { value }, children);
400
+ }
401
+ var LiberExFarcasterProvider = DiviswapFarcasterProvider;
402
+ function useAuth() {
403
+ const { user, login, logout, register, loading, error } = useDiviswap();
404
+ return {
405
+ user,
406
+ login,
407
+ logout,
408
+ register,
409
+ loading,
410
+ error,
411
+ isAuthenticated: !!user,
412
+ isLoading: loading
413
+ };
414
+ }
415
+ function useTransactions() {
416
+ const { createTransaction, getTransactions, error } = useDiviswap();
417
+ const [transactions, setTransactions] = React.useState([]);
418
+ const [loading, setLoading] = React.useState(false);
419
+ const fetchTransactions = React.useCallback(async (filters) => {
420
+ setLoading(true);
421
+ try {
422
+ const data = await getTransactions(filters);
423
+ setTransactions(data);
424
+ return data;
425
+ } catch (err) {
426
+ console.error("Failed to fetch transactions:", err);
427
+ throw err;
428
+ } finally {
429
+ setLoading(false);
430
+ }
431
+ }, [getTransactions]);
432
+ const create = React.useCallback(async (data) => {
433
+ setLoading(true);
434
+ try {
435
+ const transaction = await createTransaction(data);
436
+ await fetchTransactions();
437
+ return transaction;
438
+ } catch (err) {
439
+ console.error("Failed to create transaction:", err);
440
+ throw err;
441
+ } finally {
442
+ setLoading(false);
443
+ }
444
+ }, [createTransaction, fetchTransactions]);
445
+ return {
446
+ transactions,
447
+ loading,
448
+ error,
449
+ fetchTransactions,
450
+ createTransaction: create,
451
+ refresh: fetchTransactions
452
+ };
453
+ }
454
+ function usePayees() {
455
+ const { createPayee, getPayees, deletePayee, error } = useDiviswap();
456
+ const [payees, setPayees] = React.useState([]);
457
+ const [loading, setLoading] = React.useState(false);
458
+ const fetchPayees = React.useCallback(async () => {
459
+ setLoading(true);
460
+ try {
461
+ const data = await getPayees();
462
+ setPayees(data);
463
+ return data;
464
+ } catch (err) {
465
+ console.error("Failed to fetch payees:", err);
466
+ throw err;
467
+ } finally {
468
+ setLoading(false);
469
+ }
470
+ }, [getPayees]);
471
+ const create = React.useCallback(async (data) => {
472
+ setLoading(true);
473
+ try {
474
+ const payee = await createPayee(data);
475
+ await fetchPayees();
476
+ return payee;
477
+ } catch (err) {
478
+ console.error("Failed to create payee:", err);
479
+ throw err;
480
+ } finally {
481
+ setLoading(false);
482
+ }
483
+ }, [createPayee, fetchPayees]);
484
+ const remove = React.useCallback(async (id) => {
485
+ setLoading(true);
486
+ try {
487
+ await deletePayee(id);
488
+ await fetchPayees();
489
+ } catch (err) {
490
+ console.error("Failed to delete payee:", err);
491
+ throw err;
492
+ } finally {
493
+ setLoading(false);
494
+ }
495
+ }, [deletePayee, fetchPayees]);
496
+ React.useEffect(() => {
497
+ fetchPayees();
498
+ }, [fetchPayees]);
499
+ return {
500
+ payees,
501
+ loading,
502
+ error,
503
+ createPayee: create,
504
+ deletePayee: remove,
505
+ refresh: fetchPayees,
506
+ defaultPayee: payees.find((p) => p.isDefault) || null
507
+ };
508
+ }
509
+ function useKYCStatus(options) {
510
+ const [kycStatus, setKycStatus] = React.useState(null);
511
+ const [loading, setLoading] = React.useState(true);
512
+ const [error, setError] = React.useState(null);
513
+ const fetchKYCStatus = React.useCallback(async () => {
514
+ try {
515
+ setLoading(true);
516
+ setError(null);
517
+ const params = new URLSearchParams({ resource: "kycStatus" });
518
+ if (options?.customerId) params.set("customerId", options.customerId);
519
+ if (options?.customerEmail) params.set("customerEmail", options.customerEmail);
520
+ const response = await fetch(`/api/diviswap?${params}`);
521
+ if (!response.ok) {
522
+ throw new Error("Failed to fetch KYC status");
523
+ }
524
+ const status = await response.json();
525
+ setKycStatus(status);
526
+ } catch (err) {
527
+ console.error("KYC status fetch error:", err);
528
+ setError(err.message || "Failed to fetch KYC status");
529
+ setKycStatus({
530
+ kycStatus: "NOT_STARTED",
531
+ kybStatus: "NOT_REQUIRED",
532
+ canTransact: false,
533
+ requiresAction: true,
534
+ verificationLevel: "none",
535
+ nextStep: "COMPLETE_KYC"
536
+ });
537
+ } finally {
538
+ setLoading(false);
539
+ }
540
+ }, [options?.customerId, options?.customerEmail]);
541
+ React.useEffect(() => {
542
+ fetchKYCStatus();
543
+ }, [fetchKYCStatus]);
544
+ const refetch = React.useCallback(() => {
545
+ fetchKYCStatus();
546
+ }, [fetchKYCStatus]);
547
+ const isKycApproved = kycStatus?.kycStatus === "APPROVED";
548
+ const isKycPending = kycStatus?.kycStatus === "PENDING";
549
+ const isKycRejected = kycStatus?.kycStatus === "REJECTED";
550
+ const needsKyc = !isKycApproved && kycStatus?.requiresAction && kycStatus?.nextStep === "COMPLETE_KYC";
551
+ return {
552
+ kycStatus,
553
+ loading,
554
+ error,
555
+ refetch,
556
+ // Helper flags
557
+ isKycApproved,
558
+ isKycPending,
559
+ isKycRejected,
560
+ needsKyc,
561
+ canTransact: kycStatus?.canTransact ?? false,
562
+ verificationLevel: kycStatus?.verificationLevel ?? "none"
563
+ };
564
+ }
565
+ function useDashboard(options) {
566
+ const [loading, setLoading] = React.useState(true);
567
+ const [transactions, setTransactions] = React.useState([]);
568
+ const [payees, setPayees] = React.useState([]);
569
+ const [stats, setStats] = React.useState({
570
+ totalVolume: 0,
571
+ pendingTransactions: 0,
572
+ completedTransactions: 0,
573
+ failedTransactions: 0
574
+ });
575
+ const [chartData, setChartData] = React.useState([]);
576
+ const loadDashboardData = React.useCallback(async () => {
577
+ try {
578
+ setLoading(true);
579
+ const txParams = new URLSearchParams({
580
+ resource: "transactions",
581
+ limit: "50"
582
+ });
583
+ const payeeParams = new URLSearchParams({ resource: "payees" });
584
+ if (options?.customerId) {
585
+ txParams.set("customerId", options.customerId);
586
+ payeeParams.set("customerId", options.customerId);
587
+ }
588
+ if (options?.customerEmail) {
589
+ txParams.set("customerEmail", options.customerEmail);
590
+ payeeParams.set("customerEmail", options.customerEmail);
591
+ }
592
+ const [txResponse, payeeResponse] = await Promise.all([
593
+ fetch(`/api/diviswap?${txParams}`),
594
+ fetch(`/api/diviswap?${payeeParams}`)
595
+ ]);
596
+ const txData = txResponse.ok ? await txResponse.json() : [];
597
+ const payeeData = payeeResponse.ok ? await payeeResponse.json() : [];
598
+ setTransactions(txData || []);
599
+ setPayees(payeeData || []);
600
+ if (txData && txData.length > 0) {
601
+ const finalTransactions = txData.filter(
602
+ (tx) => tx.tx_type === "BANK_WITHDRAWAL" || tx.tx_type === "BANK_DEPOSIT"
603
+ );
604
+ const totalVolume = finalTransactions.reduce((sum, tx) => {
605
+ const amount = tx.transaction_details?.amount || 0;
606
+ return sum + amount;
607
+ }, 0);
608
+ const pendingTransactions = finalTransactions.filter(
609
+ (tx) => tx.status === "INITIATED" || tx.status === "PROCESSING" || tx.status === "pending" || tx.status === "processing"
610
+ ).length;
611
+ const completedTransactions = finalTransactions.filter(
612
+ (tx) => tx.status === "COMPLETED" || tx.status === "completed"
613
+ ).length;
614
+ const failedTransactions = finalTransactions.filter(
615
+ (tx) => tx.status === "FAILED" || tx.status === "failed"
616
+ ).length;
617
+ setStats({
618
+ totalVolume,
619
+ pendingTransactions,
620
+ completedTransactions,
621
+ failedTransactions
622
+ });
623
+ const last7Days = Array.from({ length: 7 }, (_, i) => {
624
+ const date = /* @__PURE__ */ new Date();
625
+ date.setDate(date.getDate() - (6 - i));
626
+ return date.toISOString().split("T")[0];
627
+ });
628
+ const dailyVolumes = last7Days.map((date) => {
629
+ const dayTransactions = txData.filter(
630
+ (tx) => tx.created_at && new Date(tx.created_at).toISOString().split("T")[0] === date && (tx.tx_type === "BANK_WITHDRAWAL" || tx.tx_type === "BANK_DEPOSIT")
631
+ );
632
+ const volume = dayTransactions.reduce(
633
+ (sum, tx) => sum + (tx.transaction_details?.amount || 0),
634
+ 0
635
+ );
636
+ return {
637
+ date: new Date(date).toLocaleDateString("en-US", { month: "short", day: "numeric" }),
638
+ volume,
639
+ // Amount is already in dollars
640
+ transactions: dayTransactions.length
641
+ };
642
+ });
643
+ setChartData(dailyVolumes);
644
+ }
645
+ } catch (error) {
646
+ console.error("Error loading dashboard data:", error);
647
+ } finally {
648
+ setLoading(false);
649
+ }
650
+ }, [options?.customerId, options?.customerEmail]);
651
+ React.useEffect(() => {
652
+ loadDashboardData();
653
+ }, [loadDashboardData]);
654
+ return {
655
+ stats,
656
+ chartData,
657
+ transactions: transactions.slice(0, 5),
658
+ // Recent 5 transactions for dashboard
659
+ payees,
660
+ loading,
661
+ refresh: loadDashboardData
662
+ };
663
+ }
664
+
665
+ // src/types/addresses.ts
666
+ var CHAIN_IDS = {
667
+ // Mainnets
668
+ ethereum: 1,
669
+ optimism: 10,
670
+ base: 8453,
671
+ polygon: 137,
672
+ arbitrum: 42161,
673
+ // Testnets
674
+ sepolia: 11155111,
675
+ optimism_sepolia: 11155420,
676
+ base_sepolia: 84532,
677
+ polygon_mumbai: 80001,
678
+ arbitrum_sepolia: 421614
679
+ };
680
+
681
+ // src/integrations/wallet.ts
682
+ var _WalletTracker = class _WalletTracker {
683
+ constructor(config = {}) {
684
+ this.wallet = null;
685
+ this.diviswap = null;
686
+ this.listeners = /* @__PURE__ */ new Map();
687
+ this.config = {
688
+ trackAccountChanges: true,
689
+ trackChainChanges: true,
690
+ setAsDefault: true,
691
+ ...config
692
+ };
693
+ }
694
+ /**
695
+ * Get or create the wallet tracker instance
696
+ */
697
+ static getInstance(config) {
698
+ if (!_WalletTracker.instance) {
699
+ _WalletTracker.instance = new _WalletTracker(config);
700
+ }
701
+ return _WalletTracker.instance;
702
+ }
703
+ /**
704
+ * Initialize wallet tracking with Diviswap SDK instance
705
+ */
706
+ init(diviswap, wallet) {
707
+ this.diviswap = diviswap;
708
+ if (wallet) {
709
+ this.wallet = wallet;
710
+ } else if (typeof window !== "undefined" && window.ethereum) {
711
+ this.wallet = window.ethereum;
712
+ }
713
+ if (this.wallet && this.config.trackAccountChanges) {
714
+ this.setupAccountChangeListener();
715
+ }
716
+ if (this.wallet && this.config.trackChainChanges) {
717
+ this.setupChainChangeListener();
718
+ }
719
+ }
720
+ /**
721
+ * Connect and track a wallet
722
+ */
723
+ async connect() {
724
+ if (!this.wallet) {
725
+ throw new Error("No wallet provider available");
726
+ }
727
+ if (!this.diviswap) {
728
+ throw new Error("Diviswap SDK not initialized. Call init() first.");
729
+ }
730
+ try {
731
+ const accounts = await this.wallet.request({
732
+ method: "eth_requestAccounts"
733
+ });
734
+ const chainId = await this.wallet.request({
735
+ method: "eth_chainId"
736
+ });
737
+ const numericChainId = parseInt(chainId, 16);
738
+ const connections = [];
739
+ for (const account of accounts) {
740
+ const connection = {
741
+ address: account,
742
+ chainId: numericChainId,
743
+ chainName: this.getChainName(numericChainId)
744
+ };
745
+ await this.diviswap.addresses.trackWallet(connection);
746
+ connections.push(connection);
747
+ }
748
+ return connections;
749
+ } catch (error) {
750
+ console.error("Failed to connect wallet:", error);
751
+ throw error;
752
+ }
753
+ }
754
+ /**
755
+ * Track current wallet state without requesting connection
756
+ */
757
+ async trackCurrent() {
758
+ if (!this.wallet) {
759
+ throw new Error("No wallet provider available");
760
+ }
761
+ if (!this.diviswap) {
762
+ throw new Error("Diviswap SDK not initialized. Call init() first.");
763
+ }
764
+ try {
765
+ const accounts = await this.wallet.request({
766
+ method: "eth_accounts"
767
+ });
768
+ if (accounts.length === 0) {
769
+ return [];
770
+ }
771
+ const chainId = await this.wallet.request({
772
+ method: "eth_chainId"
773
+ });
774
+ const numericChainId = parseInt(chainId, 16);
775
+ const connections = [];
776
+ for (const account of accounts) {
777
+ const connection = {
778
+ address: account,
779
+ chainId: numericChainId,
780
+ chainName: this.getChainName(numericChainId)
781
+ };
782
+ await this.diviswap.addresses.trackWallet(connection);
783
+ connections.push(connection);
784
+ }
785
+ return connections;
786
+ } catch (error) {
787
+ console.error("Failed to track current wallet state:", error);
788
+ throw error;
789
+ }
790
+ }
791
+ /**
792
+ * Setup listener for account changes
793
+ */
794
+ setupAccountChangeListener() {
795
+ if (!this.wallet?.on) return;
796
+ const handler = async (accounts) => {
797
+ if (!this.diviswap) return;
798
+ try {
799
+ const chainId = await this.wallet.request({
800
+ method: "eth_chainId"
801
+ });
802
+ const numericChainId = parseInt(chainId, 16);
803
+ for (const account of accounts) {
804
+ const connection = {
805
+ address: account,
806
+ chainId: numericChainId,
807
+ chainName: this.getChainName(numericChainId)
808
+ };
809
+ await this.diviswap.addresses.trackWallet(connection);
810
+ }
811
+ } catch (error) {
812
+ console.error("Failed to handle account change:", error);
813
+ }
814
+ };
815
+ this.wallet.on("accountsChanged", handler);
816
+ this.listeners.set("accountsChanged", handler);
817
+ }
818
+ /**
819
+ * Setup listener for chain changes
820
+ */
821
+ setupChainChangeListener() {
822
+ if (!this.wallet?.on) return;
823
+ const handler = async (chainId) => {
824
+ if (!this.diviswap) return;
825
+ try {
826
+ const accounts = await this.wallet.request({
827
+ method: "eth_accounts"
828
+ });
829
+ const numericChainId = parseInt(chainId, 16);
830
+ for (const account of accounts) {
831
+ const connection = {
832
+ address: account,
833
+ chainId: numericChainId,
834
+ chainName: this.getChainName(numericChainId)
835
+ };
836
+ await this.diviswap.addresses.trackWallet(connection);
837
+ }
838
+ } catch (error) {
839
+ console.error("Failed to handle chain change:", error);
840
+ }
841
+ };
842
+ this.wallet.on("chainChanged", handler);
843
+ this.listeners.set("chainChanged", handler);
844
+ }
845
+ /**
846
+ * Get chain name from chain ID
847
+ */
848
+ getChainName(chainId) {
849
+ const builtInChain = Object.entries(CHAIN_IDS).find(([_, id]) => id === chainId)?.[0];
850
+ if (builtInChain) return builtInChain;
851
+ return this.config.customChains?.[chainId];
852
+ }
853
+ /**
854
+ * Cleanup listeners
855
+ */
856
+ cleanup() {
857
+ if (this.wallet?.removeListener) {
858
+ for (const [event, handler] of this.listeners) {
859
+ this.wallet.removeListener(event, handler);
860
+ }
861
+ }
862
+ this.listeners.clear();
863
+ }
864
+ /**
865
+ * Update configuration
866
+ */
867
+ updateConfig(config) {
868
+ this.config = { ...this.config, ...config };
869
+ }
870
+ };
871
+ _WalletTracker.instance = null;
872
+ var WalletTracker = _WalletTracker;
873
+ async function connectWallet(diviswap, wallet, config) {
874
+ const tracker = WalletTracker.getInstance(config);
875
+ tracker.init(diviswap, wallet);
876
+ return tracker.connect();
877
+ }
878
+ async function trackCurrentWallet(diviswap, wallet, config) {
879
+ const tracker = WalletTracker.getInstance(config);
880
+ tracker.init(diviswap, wallet);
881
+ return tracker.trackCurrent();
882
+ }
883
+ function setupWalletTracking(diviswap, wallet, config) {
884
+ const tracker = WalletTracker.getInstance(config);
885
+ tracker.init(diviswap, wallet);
886
+ return tracker;
887
+ }
888
+
889
+ // src/react/useAddresses.ts
890
+ function useAddresses(diviswap) {
891
+ const [addresses, setAddresses] = React.useState([]);
892
+ const [loading, setLoading] = React.useState(false);
893
+ const [error, setError] = React.useState(null);
894
+ const fetchAddresses = React.useCallback(async () => {
895
+ if (!diviswap) return;
896
+ setLoading(true);
897
+ setError(null);
898
+ try {
899
+ const result = await diviswap.addresses.list();
900
+ setAddresses(result);
901
+ } catch (err) {
902
+ setError(err instanceof Error ? err : new Error("Failed to fetch addresses"));
903
+ } finally {
904
+ setLoading(false);
905
+ }
906
+ }, [diviswap]);
907
+ const createAddress = React.useCallback(async (data) => {
908
+ if (!diviswap) throw new Error("Diviswap instance not provided");
909
+ setLoading(true);
910
+ setError(null);
911
+ try {
912
+ const newAddress = await diviswap.addresses.create(data);
913
+ setAddresses((prev) => [...prev, newAddress]);
914
+ return newAddress;
915
+ } catch (err) {
916
+ const error2 = err instanceof Error ? err : new Error("Failed to create address");
917
+ setError(error2);
918
+ throw error2;
919
+ } finally {
920
+ setLoading(false);
921
+ }
922
+ }, [diviswap]);
923
+ const setDefaultAddress = React.useCallback(async (data) => {
924
+ if (!diviswap) throw new Error("Diviswap instance not provided");
925
+ setLoading(true);
926
+ setError(null);
927
+ try {
928
+ await diviswap.addresses.setDefault(data);
929
+ await fetchAddresses();
930
+ } catch (err) {
931
+ const error2 = err instanceof Error ? err : new Error("Failed to set default address");
932
+ setError(error2);
933
+ throw error2;
934
+ } finally {
935
+ setLoading(false);
936
+ }
937
+ }, [diviswap, fetchAddresses]);
938
+ const deleteAddress = React.useCallback(async (data) => {
939
+ if (!diviswap) throw new Error("Diviswap instance not provided");
940
+ setLoading(true);
941
+ setError(null);
942
+ try {
943
+ await diviswap.addresses.delete(data);
944
+ setAddresses((prev) => prev.filter(
945
+ (addr) => !(addr.chain_id === data.chain_id && addr.address.toLowerCase() === data.address.toLowerCase())
946
+ ));
947
+ } catch (err) {
948
+ const error2 = err instanceof Error ? err : new Error("Failed to delete address");
949
+ setError(error2);
950
+ throw error2;
951
+ } finally {
952
+ setLoading(false);
953
+ }
954
+ }, [diviswap]);
955
+ const getByChain = React.useCallback((chainIdOrName) => {
956
+ if (!diviswap) return [];
957
+ const chainId = typeof chainIdOrName === "string" ? diviswap.addresses.getChainId(chainIdOrName) : chainIdOrName;
958
+ return addresses.filter((addr) => addr.chain_id === chainId);
959
+ }, [addresses, diviswap]);
960
+ const getDefault = React.useCallback((chainIdOrName) => {
961
+ if (!diviswap) return null;
962
+ const chainId = typeof chainIdOrName === "string" ? diviswap.addresses.getChainId(chainIdOrName) : chainIdOrName;
963
+ return addresses.find((addr) => addr.chain_id === chainId && addr.is_default) || null;
964
+ }, [addresses, diviswap]);
965
+ React.useEffect(() => {
966
+ if (diviswap) {
967
+ fetchAddresses();
968
+ }
969
+ }, [diviswap, fetchAddresses]);
970
+ return {
971
+ addresses,
972
+ loading,
973
+ error,
974
+ fetchAddresses,
975
+ createAddress,
976
+ setDefaultAddress,
977
+ deleteAddress,
978
+ getByChain,
979
+ getDefault
980
+ };
981
+ }
982
+ function useWalletConnection(diviswap, config) {
983
+ const [connections, setConnections] = React.useState([]);
984
+ const [isConnecting, setIsConnecting] = React.useState(false);
985
+ const [isTracking, setIsTracking] = React.useState(false);
986
+ const [error, setError] = React.useState(null);
987
+ const connect = React.useCallback(async (wallet) => {
988
+ if (!diviswap) throw new Error("Diviswap instance not provided");
989
+ setIsConnecting(true);
990
+ setError(null);
991
+ try {
992
+ const result = await connectWallet(diviswap, wallet, config);
993
+ setConnections(result);
994
+ return result;
995
+ } catch (err) {
996
+ const error2 = err instanceof Error ? err : new Error("Failed to connect wallet");
997
+ setError(error2);
998
+ throw error2;
999
+ } finally {
1000
+ setIsConnecting(false);
1001
+ }
1002
+ }, [diviswap, config]);
1003
+ const trackCurrent = React.useCallback(async (wallet) => {
1004
+ if (!diviswap) throw new Error("Diviswap instance not provided");
1005
+ setIsTracking(true);
1006
+ setError(null);
1007
+ try {
1008
+ const result = await trackCurrentWallet(diviswap, wallet, config);
1009
+ setConnections(result);
1010
+ return result;
1011
+ } catch (err) {
1012
+ const error2 = err instanceof Error ? err : new Error("Failed to track current wallet");
1013
+ setError(error2);
1014
+ throw error2;
1015
+ } finally {
1016
+ setIsTracking(false);
1017
+ }
1018
+ }, [diviswap, config]);
1019
+ const setupTracking = React.useCallback((wallet) => {
1020
+ if (!diviswap) throw new Error("Diviswap instance not provided");
1021
+ try {
1022
+ const tracker = setupWalletTracking(diviswap, wallet, config);
1023
+ return tracker;
1024
+ } catch (err) {
1025
+ const error2 = err instanceof Error ? err : new Error("Failed to setup wallet tracking");
1026
+ setError(error2);
1027
+ throw error2;
1028
+ }
1029
+ }, [diviswap, config]);
1030
+ return {
1031
+ connections,
1032
+ isConnecting,
1033
+ isTracking,
1034
+ error,
1035
+ connect,
1036
+ trackCurrent,
1037
+ setupTracking
1038
+ };
1039
+ }
1040
+ function useWalletAddresses(diviswap, config) {
1041
+ const addressHook = useAddresses(diviswap);
1042
+ const walletHook = useWalletConnection(diviswap, config);
1043
+ const connectAndTrack = React.useCallback(async (wallet) => {
1044
+ const connections = await walletHook.connect(wallet);
1045
+ await addressHook.fetchAddresses();
1046
+ return connections;
1047
+ }, [walletHook.connect, addressHook.fetchAddresses]);
1048
+ const trackCurrentAndRefresh = React.useCallback(async (wallet) => {
1049
+ const connections = await walletHook.trackCurrent(wallet);
1050
+ await addressHook.fetchAddresses();
1051
+ return connections;
1052
+ }, [walletHook.trackCurrent, addressHook.fetchAddresses]);
1053
+ return {
1054
+ // Address management
1055
+ ...addressHook,
1056
+ // Wallet connection
1057
+ connections: walletHook.connections,
1058
+ isConnecting: walletHook.isConnecting,
1059
+ isTracking: walletHook.isTracking,
1060
+ walletError: walletHook.error,
1061
+ // Combined actions
1062
+ connectAndTrack,
1063
+ trackCurrentAndRefresh,
1064
+ setupTracking: walletHook.setupTracking
1065
+ };
1066
+ }
1067
+
1068
+ exports.DiviswapFarcasterProvider = DiviswapFarcasterProvider;
1069
+ exports.DiviswapProvider = DiviswapProvider;
1070
+ exports.LiberExFarcasterProvider = LiberExFarcasterProvider;
1071
+ exports.LiberExProvider = LiberExProvider;
1072
+ exports.useAddresses = useAddresses;
1073
+ exports.useAuth = useAuth;
1074
+ exports.useDashboard = useDashboard;
1075
+ exports.useDiviswap = useDiviswap;
1076
+ exports.useKYCStatus = useKYCStatus;
1077
+ exports.useLiberEx = useDiviswap;
1078
+ exports.usePayees = usePayees;
1079
+ exports.useTransactions = useTransactions;
1080
+ exports.useWalletAddresses = useWalletAddresses;
1081
+ exports.useWalletConnection = useWalletConnection;
1082
+ //# sourceMappingURL=index.js.map
1083
+ //# sourceMappingURL=index.js.map