@chipi-stack/chipi-react 14.0.0 → 14.1.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.d.ts CHANGED
@@ -4,7 +4,7 @@ import { ChipiSDK } from '@chipi-stack/backend';
4
4
  import { ChipiSDKConfig } from '@chipi-stack/types';
5
5
  export * from '@chipi-stack/types';
6
6
  export { Chain, ChainToken } from '@chipi-stack/types';
7
- export { ChipiWalletData, SessionState, SessionWallet, UseChipiSessionConfig, UseChipiSessionReturn, UseChipiWalletConfig, UseChipiWalletReturn, useAddSessionKeyToContract, useApprove, useCallAnyContract, useChipiSession, useChipiWallet, useCreateSessionKey, useCreateWallet, useExecuteWithSession, useGetSessionData, useGetSku, useGetSkuList, useGetSkuPurchase, useGetTokenBalance, useGetTransactionList, useGetWallet, useMigrateWalletToPasskey, usePurchaseSku, useRecordSendTransaction, useRevokeSessionKey, useTransfer, useUpdateWalletEncryption } from './hooks.js';
7
+ export { ChipiWalletData, SessionState, SessionWallet, UseChipiSessionConfig, UseChipiSessionReturn, UseChipiWalletConfig, UseChipiWalletReturn, UseX402PaymentConfig, UseX402PaymentReturn, useAddSessionKeyToContract, useApprove, useCallAnyContract, useChipiSession, useChipiWallet, useCreateSessionKey, useCreateWallet, useExecuteWithSession, useGetSessionData, useGetSku, useGetSkuList, useGetSkuPurchase, useGetTokenBalance, useGetTransaction, useGetTransactionList, useGetTransactionStatus, useGetWallet, useMigrateWalletToPasskey, usePurchaseSku, useRecordSendTransaction, useRevokeSessionKey, useTransfer, useUpdateWalletEncryption, useX402Payment } from './hooks.js';
8
8
  import '@tanstack/react-query';
9
9
 
10
10
  interface PasskeyAdapter {
package/dist/index.js CHANGED
@@ -7,6 +7,7 @@ var chipiPasskey = require('@chipi-stack/chipi-passkey');
7
7
  var jsxRuntime = require('react/jsx-runtime');
8
8
  var shared = require('@chipi-stack/shared');
9
9
  var types = require('@chipi-stack/types');
10
+ var core = require('@chipi-stack/core');
10
11
 
11
12
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
12
13
 
@@ -744,6 +745,104 @@ function useGetTransactionList(input) {
744
745
  fetchTransactionList
745
746
  };
746
747
  }
