@unifold/headless-react 0.1.70-beta.1

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.
package/dist/index.js ADDED
@@ -0,0 +1,420 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ActionType: () => import_core8.ActionType,
24
+ DepositSession: () => import_core8.DepositSession,
25
+ DepositSessionEventType: () => import_core8.DepositSessionEventType,
26
+ DepositSessionWaitError: () => import_core8.DepositSessionWaitError,
27
+ ExecutionStatus: () => import_core8.ExecutionStatus,
28
+ UnifoldClient: () => import_core8.UnifoldClient,
29
+ UnifoldProvider: () => import_react_provider8.UnifoldProvider,
30
+ createUnifoldClient: () => import_core8.createUnifoldClient,
31
+ useAddressValidation: () => useAddressValidation,
32
+ useAllowedCountry: () => useAllowedCountry,
33
+ useDeposit: () => useDeposit,
34
+ useDepositAddresses: () => useDepositAddresses,
35
+ useExecutions: () => useExecutions,
36
+ useSupportedDepositTokens: () => useSupportedDepositTokens,
37
+ useUnifold: () => import_react_provider8.useUnifold,
38
+ useUnifoldClient: () => useUnifoldClient
39
+ });
40
+ module.exports = __toCommonJS(index_exports);
41
+ var import_react_provider8 = require("@unifold/react-provider");
42
+
43
+ // src/use-unifold-client.ts
44
+ var import_react = require("react");
45
+ var import_core = require("@unifold/core");
46
+ var import_react_provider = require("@unifold/react-provider");
47
+ function useUnifoldClient() {
48
+ const { publishableKey } = (0, import_react_provider.useUnifold)();
49
+ return (0, import_react.useMemo)(
50
+ () => publishableKey ? (0, import_core.createUnifoldClient)({ publishableKey }) : null,
51
+ [publishableKey]
52
+ );
53
+ }
54
+
55
+ // src/use-deposit.ts
56
+ var import_react2 = require("react");
57
+ var import_core2 = require("@unifold/core");
58
+ var import_react_provider2 = require("@unifold/react-provider");
59
+ var IDLE_SNAPSHOT = {
60
+ status: "idle",
61
+ addresses: [],
62
+ executions: [],
63
+ latestExecution: null,
64
+ isCheckingDeposit: false,
65
+ error: null
66
+ };
67
+ function useDeposit(options) {
68
+ const { publishableKey } = (0, import_react_provider2.useUnifold)();
69
+ const {
70
+ externalUserId,
71
+ destination,
72
+ confirmationMode = "auto",
73
+ method,
74
+ autoStart = true
75
+ } = options;
76
+ const callbacksRef = (0, import_react2.useRef)(options);
77
+ (0, import_react2.useEffect)(() => {
78
+ callbacksRef.current = options;
79
+ });
80
+ const [session, setSession] = (0, import_react2.useState)(null);
81
+ const sessionKey = [
82
+ publishableKey,
83
+ externalUserId ?? "",
84
+ destination.chainType,
85
+ destination.chainId,
86
+ destination.tokenAddress,
87
+ destination.recipientAddress,
88
+ JSON.stringify(destination.contractCalls ?? null),
89
+ confirmationMode,
90
+ method ?? ""
91
+ ].join("|");
92
+ (0, import_react2.useEffect)(() => {
93
+ if (!publishableKey || !externalUserId) {
94
+ setSession(null);
95
+ return;
96
+ }
97
+ const nextSession = new import_core2.DepositSession({
98
+ publishableKey,
99
+ externalUserId,
100
+ destination,
101
+ confirmationMode,
102
+ method
103
+ });
104
+ let previousStatus = nextSession.getSnapshot().status;
105
+ const offEvents = nextSession.on("*", (event) => {
106
+ const callbacks = callbacksRef.current;
107
+ callbacks.onEvent?.(event);
108
+ switch (event.type) {
109
+ case import_core2.DepositSessionEventType.ADDRESSES_CREATED:
110
+ callbacks.onAddressesReady?.(event.data.object.addresses);
111
+ break;
112
+ case import_core2.DepositSessionEventType.EXECUTION_DETECTED:
113
+ callbacks.onExecutionDetected?.(event.data.object);
114
+ break;
115
+ case import_core2.DepositSessionEventType.EXECUTION_UPDATED:
116
+ callbacks.onExecutionUpdated?.(event.data.object);
117
+ break;
118
+ case import_core2.DepositSessionEventType.EXECUTION_SUCCEEDED:
119
+ callbacks.onSuccess?.(event.data.object);
120
+ break;
121
+ case import_core2.DepositSessionEventType.EXECUTION_FAILED:
122
+ callbacks.onError?.({
123
+ code: "DEPOSIT_FAILED",
124
+ message: "Deposit failed",
125
+ fatal: false,
126
+ cause: event.data.object
127
+ });
128
+ break;
129
+ case import_core2.DepositSessionEventType.SESSION_ERRORED:
130
+ callbacks.onError?.({
131
+ code: event.data.object.code,
132
+ message: event.data.object.message,
133
+ fatal: event.data.object.fatal
134
+ });
135
+ break;
136
+ }
137
+ });
138
+ const offStatus = nextSession.subscribe(() => {
139
+ const status = nextSession.getSnapshot().status;
140
+ if (status !== previousStatus) {
141
+ previousStatus = status;
142
+ callbacksRef.current.onStatusChange?.(status);
143
+ }
144
+ });
145
+ setSession(nextSession);
146
+ if (autoStart) {
147
+ void nextSession.start();
148
+ }
149
+ return () => {
150
+ offEvents();
151
+ offStatus();
152
+ nextSession.destroy();
153
+ };
154
+ }, [sessionKey, autoStart]);
155
+ const subscribe = (0, import_react2.useCallback)(
156
+ (listener) => session ? session.subscribe(listener) : () => {
157
+ },
158
+ [session]
159
+ );
160
+ const getSnapshot = (0, import_react2.useCallback)(
161
+ () => session ? session.getSnapshot() : IDLE_SNAPSHOT,
162
+ [session]
163
+ );
164
+ const snapshot = (0, import_react2.useSyncExternalStore)(subscribe, getSnapshot, () => IDLE_SNAPSHOT);
165
+ const getAddress = (0, import_react2.useCallback)(
166
+ (query) => snapshot.addresses.find((a) => a.chainType === query.chainType),
167
+ [snapshot.addresses]
168
+ );
169
+ const controls = (0, import_react2.useMemo)(
170
+ () => ({
171
+ start: () => session?.start() ?? Promise.resolve(),
172
+ confirmFundsSent: () => session?.confirmFundsSent(),
173
+ stop: () => session?.stop(),
174
+ restart: async () => {
175
+ if (!session) return;
176
+ session.stop();
177
+ await session.start();
178
+ }
179
+ }),
180
+ [session]
181
+ );
182
+ return {
183
+ status: snapshot.status,
184
+ addresses: snapshot.addresses,
185
+ getAddress,
186
+ executions: snapshot.executions,
187
+ latestExecution: snapshot.latestExecution,
188
+ isCheckingDeposit: snapshot.isCheckingDeposit,
189
+ error: snapshot.error,
190
+ ...controls,
191
+ session
192
+ };
193
+ }
194
+
195
+ // src/use-deposit-addresses.ts
196
+ var import_react_query = require("@tanstack/react-query");
197
+ var import_core3 = require("@unifold/core");
198
+ var import_react_provider3 = require("@unifold/react-provider");
199
+ function useDepositAddresses(options) {
200
+ const { publishableKey } = (0, import_react_provider3.useUnifold)();
201
+ const { externalUserId, destination, actionType, enabled = true } = options;
202
+ return (0, import_react_query.useQuery)({
203
+ // Key parity with @unifold/ui-react's useDepositAddress — do not reorder.
204
+ queryKey: [
205
+ "unifold",
206
+ "depositAddress",
207
+ externalUserId,
208
+ destination?.recipientAddress ?? null,
209
+ destination?.chainType ?? null,
210
+ destination?.chainId ?? null,
211
+ destination?.tokenAddress ?? null,
212
+ actionType ?? null,
213
+ destination?.contractCalls ?? null,
214
+ publishableKey
215
+ ],
216
+ queryFn: () => (0, import_core3.createDepositAddress)(
217
+ {
218
+ external_user_id: externalUserId,
219
+ recipient_address: destination?.recipientAddress,
220
+ destination_chain_type: destination?.chainType,
221
+ destination_chain_id: destination?.chainId,
222
+ destination_token_address: destination?.tokenAddress,
223
+ action_type: actionType,
224
+ contract_calls: destination?.contractCalls
225
+ },
226
+ publishableKey
227
+ ),
228
+ select: (response) => response.data.map(import_core3.mapWalletToDepositAddress),
229
+ enabled: enabled && !!externalUserId && !!publishableKey,
230
+ staleTime: 1e3 * 60 * 60,
231
+ // 1 hour — wallets don't change once created
232
+ gcTime: 1e3 * 60 * 60 * 24,
233
+ refetchOnMount: false,
234
+ refetchOnWindowFocus: false,
235
+ retry: 3,
236
+ retryDelay: (attempt) => Math.min(1e3 * 2 ** attempt, 1e4)
237
+ });
238
+ }
239
+
240
+ // src/use-supported-deposit-tokens.ts
241
+ var import_react_query2 = require("@tanstack/react-query");
242
+ var import_core4 = require("@unifold/core");
243
+ var import_react_provider4 = require("@unifold/react-provider");
244
+ function useSupportedDepositTokens(options = {}) {
245
+ const { publishableKey } = (0, import_react_provider4.useUnifold)();
246
+ const { destination, productType, enabled = true } = options;
247
+ const apiOptions = destination || productType ? {
248
+ ...destination ? {
249
+ destination_token_address: destination.tokenAddress,
250
+ destination_chain_id: destination.chainId,
251
+ destination_chain_type: destination.chainType
252
+ } : {},
253
+ ...productType ? { product_type: productType } : {}
254
+ } : void 0;
255
+ return (0, import_react_query2.useQuery)({
256
+ // Key parity with @unifold/ui-react's useSupportedDepositTokens.
257
+ queryKey: [
258
+ "unifold",
259
+ "supportedDepositTokens",
260
+ publishableKey,
261
+ destination?.tokenAddress ?? null,
262
+ destination?.chainId ?? null,
263
+ destination?.chainType ?? null,
264
+ productType ?? null
265
+ ],
266
+ queryFn: () => (0, import_core4.getSupportedDepositTokens)(publishableKey, apiOptions),
267
+ select: (response) => response.data,
268
+ enabled: enabled && !!publishableKey,
269
+ staleTime: 1e3 * 60 * 5,
270
+ gcTime: 1e3 * 60 * 30,
271
+ refetchOnMount: false,
272
+ refetchOnWindowFocus: false
273
+ });
274
+ }
275
+
276
+ // src/use-executions.ts
277
+ var import_react_query3 = require("@tanstack/react-query");
278
+ var import_core5 = require("@unifold/core");
279
+ var import_react_provider5 = require("@unifold/react-provider");
280
+ function useExecutions(options) {
281
+ const { publishableKey } = (0, import_react_provider5.useUnifold)();
282
+ const { externalUserId, refetchInterval = false, enabled = true, actionType = import_core5.ActionType.Deposit } = options;
283
+ return (0, import_react_query3.useQuery)({
284
+ // Key parity with @unifold/ui-react's useExecutions.
285
+ queryKey: ["unifold", "executions", actionType, externalUserId, publishableKey],
286
+ queryFn: () => (0, import_core5.queryExecutions)(externalUserId, publishableKey, actionType),
287
+ select: (response) => response.data.map(import_core5.mapDirectExecution),
288
+ enabled: enabled && !!externalUserId && !!publishableKey,
289
+ refetchInterval,
290
+ staleTime: 0,
291
+ gcTime: 1e3 * 60 * 5,
292
+ refetchOnWindowFocus: false
293
+ });
294
+ }
295
+
296
+ // src/use-allowed-country.ts
297
+ var import_react_query4 = require("@tanstack/react-query");
298
+ var import_core6 = require("@unifold/core");
299
+ var import_react_provider6 = require("@unifold/react-provider");
300
+ function useAllowedCountry() {
301
+ const { publishableKey } = (0, import_react_provider6.useUnifold)();
302
+ const ipQuery = (0, import_react_query4.useQuery)({
303
+ // Key parity with @unifold/core's useUserIp.
304
+ queryKey: ["unifold", "userIpInfo"],
305
+ queryFn: async () => {
306
+ const data = await (0, import_core6.getIpAddress)();
307
+ const subdivision = data.subdivision_code || data.state || null;
308
+ return { alpha2: data.alpha2, country: data.country, subdivisionCode: subdivision };
309
+ },
310
+ refetchOnMount: false,
311
+ refetchOnReconnect: true,
312
+ refetchOnWindowFocus: false,
313
+ staleTime: 1e3 * 60 * 60,
314
+ gcTime: 1e3 * 60 * 60 * 24
315
+ });
316
+ const ip = ipQuery.data;
317
+ const configQuery = (0, import_react_query4.useQuery)({
318
+ // Key parity with @unifold/ui-react's useProjectConfig.
319
+ queryKey: ip?.alpha2 ? ["unifold", "projectConfig", publishableKey, ip.alpha2, ip.subdivisionCode ?? null] : ["unifold", "projectConfig", publishableKey],
320
+ queryFn: () => (0, import_core6.getProjectConfig)(
321
+ publishableKey,
322
+ ip?.alpha2 ? { countryCode: ip.alpha2, subdivisionCode: ip.subdivisionCode ?? void 0 } : void 0
323
+ ),
324
+ enabled: !!publishableKey && !ipQuery.isLoading,
325
+ placeholderData: import_react_query4.keepPreviousData,
326
+ staleTime: 1e3 * 60 * 30
327
+ });
328
+ const isLoading = ipQuery.isLoading || configQuery.isLoading;
329
+ const error = ipQuery.error || configQuery.error || null;
330
+ const projectConfig = configQuery.data;
331
+ let isAllowed = null;
332
+ if (ip && projectConfig) {
333
+ const blockedCodes = projectConfig.blocked_country_codes || [];
334
+ const blockedSubdivisions = projectConfig.blocked_country_subdivisions || [];
335
+ const countryUpper = ip.alpha2.toUpperCase();
336
+ const subdivisionUpper = (ip.subdivisionCode ?? "").toUpperCase();
337
+ const countryBlocked = blockedCodes.some((code) => code.toUpperCase() === countryUpper);
338
+ const subdivisionBlocked = blockedSubdivisions.some((entry) => {
339
+ if (entry.country_code.toUpperCase() !== countryUpper) return false;
340
+ return entry.subdivision_codes.some((code) => code.toUpperCase() === subdivisionUpper);
341
+ });
342
+ isAllowed = !countryBlocked && !subdivisionBlocked;
343
+ }
344
+ return {
345
+ isAllowed,
346
+ alpha2: ip?.alpha2 ?? null,
347
+ country: ip?.country ?? null,
348
+ subdivisionCode: ip?.subdivisionCode ?? null,
349
+ isLoading,
350
+ error
351
+ };
352
+ }
353
+
354
+ // src/use-address-validation.ts
355
+ var import_react_query5 = require("@tanstack/react-query");
356
+ var import_core7 = require("@unifold/core");
357
+ var import_react_provider7 = require("@unifold/react-provider");
358
+ function useAddressValidation(options) {
359
+ const { publishableKey } = (0, import_react_provider7.useUnifold)();
360
+ const { recipientAddress, destination, enabled = true } = options;
361
+ const shouldValidate = enabled && !!publishableKey && !!recipientAddress && !!destination;
362
+ const { data, isLoading, error } = (0, import_react_query5.useQuery)({
363
+ // Key parity with @unifold/ui-react's useAddressValidation.
364
+ queryKey: [
365
+ "unifold",
366
+ "addressValidation",
367
+ recipientAddress,
368
+ destination?.chainType,
369
+ destination?.chainId,
370
+ destination?.tokenAddress
371
+ ],
372
+ queryFn: () => (0, import_core7.verifyRecipientAddress)(
373
+ {
374
+ chain_type: destination.chainType,
375
+ chain_id: destination.chainId,
376
+ token_address: destination.tokenAddress,
377
+ recipient_address: recipientAddress
378
+ },
379
+ publishableKey
380
+ ),
381
+ enabled: shouldValidate,
382
+ refetchOnMount: false,
383
+ refetchOnReconnect: false,
384
+ refetchOnWindowFocus: false,
385
+ staleTime: 1e3 * 60 * 5,
386
+ gcTime: 1e3 * 60 * 30
387
+ });
388
+ if (!shouldValidate) {
389
+ return { isValid: null, failureCode: null, metadata: null, isLoading: false, error: null };
390
+ }
391
+ return {
392
+ isValid: data?.valid ?? null,
393
+ failureCode: data?.failure_code ?? null,
394
+ metadata: data?.metadata ?? null,
395
+ isLoading,
396
+ error: error ?? null
397
+ };
398
+ }
399
+
400
+ // src/index.ts
401
+ var import_core8 = require("@unifold/core");
402
+ // Annotate the CommonJS export names for ESM import in node:
403
+ 0 && (module.exports = {
404
+ ActionType,
405
+ DepositSession,
406
+ DepositSessionEventType,
407
+ DepositSessionWaitError,
408
+ ExecutionStatus,
409
+ UnifoldClient,
410
+ UnifoldProvider,
411
+ createUnifoldClient,
412
+ useAddressValidation,
413
+ useAllowedCountry,
414
+ useDeposit,
415
+ useDepositAddresses,
416
+ useExecutions,
417
+ useSupportedDepositTokens,
418
+ useUnifold,
419
+ useUnifoldClient
420
+ });