@phantom/react-native-sdk 0.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,479 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ AddressType: () => import_client.AddressType,
34
+ NetworkId: () => import_client.NetworkId,
35
+ PhantomProvider: () => PhantomProvider,
36
+ useAccounts: () => useAccounts,
37
+ useConnect: () => useConnect,
38
+ useDisconnect: () => useDisconnect,
39
+ usePhantom: () => usePhantom,
40
+ useSignAndSendTransaction: () => useSignAndSendTransaction,
41
+ useSignMessage: () => useSignMessage
42
+ });
43
+ module.exports = __toCommonJS(src_exports);
44
+
45
+ // src/PhantomProvider.tsx
46
+ var import_react = require("react");
47
+ var import_embedded_provider_core = require("@phantom/embedded-provider-core");
48
+
49
+ // src/providers/embedded/storage.ts
50
+ var SecureStore = __toESM(require("expo-secure-store"));
51
+ var ExpoSecureStorage = class {
52
+ constructor(requireAuth = false) {
53
+ this.sessionKey = "phantom_session";
54
+ this.requireAuth = requireAuth;
55
+ }
56
+ async saveSession(session) {
57
+ try {
58
+ await SecureStore.setItemAsync(this.sessionKey, JSON.stringify(session), {
59
+ requireAuthentication: this.requireAuth,
60
+ keychainAccessible: SecureStore.WHEN_UNLOCKED_THIS_DEVICE_ONLY
61
+ });
62
+ } catch (error) {
63
+ console.error("[ExpoSecureStorage] Failed to save session", { error: error.message });
64
+ throw new Error(`Failed to save session: ${error.message}`);
65
+ }
66
+ }
67
+ async getSession() {
68
+ try {
69
+ const sessionData = await SecureStore.getItemAsync(this.sessionKey, {
70
+ requireAuthentication: this.requireAuth
71
+ });
72
+ if (!sessionData) {
73
+ return null;
74
+ }
75
+ return JSON.parse(sessionData);
76
+ } catch (error) {
77
+ console.error("[ExpoSecureStorage] Failed to load session", { error: error.message });
78
+ return null;
79
+ }
80
+ }
81
+ async clearSession() {
82
+ try {
83
+ await SecureStore.deleteItemAsync(this.sessionKey);
84
+ } catch (error) {
85
+ console.error("[ExpoSecureStorage] Failed to clear session", { error: error.message });
86
+ }
87
+ }
88
+ async isAvailable() {
89
+ return await SecureStore.isAvailableAsync();
90
+ }
91
+ // Method to update authentication requirement
92
+ setRequireAuth(_requireAuth) {
93
+ console.warn("[ExpoSecureStorage] Cannot change requireAuth after initialization");
94
+ }
95
+ };
96
+
97
+ // src/providers/embedded/auth.ts
98
+ var WebBrowser = __toESM(require("expo-web-browser"));
99
+ var ExpoAuthProvider = class {
100
+ async authenticate(options) {
101
+ if ("jwtToken" in options) {
102
+ return;
103
+ }
104
+ const { authUrl, redirectUrl } = options;
105
+ if (!authUrl || !redirectUrl) {
106
+ throw new Error("authUrl and redirectUrl are required for web browser authentication");
107
+ }
108
+ try {
109
+ console.log("[ExpoAuthProvider] Starting authentication", {
110
+ authUrl: authUrl.substring(0, 50) + "...",
111
+ redirectUrl
112
+ });
113
+ await WebBrowser.warmUpAsync();
114
+ const result = await WebBrowser.openAuthSessionAsync(authUrl, redirectUrl, {
115
+ // Use system browser on iOS for ASWebAuthenticationSession
116
+ preferEphemeralSession: false
117
+ });
118
+ console.log("[ExpoAuthProvider] Authentication result", {
119
+ type: result.type,
120
+ url: result.type === "success" && result.url ? result.url.substring(0, 100) + "..." : void 0
121
+ });
122
+ if (result.type === "success" && result.url) {
123
+ const url = new URL(result.url);
124
+ const walletId = url.searchParams.get("walletId");
125
+ const provider = url.searchParams.get("provider");
126
+ if (!walletId) {
127
+ throw new Error("Authentication failed: no walletId in redirect URL");
128
+ }
129
+ const userInfo = {};
130
+ url.searchParams.forEach((value, key) => {
131
+ userInfo[key] = value;
132
+ });
133
+ return {
134
+ walletId,
135
+ provider: provider || void 0,
136
+ userInfo
137
+ };
138
+ } else if (result.type === "cancel") {
139
+ throw new Error("User cancelled authentication");
140
+ } else {
141
+ throw new Error("Authentication failed");
142
+ }
143
+ } catch (error) {
144
+ console.error("[ExpoAuthProvider] Authentication error", error);
145
+ throw error;
146
+ } finally {
147
+ await WebBrowser.coolDownAsync();
148
+ }
149
+ }
150
+ isAvailable() {
151
+ return Promise.resolve(true);
152
+ }
153
+ };
154
+
155
+ // src/providers/embedded/url-params.ts
156
+ var import_react_native = require("react-native");
157
+ var ExpoURLParamsAccessor = class {
158
+ constructor() {
159
+ this.listeners = /* @__PURE__ */ new Set();
160
+ this.subscription = null;
161
+ this.currentParams = {};
162
+ }
163
+ getParam(key) {
164
+ return this.currentParams[key] || null;
165
+ }
166
+ async getInitialParams() {
167
+ try {
168
+ const url = await import_react_native.Linking.getInitialURL();
169
+ if (!url) {
170
+ return null;
171
+ }
172
+ const params = this.parseURLParams(url);
173
+ this.currentParams = params;
174
+ return params;
175
+ } catch (error) {
176
+ console.error("[ExpoURLParamsAccessor] Failed to get initial URL", error);
177
+ return null;
178
+ }
179
+ }
180
+ startListening() {
181
+ if (this.subscription) {
182
+ return;
183
+ }
184
+ this.subscription = import_react_native.Linking.addEventListener("url", ({ url }) => {
185
+ const params = this.parseURLParams(url);
186
+ if (params && Object.keys(params).length > 0) {
187
+ this.currentParams = { ...this.currentParams, ...params };
188
+ this.listeners.forEach((listener) => listener(params));
189
+ }
190
+ });
191
+ }
192
+ stopListening() {
193
+ if (this.subscription) {
194
+ this.subscription.remove();
195
+ this.subscription = null;
196
+ }
197
+ }
198
+ addListener(callback) {
199
+ this.listeners.add(callback);
200
+ return () => {
201
+ this.listeners.delete(callback);
202
+ };
203
+ }
204
+ parseURLParams(url) {
205
+ try {
206
+ const parsed = new URL(url);
207
+ const params = {};
208
+ parsed.searchParams.forEach((value, key) => {
209
+ params[key] = value;
210
+ });
211
+ return params;
212
+ } catch (error) {
213
+ console.error("[ExpoURLParamsAccessor] Failed to parse URL", url, error);
214
+ return {};
215
+ }
216
+ }
217
+ dispose() {
218
+ this.stopListening();
219
+ this.listeners.clear();
220
+ }
221
+ };
222
+
223
+ // src/providers/embedded/logger.ts
224
+ var ExpoLogger = class {
225
+ constructor(enabled = false) {
226
+ this.enabled = enabled;
227
+ }
228
+ info(category, message, data) {
229
+ if (this.enabled) {
230
+ console.info(`[${category}] ${message}`, data);
231
+ }
232
+ }
233
+ warn(category, message, data) {
234
+ if (this.enabled) {
235
+ console.warn(`[${category}] ${message}`, data);
236
+ }
237
+ }
238
+ error(category, message, data) {
239
+ if (this.enabled) {
240
+ console.error(`[${category}] ${message}`, data);
241
+ }
242
+ }
243
+ log(category, message, data) {
244
+ if (this.enabled) {
245
+ console.log(`[${category}] ${message}`, data);
246
+ }
247
+ }
248
+ };
249
+
250
+ // src/PhantomProvider.tsx
251
+ var import_jsx_runtime = require("react/jsx-runtime");
252
+ var PhantomContext = (0, import_react.createContext)(void 0);
253
+ function PhantomProvider({ children, config }) {
254
+ const sdk = (0, import_react.useMemo)(() => {
255
+ const redirectUrl = config.authOptions?.redirectUrl || `${config.scheme}://phantom-auth-callback`;
256
+ const embeddedConfig = {
257
+ apiBaseUrl: config.apiBaseUrl,
258
+ organizationId: config.organizationId,
259
+ authOptions: {
260
+ ...config.authOptions,
261
+ redirectUrl
262
+ },
263
+ embeddedWalletType: config.embeddedWalletType,
264
+ addressTypes: config.addressTypes,
265
+ solanaProvider: config.solanaProvider || "web3js"
266
+ };
267
+ const storage = new ExpoSecureStorage();
268
+ const authProvider = new ExpoAuthProvider();
269
+ const urlParamsAccessor = new ExpoURLParamsAccessor();
270
+ const logger = new ExpoLogger(config.debug);
271
+ const platform = {
272
+ storage,
273
+ authProvider,
274
+ urlParamsAccessor
275
+ };
276
+ return new import_embedded_provider_core.EmbeddedProvider(embeddedConfig, platform, logger);
277
+ }, [config]);
278
+ const [isConnected, setIsConnected] = (0, import_react.useState)(false);
279
+ const [addresses, setAddresses] = (0, import_react.useState)([]);
280
+ const [walletId, setWalletId] = (0, import_react.useState)(null);
281
+ const [error, setError] = (0, import_react.useState)(null);
282
+ const updateConnectionState = (0, import_react.useCallback)(() => {
283
+ try {
284
+ const connected = sdk.isConnected();
285
+ setIsConnected(connected);
286
+ if (connected) {
287
+ const addrs = sdk.getAddresses();
288
+ setAddresses(addrs);
289
+ } else {
290
+ setAddresses([]);
291
+ setWalletId(null);
292
+ }
293
+ } catch (err) {
294
+ console.error("[PhantomProvider] Error updating connection state", err);
295
+ setError(err);
296
+ }
297
+ }, [sdk]);
298
+ (0, import_react.useEffect)(() => {
299
+ updateConnectionState();
300
+ }, [updateConnectionState]);
301
+ const value = {
302
+ sdk,
303
+ isConnected,
304
+ addresses,
305
+ walletId,
306
+ error,
307
+ updateConnectionState,
308
+ setWalletId
309
+ };
310
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PhantomContext.Provider, { value, children });
311
+ }
312
+ function usePhantom() {
313
+ const context = (0, import_react.useContext)(PhantomContext);
314
+ if (!context) {
315
+ throw new Error("usePhantom must be used within a PhantomProvider");
316
+ }
317
+ return context;
318
+ }
319
+
320
+ // src/hooks/useConnect.ts
321
+ var import_react2 = require("react");
322
+ function useConnect() {
323
+ const { sdk, updateConnectionState, setWalletId } = usePhantom();
324
+ const [isConnecting, setIsConnecting] = (0, import_react2.useState)(false);
325
+ const [error, setError] = (0, import_react2.useState)(null);
326
+ const connect = (0, import_react2.useCallback)(
327
+ async (options) => {
328
+ if (!sdk) {
329
+ throw new Error("SDK not initialized");
330
+ }
331
+ setIsConnecting(true);
332
+ setError(null);
333
+ try {
334
+ const result = await sdk.connect(options);
335
+ if (result.status === "completed") {
336
+ if (result.walletId) {
337
+ setWalletId(result.walletId);
338
+ }
339
+ updateConnectionState();
340
+ }
341
+ return result;
342
+ } catch (err) {
343
+ const error2 = err;
344
+ setError(error2);
345
+ throw error2;
346
+ } finally {
347
+ setIsConnecting(false);
348
+ }
349
+ },
350
+ [sdk, updateConnectionState, setWalletId]
351
+ );
352
+ return {
353
+ connect,
354
+ isConnecting,
355
+ error
356
+ };
357
+ }
358
+
359
+ // src/hooks/useDisconnect.ts
360
+ var import_react3 = require("react");
361
+ function useDisconnect() {
362
+ const { sdk, updateConnectionState } = usePhantom();
363
+ const [isDisconnecting, setIsDisconnecting] = (0, import_react3.useState)(false);
364
+ const [error, setError] = (0, import_react3.useState)(null);
365
+ const disconnect = (0, import_react3.useCallback)(async () => {
366
+ if (!sdk) {
367
+ throw new Error("SDK not initialized");
368
+ }
369
+ setIsDisconnecting(true);
370
+ setError(null);
371
+ try {
372
+ await sdk.disconnect();
373
+ updateConnectionState();
374
+ } catch (err) {
375
+ const error2 = err;
376
+ setError(error2);
377
+ throw error2;
378
+ } finally {
379
+ setIsDisconnecting(false);
380
+ }
381
+ }, [sdk, updateConnectionState]);
382
+ return {
383
+ disconnect,
384
+ isDisconnecting,
385
+ error
386
+ };
387
+ }
388
+
389
+ // src/hooks/useAccounts.ts
390
+ function useAccounts() {
391
+ const { addresses, isConnected, walletId, error } = usePhantom();
392
+ return {
393
+ addresses,
394
+ isConnected,
395
+ walletId,
396
+ error
397
+ };
398
+ }
399
+
400
+ // src/hooks/useSignMessage.ts
401
+ var import_react4 = require("react");
402
+ function useSignMessage() {
403
+ const { sdk } = usePhantom();
404
+ const [isSigning, setIsSigning] = (0, import_react4.useState)(false);
405
+ const [error, setError] = (0, import_react4.useState)(null);
406
+ const signMessage = (0, import_react4.useCallback)(
407
+ async (params) => {
408
+ if (!sdk) {
409
+ throw new Error("SDK not initialized");
410
+ }
411
+ setIsSigning(true);
412
+ setError(null);
413
+ try {
414
+ const signature = await sdk.signMessage(params);
415
+ return signature;
416
+ } catch (err) {
417
+ const error2 = err;
418
+ setError(error2);
419
+ throw error2;
420
+ } finally {
421
+ setIsSigning(false);
422
+ }
423
+ },
424
+ [sdk]
425
+ );
426
+ return {
427
+ signMessage,
428
+ isSigning,
429
+ error
430
+ };
431
+ }
432
+
433
+ // src/hooks/useSignAndSendTransaction.ts
434
+ var import_react5 = require("react");
435
+ function useSignAndSendTransaction() {
436
+ const { sdk } = usePhantom();
437
+ const [isSigning, setIsSigning] = (0, import_react5.useState)(false);
438
+ const [error, setError] = (0, import_react5.useState)(null);
439
+ const signAndSendTransaction = (0, import_react5.useCallback)(
440
+ async (params) => {
441
+ if (!sdk) {
442
+ throw new Error("SDK not initialized");
443
+ }
444
+ setIsSigning(true);
445
+ setError(null);
446
+ try {
447
+ const result = await sdk.signAndSendTransaction(params);
448
+ return result;
449
+ } catch (err) {
450
+ const error2 = err;
451
+ setError(error2);
452
+ throw error2;
453
+ } finally {
454
+ setIsSigning(false);
455
+ }
456
+ },
457
+ [sdk]
458
+ );
459
+ return {
460
+ signAndSendTransaction,
461
+ isSigning,
462
+ error
463
+ };
464
+ }
465
+
466
+ // src/index.ts
467
+ var import_client = require("@phantom/client");
468
+ // Annotate the CommonJS export names for ESM import in node:
469
+ 0 && (module.exports = {
470
+ AddressType,
471
+ NetworkId,
472
+ PhantomProvider,
473
+ useAccounts,
474
+ useConnect,
475
+ useDisconnect,
476
+ usePhantom,
477
+ useSignAndSendTransaction,
478
+ useSignMessage
479
+ });