748
+ function useGetTransaction(input) {
749
+ const { chipiSDK } = useChipiContext();
750
+ const queryClient = reactQuery.useQueryClient();
751
+ const buildQueryKey = (hashOrId) => ["transaction", hashOrId ?? null];
752
+ const query = reactQuery.useQuery({
753
+ queryKey: buildQueryKey(input?.hashOrId),
754
+ queryFn: async () => {
755
+ if (!input?.hashOrId) throw new Error("hashOrId is required");
756
+ if (!input?.getBearerToken) throw new Error("getBearerToken is required");
757
+ const bearerToken = await input.getBearerToken();
758
+ if (!bearerToken) throw new Error("Bearer token is required");
759
+ return chipiSDK.getTransaction(input.hashOrId, bearerToken);
760
+ },
761
+ enabled: Boolean(input?.hashOrId && input?.getBearerToken),
762
+ retry: (failureCount, error) => {
763
+ if (error instanceof shared.ChipiApiError || error?.status) {
764
+ return false;
765
+ }
766
+ return failureCount < 3;
767
+ },
768
+ ...input?.queryOptions
769
+ });
770
+ const fetchTransaction = async (newInput) => {
771
+ return queryClient.fetchQuery({
772
+ queryKey: buildQueryKey(newInput.hashOrId),
773
+ queryFn: async () => {
774
+ const bearerToken = await newInput.getBearerToken();
775
+ if (!bearerToken) throw new Error("Bearer token is required");
776
+ return chipiSDK.getTransaction(newInput.hashOrId, bearerToken);
777
+ },
778
+ retry: (failureCount, error) => {
779
+ if (error instanceof shared.ChipiApiError || error?.status) {
780
+ return false;
781
+ }
782
+ return failureCount < 3;
783
+ }
784
+ });
785
+ };
786
+ return {
787
+ ...query,
788
+ fetchTransaction
789
+ };
790
+ }
791
+ var TERMINAL_STATUSES = [
792
+ types.OnChainTxStatus.ACCEPTED_ON_L1,
793
+ types.OnChainTxStatus.REJECTED,
794
+ types.OnChainTxStatus.REVERTED
795
+ ];
796
+ function useGetTransactionStatus(input) {
797
+ const { chipiSDK } = useChipiContext();
798
+ const queryClient = reactQuery.useQueryClient();
799
+ const buildQueryKey = (hash) => ["transaction-status", hash ?? null];
800
+ const query = reactQuery.useQuery({
801
+ queryKey: buildQueryKey(input?.hash),
802
+ queryFn: async () => {
803
+ if (!input?.hash) throw new Error("hash is required");
804
+ if (!input?.getBearerToken) throw new Error("getBearerToken is required");
805
+ const bearerToken = await input.getBearerToken();
806
+ if (!bearerToken) throw new Error("Bearer token is required");
807
+ return chipiSDK.getTransactionStatus(input.hash, bearerToken);
808
+ },
809
+ enabled: Boolean(input?.hash && input?.getBearerToken),
810
+ refetchInterval: (query2) => {
811
+ const status = query2.state.data?.status;
812
+ if (status && TERMINAL_STATUSES.includes(status)) {
813
+ return false;
814
+ }
815
+ return input?.refetchInterval ?? 3e3;
816
+ },
817
+ retry: (failureCount, error) => {
818
+ if (error instanceof shared.ChipiApiError || error?.status) {
819
+ return false;
820
+ }
821
+ return failureCount < 3;
822
+ },
823
+ ...input?.queryOptions
824
+ });
825
+ const fetchTransactionStatus = async (newInput) => {
826
+ return queryClient.fetchQuery({
827
+ queryKey: buildQueryKey(newInput.hash),
828
+ queryFn: async () => {
829
+ const bearerToken = await newInput.getBearerToken();
830
+ if (!bearerToken) throw new Error("Bearer token is required");
831
+ return chipiSDK.getTransactionStatus(newInput.hash, bearerToken);
832
+ },
833
+ retry: (failureCount, error) => {
834
+ if (error instanceof shared.ChipiApiError || error?.status) {
835
+ return false;
836
+ }
837
+ return failureCount < 3;
838
+ }
839
+ });
840
+ };
841
+ return {
842
+ ...query,
843
+ fetchTransactionStatus
844
+ };
845
+ }
747
846
  function usePurchaseSku() {
748
847
  const { chipiSDK } = useChipiContext();
749
848
  const mutation = reactQuery.useMutation({
@@ -1100,6 +1199,240 @@ function useExecuteWithSession() {
1100
1199
  reset: mutation.reset
1101
1200
  };
1102
1201
  }
1202
+ function useX402Payment(config) {
1203
+ const { chipiSDK } = useChipiContext();
1204
+ const {
1205
+ wallet,
1206
+ encryptKey,
1207
+ getBearerToken: getBearerTokenFn,
1208
+ bearerToken: staticBearerToken,
1209
+ maxPaymentAmount: maxPaymentAmountProp,
1210
+ maxAmount,
1211
+ allowedRecipients,
1212
+ session,
1213
+ onPaymentComplete
1214
+ } = config;
1215
+ const maxPaymentAmount = maxPaymentAmountProp ?? maxAmount;
1216
+ const getBearerToken = React.useMemo(
1217
+ () => getBearerTokenFn ?? (staticBearerToken ? () => Promise.resolve(staticBearerToken) : () => Promise.resolve(void 0)),
1218
+ [getBearerTokenFn, staticBearerToken]
1219
+ );
1220
+ const [lastTxHash, setLastTxHash] = React.useState(null);
1221
+ const [lastAmount, setLastAmount] = React.useState(null);
1222
+ const [lastPayment, setLastPayment] = React.useState(null);
1223
+ const [error, setError] = React.useState(null);
1224
+ const paymentCountRef = React.useRef(0);
1225
+ const [paymentCount, setPaymentCount] = React.useState(0);
1226
+ const totalSpentRef = React.useRef(0n);
1227
+ const [totalSpent, setTotalSpent] = React.useState("0.000000");
1228
+ const parsePaymentRequired = React.useCallback((response) => {
1229
+ const headerValue = response.headers.get("payment-required");
1230
+ if (!headerValue) {
1231
+ throw new Error(
1232
+ "Server returned 402 but no PAYMENT-REQUIRED header. The server may not support x402 or is misconfigured."
1233
+ );
1234
+ }
1235
+ try {
1236
+ return JSON.parse(headerValue);
1237
+ } catch {
1238
+ throw new Error("Malformed PAYMENT-REQUIRED header: invalid JSON");
1239
+ }
1240
+ }, []);
1241
+ const validateRequirement = React.useCallback(
1242
+ (requirement) => {
1243
+ if (requirement.scheme !== "exact") {
1244
+ throw new Error(
1245
+ `Unsupported payment scheme: "${requirement.scheme}". Only "exact" is supported.`
1246
+ );
1247
+ }
1248
+ if (requirement.network !== "starknet-mainnet") {
1249
+ throw new Error(
1250
+ `Unsupported network: "${requirement.network}". Only "starknet-mainnet" is supported.`
1251
+ );
1252
+ }
1253
+ const USDC_MAINNET = "0x033068F6539f8e6e6b131e6B2B814e6c34A5224bC66947c47DaB9dFeE93b35fb";
1254
+ const normalizeAddr = (a) => a.toLowerCase().replace(/^0x0+/, "0x");
1255
+ if (normalizeAddr(requirement.asset) !== normalizeAddr(USDC_MAINNET)) {
1256
+ throw new Error(`Unsupported asset: ${requirement.asset}. Only USDC is supported.`);
1257
+ }
1258
+ if (!requirement.payTo) {
1259
+ throw new Error("Invalid payment requirement: missing payTo address");
1260
+ }
1261
+ const timeoutSeconds = Number(requirement.maxTimeoutSeconds);
1262
+ if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
1263
+ throw new Error("Invalid payment requirement: maxTimeoutSeconds must be a positive number");
1264
+ }
1265
+ let requiredAmount;
1266
+ try {
1267
+ requiredAmount = BigInt(requirement.maxAmountRequired);
1268
+ } catch {
1269
+ throw new Error("Invalid payment requirement: maxAmountRequired must be an integer string");
1270
+ }
1271
+ if (requiredAmount <= 0n) {
1272
+ throw new Error("Invalid payment requirement: maxAmountRequired must be > 0");
1273
+ }
1274
+ if (maxPaymentAmount) {
1275
+ const trimmed = maxPaymentAmount.trim();
1276
+ if (!/^\d+(\.\d{1,6})?$/.test(trimmed)) {
1277
+ throw new Error(`Invalid maxPaymentAmount format: "${maxPaymentAmount}"`);
1278
+ }
1279
+ const [whole, frac = ""] = trimmed.split(".");
1280
+ const fracPadded = (frac + "000000").slice(0, 6);
1281
+ const maxBaseUnits = BigInt((whole || "0") + fracPadded);
1282
+ if (requiredAmount > maxBaseUnits) {
1283
+ const requiredHuman = (Number(requiredAmount) / 1e6).toFixed(6);
1284
+ throw new Error(
1285
+ `Payment amount ${requiredHuman} USDC exceeds maximum allowed ${maxPaymentAmount} USDC`
1286
+ );
1287
+ }
1288
+ }
1289
+ if (allowedRecipients && allowedRecipients.length > 0) {
1290
+ const normalize = (a) => a.toLowerCase().replace(/^0x0+/, "0x");
1291
+ const normalized = normalize(requirement.payTo);
1292
+ const isAllowed = allowedRecipients.some((addr) => normalize(addr) === normalized);
1293
+ if (!isAllowed) {
1294
+ throw new Error(`Recipient ${requirement.payTo} is not in the allowed recipients list`);
1295
+ }
1296
+ }
1297
+ },
1298
+ [maxPaymentAmount, allowedRecipients]
1299
+ );
1300
+ const signPayment = React.useCallback(
1301
+ async (requirement) => {
1302
+ if (!wallet) {
1303
+ throw new Error("Wallet is required for x402 payments");
1304
+ }
1305
+ if (!encryptKey) {
1306
+ throw new Error("Encryption key (PIN) is required for x402 payments");
1307
+ }
1308
+ validateRequirement(requirement);
1309
+ const nonce = crypto.randomUUID();
1310
+ const validUntil = Math.floor(Date.now() / 1e3) + requirement.maxTimeoutSeconds;
1311
+ if (session) {
1312
+ const bearerToken = await getBearerToken();
1313
+ if (!bearerToken) throw new Error("Bearer token is required");
1314
+ const txHash = await chipiSDK.executeTransactionWithSession({
1315
+ params: {
1316
+ encryptKey,
1317
+ wallet,
1318
+ session,
1319
+ calls: [
1320
+ {
1321
+ contractAddress: requirement.asset,
1322
+ entrypoint: "transfer",
1323
+ calldata: [requirement.payTo, requirement.maxAmountRequired, "0x0"]
1324
+ }
1325
+ ]
1326
+ },
1327
+ bearerToken
1328
+ });
1329
+ return {
1330
+ x402Version: 1,
1331
+ scheme: "exact",
1332
+ network: "starknet-mainnet",
1333
+ payload: {
1334
+ signature: { r: txHash, s: "session" },
1335
+ fromAddress: wallet.publicKey,
1336
+ toAddress: requirement.payTo,
1337
+ amount: requirement.maxAmountRequired,
1338
+ asset: requirement.asset,
1339
+ validUntil,
1340
+ nonce
1341
+ }
1342
+ };
1343
+ }
1344
+ const typedData = core.buildX402TypedData({
1345
+ from_address: wallet.publicKey,
1346
+ to_address: requirement.payTo,
1347
+ amount: requirement.maxAmountRequired,
1348
+ asset: requirement.asset,
1349
+ valid_until: String(validUntil),
1350
+ nonce
1351
+ });
1352
+ const signature = await chipiSDK.signTypedData({
1353
+ params: {
1354
+ encryptKey,
1355
+ wallet,
1356
+ typedData
1357
+ }
1358
+ });
1359
+ return {
1360
+ x402Version: 1,
1361
+ scheme: "exact",
1362
+ network: "starknet-mainnet",
1363
+ payload: {
1364
+ signature,
1365
+ fromAddress: wallet.publicKey,
1366
+ toAddress: requirement.payTo,
1367
+ amount: requirement.maxAmountRequired,
1368
+ asset: requirement.asset,
1369
+ validUntil,
1370
+ nonce
1371
+ }
1372
+ };
1373
+ },
1374
+ [wallet, encryptKey, session, getBearerToken, chipiSDK, validateRequirement]
1375
+ );
1376
+ const paymentMutation = reactQuery.useMutation(
1377
+ {
1378
+ mutationFn: async ({ url, init }) => {
1379
+ const response = await globalThis.fetch(url, init);
1380
+ if (response.status !== 402) {
1381
+ return response;
1382
+ }
1383
+ const requirement = parsePaymentRequired(response);
1384
+ const payment = await signPayment(requirement);
1385
+ const humanAmount = (Number(BigInt(requirement.maxAmountRequired)) / 1e6).toFixed(6);
1386
+ const isSessionPayment = payment.payload.signature.s === "session";
1387
+ const txHash = isSessionPayment ? payment.payload.signature.r : null;
1388
+ setLastAmount(humanAmount);
1389
+ setLastTxHash(txHash);
1390
+ setLastPayment({ txHash, amount: humanAmount, timestamp: Date.now() });
1391
+ totalSpentRef.current += BigInt(requirement.maxAmountRequired);
1392
+ setTotalSpent((Number(totalSpentRef.current) / 1e6).toFixed(6));
1393
+ paymentCountRef.current += 1;
1394
+ setPaymentCount(paymentCountRef.current);
1395
+ const headers = new Headers(init?.headers);
1396
+ headers.set("X-PAYMENT", JSON.stringify(payment));
1397
+ const paidResponse = await globalThis.fetch(url, { ...init, headers });
1398
+ if (paidResponse.status === 402) {
1399
+ throw new Error(
1400
+ "Server returned 402 after payment was submitted. Payment may have failed verification."
1401
+ );
1402
+ }
1403
+ if (onPaymentComplete) {
1404
+ void Promise.resolve(onPaymentComplete(txHash ?? "", humanAmount)).catch(() => {
1405
+ });
1406
+ }
1407
+ return paidResponse;
1408
+ },
1409
+ onError: (err) => {
1410
+ setError(err);
1411
+ },
1412
+ onSuccess: () => {
1413
+ setError(null);
1414
+ }
1415
+ }
1416
+ );
1417
+ const x402Fetch = React.useCallback(
1418
+ async (url, init) => {
1419
+ return paymentMutation.mutateAsync({ url, init });
1420
+ },
1421
+ [paymentMutation]
1422
+ );
1423
+ return {
1424
+ x402Fetch,
1425
+ payFetch: x402Fetch,
1426
+ signPayment,
1427
+ isPaying: paymentMutation.isPending,
1428
+ lastTxHash,
1429
+ lastAmount,
1430
+ lastPayment,
1431
+ totalSpent,
1432
+ error: error || paymentMutation.error || null,
1433
+ paymentCount
1434
+ };
1435
+ }
1103
1436
 
1104
1437
  Object.defineProperty(exports, "Chain", {
1105
1438
  enumerable: true,
@@ -1124,7 +1457,9 @@ exports.useGetSku = useGetSku;
1124
1457
  exports.useGetSkuList = useGetSkuList;
1125
1458
  exports.useGetSkuPurchase = useGetSkuPurchase;
1126
1459
  exports.useGetTokenBalance = useGetTokenBalance;
1460
+ exports.useGetTransaction = useGetTransaction;
1127
1461
  exports.useGetTransactionList = useGetTransactionList;
1462
+ exports.useGetTransactionStatus = useGetTransactionStatus;
1128
1463
  exports.useGetWallet = useGetWallet;
1129
1464
  exports.useMigrateWalletToPasskey = useMigrateWalletToPasskey;
1130
1465
  exports.usePurchaseSku = usePurchaseSku;
@@ -1132,5 +1467,6 @@ exports.useRecordSendTransaction = useRecordSendTransaction;
1132
1467
  exports.useRevokeSessionKey = useRevokeSessionKey;
1133
1468
  exports.useTransfer = useTransfer;
1134
1469
  exports.useUpdateWalletEncryption = useUpdateWalletEncryption;
1470
+ exports.useX402Payment = useX402Payment;
1135
1471
  //# sourceMappingURL=index.js.map
1136
1472
  //# sourceMappingURL=index.js.map