@chipi-stack/chipi-react 11.21.0 → 12.0.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.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import React, { createContext, useContext } from 'react';
1
+ import React, { createContext, useContext, useMemo, useCallback, useState, useEffect } from 'react';
2
2
  import { QueryClient, QueryClientProvider, useMutation, useQueryClient, useQuery } from '@tanstack/react-query';
3
3
  import { ChipiSDK } from '@chipi-stack/backend';
4
4
  import { jsx } from 'react/jsx-runtime';
@@ -109,6 +109,367 @@ function useGetWallet(input) {
109
109
  fetchWallet
110
110
  };
111
111
  }
112
+ function useChipiWallet(config) {
113
+ const { chipiSDK } = useChipiContext();
114
+ const queryClient = useQueryClient();
115
+ const {
116
+ externalUserId,
117
+ getBearerToken,
118
+ defaultToken = "USDC",
119
+ enabled = true
120
+ } = config;
121
+ const isEnabled = Boolean(
122
+ enabled && externalUserId && externalUserId.trim() !== ""
123
+ );
124
+ const walletQuery = useQuery({
125
+ queryKey: ["chipi-wallet", externalUserId],
126
+ queryFn: async () => {
127
+ if (!externalUserId) return null;
128
+ const bearerToken = await getBearerToken();
129
+ if (!bearerToken) throw new Error("Bearer token is required");
130
+ return chipiSDK.getWallet({ externalUserId }, bearerToken);
131
+ },
132
+ enabled: isEnabled,
133
+ retry: (failureCount, error) => {
134
+ if (error instanceof ChipiApiError || error?.status) {
135
+ return false;
136
+ }
137
+ return failureCount < 3;
138
+ }
139
+ });
140
+ const walletPublicKey = walletQuery.data?.wallet.publicKey;
141
+ const balanceQuery = useQuery({
142
+ queryKey: ["chipi-wallet-balance", walletPublicKey, defaultToken],
143
+ queryFn: async () => {
144
+ if (!walletPublicKey) throw new Error("No wallet");
145
+ const bearerToken = await getBearerToken();
146
+ if (!bearerToken) throw new Error("Bearer token is required");
147
+ return chipiSDK.getTokenBalance(
148
+ {
149
+ chain: "STARKNET",
150
+ chainToken: defaultToken,
151
+ walletPublicKey
152
+ },
153
+ bearerToken
154
+ );
155
+ },
156
+ enabled: Boolean(walletPublicKey),
157
+ retry: (failureCount, error) => {
158
+ if (error instanceof ChipiApiError || error?.status) {
159
+ return false;
160
+ }
161
+ return failureCount < 3;
162
+ }
163
+ });
164
+ const createWalletMutation = useMutation({
165
+ mutationFn: async ({ encryptKey, walletType = "CHIPI" }) => {
166
+ if (!externalUserId) throw new Error("External user ID is required");
167
+ const bearerToken = await getBearerToken();
168
+ if (!bearerToken) throw new Error("Bearer token is required");
169
+ return chipiSDK.createWallet({
170
+ params: {
171
+ encryptKey,
172
+ externalUserId,
173
+ walletType
174
+ },
175
+ bearerToken
176
+ });
177
+ },
178
+ onSuccess: () => {
179
+ queryClient.invalidateQueries({
180
+ queryKey: ["chipi-wallet", externalUserId]
181
+ });
182
+ }
183
+ });
184
+ const wallet = useMemo(() => {
185
+ if (walletQuery.isLoading) return void 0;
186
+ if (!walletQuery.data) return null;
187
+ const data = walletQuery.data;
188
+ return {
189
+ ...data,
190
+ supportsSessionKeys: data.wallet.walletType === "CHIPI",
191
+ shortAddress: formatAddress(data.wallet.publicKey)
192
+ };
193
+ }, [walletQuery.data, walletQuery.isLoading]);
194
+ const formattedBalance = useMemo(() => {
195
+ if (!balanceQuery.data?.balance) return "0.00";
196
+ const num = Number(balanceQuery.data.balance);
197
+ return num.toLocaleString(void 0, {
198
+ minimumFractionDigits: 2,
199
+ maximumFractionDigits: defaultToken === "ETH" || defaultToken === "STRK" ? 6 : 2
200
+ });
201
+ }, [balanceQuery.data, defaultToken]);
202
+ const refetchWallet = useCallback(async () => {
203
+ await walletQuery.refetch();
204
+ }, [walletQuery]);
205
+ const refetchBalance = useCallback(async () => {
206
+ await balanceQuery.refetch();
207
+ }, [balanceQuery]);
208
+ const refetchAll = useCallback(async () => {
209
+ await Promise.all([walletQuery.refetch(), balanceQuery.refetch()]);
210
+ }, [walletQuery, balanceQuery]);
211
+ const createWallet = useCallback(
212
+ async (params) => {
213
+ return createWalletMutation.mutateAsync(params);
214
+ },
215
+ [createWalletMutation]
216
+ );
217
+ return {
218
+ // Wallet data
219
+ wallet,
220
+ hasWallet: wallet !== null && wallet !== void 0,
221
+ isLoadingWallet: walletQuery.isLoading,
222
+ walletError: walletQuery.error,
223
+ // Balance data
224
+ balance: balanceQuery.data,
225
+ formattedBalance,
226
+ isLoadingBalance: balanceQuery.isLoading,
227
+ // Create wallet
228
+ createWallet,
229
+ isCreating: createWalletMutation.isPending,
230
+ createdWallet: createWalletMutation.data,
231
+ // Actions
232
+ refetchWallet,
233
+ refetchBalance,
234
+ refetchAll
235
+ };
236
+ }
237
+ function formatAddress(address, chars = 6) {
238
+ if (!address || address.length < chars * 2) return address;
239
+ return `${address.slice(0, chars + 2)}...${address.slice(-chars)}`;
240
+ }
241
+ function useChipiSession(config) {
242
+ const { chipiSDK } = useChipiContext();
243
+ const queryClient = useQueryClient();
244
+ const {
245
+ wallet,
246
+ encryptKey,
247
+ getBearerToken,
248
+ storedSession,
249
+ onSessionCreated,
250
+ defaultDurationSeconds = 21600,
251
+ // 6 hours
252
+ defaultMaxCalls = 1e3,
253
+ autoCheckStatus = true
254
+ } = config;
255
+ const [localSession, setLocalSession] = useState(
256
+ storedSession ?? null
257
+ );
258
+ const [error, setError] = useState(null);
259
+ useEffect(() => {
260
+ if (storedSession) {
261
+ setLocalSession(storedSession);
262
+ }
263
+ }, [storedSession]);
264
+ const supportsSession = useMemo(() => {
265
+ if (!wallet) return false;
266
+ return wallet.walletType === "CHIPI";
267
+ }, [wallet]);
268
+ const sessionStatusQuery = useQuery({
269
+ queryKey: ["chipi-session-status", wallet?.publicKey, localSession?.publicKey],
270
+ queryFn: async () => {
271
+ if (!wallet?.publicKey || !localSession?.publicKey) return null;
272
+ return chipiSDK.sessions.getSessionData({
273
+ walletAddress: wallet.publicKey,
274
+ sessionPublicKey: localSession.publicKey
275
+ });
276
+ },
277
+ enabled: Boolean(
278
+ autoCheckStatus && wallet?.publicKey && localSession?.publicKey && supportsSession
279
+ ),
280
+ staleTime: 3e4
281
+ // 30 seconds
282
+ });
283
+ const sessionState = useMemo(() => {
284
+ if (!localSession) return "none";
285
+ const status = sessionStatusQuery.data;
286
+ if (status) {
287
+ if (!status.isActive) return "revoked";
288
+ if (status.validUntil * 1e3 < Date.now()) return "expired";
289
+ if (status.remainingCalls <= 0) return "expired";
290
+ return "active";
291
+ }
292
+ if (localSession.validUntil * 1e3 < Date.now()) return "expired";
293
+ return "created";
294
+ }, [localSession, sessionStatusQuery.data]);
295
+ const hasActiveSession = sessionState === "active";
296
+ const isSessionExpired = sessionState === "expired";
297
+ const remainingCalls = sessionStatusQuery.data?.remainingCalls;
298
+ const createSessionMutation = useMutation({
299
+ mutationFn: async (params = {}) => {
300
+ if (!encryptKey) throw new Error("Encryption key (PIN) is required");
301
+ if (!supportsSession) throw new Error("Wallet does not support sessions. Only CHIPI wallets support session keys.");
302
+ const sessionData = chipiSDK.sessions.createSessionKey({
303
+ encryptKey,
304
+ durationSeconds: params.durationSeconds ?? defaultDurationSeconds
305
+ });
306
+ return sessionData;
307
+ },
308
+ onSuccess: async (sessionData) => {
309
+ setLocalSession(sessionData);
310
+ setError(null);
311
+ if (onSessionCreated) {
312
+ await onSessionCreated(sessionData);
313
+ }
314
+ },
315
+ onError: (err) => {
316
+ setError(err);
317
+ }
318
+ });
319
+ const registerSessionMutation = useMutation({
320
+ mutationFn: async (sessionConfig = {}) => {
321
+ if (!wallet) throw new Error("Wallet is required");
322
+ if (!localSession) throw new Error("No session to register. Call createSession first.");
323
+ if (!encryptKey) throw new Error("Encryption key (PIN) is required");
324
+ if (!supportsSession) throw new Error("Wallet does not support sessions");
325
+ const bearerToken = await getBearerToken();
326
+ if (!bearerToken) throw new Error("Bearer token is required");
327
+ const txHash = await chipiSDK.sessions.addSessionKeyToContract(
328
+ {
329
+ encryptKey,
330
+ wallet,
331
+ sessionConfig: {
332
+ sessionPublicKey: localSession.publicKey,
333
+ validUntil: sessionConfig.validUntil ?? localSession.validUntil,
334
+ maxCalls: sessionConfig.maxCalls ?? defaultMaxCalls,
335
+ allowedEntrypoints: sessionConfig.allowedEntrypoints ?? []
336
+ }
337
+ },
338
+ bearerToken
339
+ );
340
+ return txHash;
341
+ },
342
+ onSuccess: () => {
343
+ setError(null);
344
+ queryClient.invalidateQueries({
345
+ queryKey: ["chipi-session-status", wallet?.publicKey, localSession?.publicKey]
346
+ });
347
+ },
348
+ onError: (err) => {
349
+ setError(err);
350
+ }
351
+ });
352
+ const revokeSessionMutation = useMutation({
353
+ mutationFn: async () => {
354
+ if (!wallet) throw new Error("Wallet is required");
355
+ if (!localSession) throw new Error("No session to revoke");
356
+ if (!encryptKey) throw new Error("Encryption key (PIN) is required");
357
+ if (!supportsSession) throw new Error("Wallet does not support sessions");
358
+ const bearerToken = await getBearerToken();
359
+ if (!bearerToken) throw new Error("Bearer token is required");
360
+ const txHash = await chipiSDK.sessions.revokeSessionKey(
361
+ {
362
+ encryptKey,
363
+ wallet,
364
+ sessionPublicKey: localSession.publicKey
365
+ },
366
+ bearerToken
367
+ );
368
+ return txHash;
369
+ },
370
+ onSuccess: () => {
371
+ setError(null);
372
+ queryClient.invalidateQueries({
373
+ queryKey: ["chipi-session-status", wallet?.publicKey, localSession?.publicKey]
374
+ });
375
+ },
376
+ onError: (err) => {
377
+ setError(err);
378
+ }
379
+ });
380
+ const executeWithSessionMutation = useMutation({
381
+ mutationFn: async (calls) => {
382
+ if (!wallet) throw new Error("Wallet is required");
383
+ if (!localSession) throw new Error("No active session");
384
+ if (!encryptKey) throw new Error("Encryption key (PIN) is required");
385
+ if (!hasActiveSession) throw new Error("Session is not active. Register the session first.");
386
+ const bearerToken = await getBearerToken();
387
+ if (!bearerToken) throw new Error("Bearer token is required");
388
+ const txHash = await chipiSDK.executeTransactionWithSession({
389
+ params: {
390
+ encryptKey,
391
+ wallet,
392
+ session: localSession,
393
+ calls
394
+ },
395
+ bearerToken
396
+ });
397
+ return txHash;
398
+ },
399
+ onSuccess: () => {
400
+ setError(null);
401
+ queryClient.invalidateQueries({
402
+ queryKey: ["chipi-session-status", wallet?.publicKey, localSession?.publicKey]
403
+ });
404
+ },
405
+ onError: (err) => {
406
+ setError(err);
407
+ }
408
+ });
409
+ const createSession = useCallback(
410
+ async (params) => {
411
+ return createSessionMutation.mutateAsync(params ?? {});
412
+ },
413
+ [createSessionMutation]
414
+ );
415
+ const registerSession = useCallback(
416
+ async (sessionConfig) => {
417
+ return registerSessionMutation.mutateAsync(sessionConfig ?? {});
418
+ },
419
+ [registerSessionMutation]
420
+ );
421
+ const revokeSession = useCallback(async () => {
422
+ return revokeSessionMutation.mutateAsync();
423
+ }, [revokeSessionMutation]);
424
+ const executeWithSession = useCallback(
425
+ async (calls) => {
426
+ return executeWithSessionMutation.mutateAsync(calls);
427
+ },
428
+ [executeWithSessionMutation]
429
+ );
430
+ const clearSession = useCallback(() => {
431
+ setLocalSession(null);
432
+ setError(null);
433
+ }, []);
434
+ const refetchStatus = useCallback(async () => {
435
+ await sessionStatusQuery.refetch();
436
+ }, [sessionStatusQuery]);
437
+ const combinedError = useMemo(() => {
438
+ return error || createSessionMutation.error || registerSessionMutation.error || revokeSessionMutation.error || executeWithSessionMutation.error || sessionStatusQuery.error || null;
439
+ }, [
440
+ error,
441
+ createSessionMutation.error,
442
+ registerSessionMutation.error,
443
+ revokeSessionMutation.error,
444
+ executeWithSessionMutation.error,
445
+ sessionStatusQuery.error
446
+ ]);
447
+ return {
448
+ // Session data
449
+ session: localSession,
450
+ sessionStatus: sessionStatusQuery.data ?? void 0,
451
+ sessionState,
452
+ hasActiveSession,
453
+ isSessionExpired,
454
+ remainingCalls,
455
+ supportsSession,
456
+ // Actions
457
+ createSession,
458
+ registerSession,
459
+ revokeSession,
460
+ executeWithSession,
461
+ clearSession,
462
+ refetchStatus,
463
+ // Loading states
464
+ isCreating: createSessionMutation.isPending,
465
+ isRegistering: registerSessionMutation.isPending,
466
+ isRevoking: revokeSessionMutation.isPending,
467
+ isExecuting: executeWithSessionMutation.isPending,
468
+ isLoadingStatus: sessionStatusQuery.isLoading,
469
+ // Errors
470
+ error: combinedError
471
+ };
472
+ }
112
473
  function useTransfer() {
113
474
  const { chipiSDK } = useChipiContext();
114
475
  const mutation = useMutation(
@@ -559,7 +920,102 @@ function useCreateUser() {
559
920
  reset: mutation.reset
560
921
  };
561
922
  }
923
+ function useCreateSessionKey() {
924
+ const { chipiSDK } = useChipiContext();
925
+ const mutation = useMutation({
926
+ mutationFn: async (params) => chipiSDK.sessions.createSessionKey(params)
927
+ });
928
+ return {
929
+ createSessionKey: mutation.mutate,
930
+ createSessionKeyAsync: mutation.mutateAsync,
931
+ data: mutation.data,
932
+ isLoading: mutation.isPending,
933
+ isError: mutation.isError,
934
+ error: mutation.error,
935
+ isSuccess: mutation.isSuccess,
936
+ reset: mutation.reset
937
+ };
938
+ }
939
+ function useAddSessionKeyToContract() {
940
+ const { chipiSDK } = useChipiContext();
941
+ const mutation = useMutation({
942
+ mutationFn: (input) => chipiSDK.sessions.addSessionKeyToContract(
943
+ input.params,
944
+ input.bearerToken
945
+ )
946
+ });
947
+ return {
948
+ addSessionKeyToContract: mutation.mutate,
949
+ addSessionKeyToContractAsync: mutation.mutateAsync,
950
+ data: mutation.data,
951
+ isLoading: mutation.isPending,
952
+ isError: mutation.isError,
953
+ error: mutation.error,
954
+ isSuccess: mutation.isSuccess,
955
+ reset: mutation.reset
956
+ };
957
+ }
958
+ function useRevokeSessionKey() {
959
+ const { chipiSDK } = useChipiContext();
960
+ const mutation = useMutation({
961
+ mutationFn: (input) => chipiSDK.sessions.revokeSessionKey(input.params, input.bearerToken)
962
+ });
963
+ return {
964
+ revokeSessionKey: mutation.mutate,
965
+ revokeSessionKeyAsync: mutation.mutateAsync,
966
+ data: mutation.data,
967
+ isLoading: mutation.isPending,
968
+ isError: mutation.isError,
969
+ error: mutation.error,
970
+ isSuccess: mutation.isSuccess,
971
+ reset: mutation.reset
972
+ };
973
+ }
974
+ function useGetSessionData(params, options) {
975
+ const { chipiSDK } = useChipiContext();
976
+ const query = useQuery({
977
+ queryKey: [
978
+ "sessionData",
979
+ params?.walletAddress,
980
+ params?.sessionPublicKey
981
+ ],
982
+ queryFn: () => {
983
+ if (!params) {
984
+ throw new Error("Session data params are required");
985
+ }
986
+ return chipiSDK.sessions.getSessionData(params);
987
+ },
988
+ enabled: options?.enabled !== false && params !== null
989
+ });
990
+ return {
991
+ data: query.data,
992
+ isLoading: query.isLoading,
993
+ isError: query.isError,
994
+ error: query.error,
995
+ isSuccess: query.isSuccess,
996
+ refetch: query.refetch
997
+ };
998
+ }
999
+ function useExecuteWithSession() {
1000
+ const { chipiSDK } = useChipiContext();
1001
+ const mutation = useMutation({
1002
+ mutationFn: (input) => chipiSDK.executeTransactionWithSession({
1003
+ params: input.params,
1004
+ bearerToken: input.bearerToken
1005
+ })
1006
+ });
1007
+ return {
1008
+ executeWithSession: mutation.mutate,
1009
+ executeWithSessionAsync: mutation.mutateAsync,
1010
+ data: mutation.data,
1011
+ isLoading: mutation.isPending,
1012
+ isError: mutation.isError,
1013
+ error: mutation.error,
1014
+ isSuccess: mutation.isSuccess,
1015
+ reset: mutation.reset
1016
+ };
1017
+ }
562
1018
 
563
- export { ChipiProvider, useApprove, useCallAnyContract, useChipiContext, useCreateSkuTransaction, useCreateUser, useCreateWallet, useGetSku, useGetSkuList, useGetSkuTransaction, useGetTokenBalance, useGetTransactionList, useGetUser, useGetWallet, useRecordSendTransaction, useStakeVesuUsdc, useTransfer, useWithdrawVesuUsdc };
1019
+ export { ChipiProvider, useAddSessionKeyToContract, useApprove, useCallAnyContract, useChipiContext, useChipiSession, useChipiWallet, useCreateSessionKey, useCreateSkuTransaction, useCreateUser, useCreateWallet, useExecuteWithSession, useGetSessionData, useGetSku, useGetSkuList, useGetSkuTransaction, useGetTokenBalance, useGetTransactionList, useGetUser, useGetWallet, useRecordSendTransaction, useRevokeSessionKey, useStakeVesuUsdc, useTransfer, useWithdrawVesuUsdc };
564
1020
  //# sourceMappingURL=index.mjs.map
565
1021
  //# sourceMappingURL=index.mjs.map