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