@chipi-stack/chipi-react 14.0.0 → 14.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/hooks.js CHANGED
@@ -7,6 +7,7 @@ var chipiPasskey = require('@chipi-stack/chipi-passkey');
7
7
  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
  // src/hooks/useCreateWallet.ts
12
13
  var ChipiContext = react.createContext(null);
@@ -703,6 +704,104 @@ function useGetTransactionList(input) {
703
704
  fetchTransactionList
704
705
  };
705
706
  }
707
+ function useGetTransaction(input) {
708
+ const { chipiSDK } = useChipiContext();
709
+ const queryClient = reactQuery.useQueryClient();
710
+ const buildQueryKey = (hashOrId) => ["transaction", hashOrId ?? null];
711
+ const query = reactQuery.useQuery({
712
+ queryKey: buildQueryKey(input?.hashOrId),
713
+ queryFn: async () => {
714
+ if (!input?.hashOrId) throw new Error("hashOrId is required");
715
+ if (!input?.getBearerToken) throw new Error("getBearerToken is required");
716
+ const bearerToken = await input.getBearerToken();
717
+ if (!bearerToken) throw new Error("Bearer token is required");
718
+ return chipiSDK.getTransaction(input.hashOrId, bearerToken);
719
+ },
720
+ enabled: Boolean(input?.hashOrId && input?.getBearerToken),
721
+ retry: (failureCount, error) => {
722
+ if (error instanceof shared.ChipiApiError || error?.status) {
723
+ return false;
724
+ }
725
+ return failureCount < 3;
726
+ },
727
+ ...input?.queryOptions
728
+ });
729
+ const fetchTransaction = async (newInput) => {
730
+ return queryClient.fetchQuery({
731
+ queryKey: buildQueryKey(newInput.hashOrId),
732
+ queryFn: async () => {
733
+ const bearerToken = await newInput.getBearerToken();
734
+ if (!bearerToken) throw new Error("Bearer token is required");
735
+ return chipiSDK.getTransaction(newInput.hashOrId, bearerToken);
736
+ },
737
+ retry: (failureCount, error) => {
738
+ if (error instanceof shared.ChipiApiError || error?.status) {
739
+ return false;
740
+ }
741
+ return failureCount < 3;
742
+ }
743
+ });
744
+ };
745
+ return {
746
+ ...query,
747
+ fetchTransaction
748
+ };
749
+ }
750
+ var TERMINAL_STATUSES = [
751
+ types.OnChainTxStatus.ACCEPTED_ON_L1,
752
+ types.OnChainTxStatus.REJECTED,
753
+ types.OnChainTxStatus.REVERTED
754
+ ];
755
+ function useGetTransactionStatus(input) {
756
+ const { chipiSDK } = useChipiContext();
757
+ const queryClient = reactQuery.useQueryClient();
758
+ const buildQueryKey = (hash) => ["transaction-status", hash ?? null];
759
+ const query = reactQuery.useQuery({
760
+ queryKey: buildQueryKey(input?.hash),
761
+ queryFn: async () => {
762
+ if (!input?.hash) throw new Error("hash is required");
763
+ if (!input?.getBearerToken) throw new Error("getBearerToken is required");
764
+ const bearerToken = await input.getBearerToken();
765
+ if (!bearerToken) throw new Error("Bearer token is required");
766
+ return chipiSDK.getTransactionStatus(input.hash, bearerToken);
767
+ },
768
+ enabled: Boolean(input?.hash && input?.getBearerToken),
769
+ refetchInterval: (query2) => {
770
+ const status = query2.state.data?.status;
771
+ if (status && TERMINAL_STATUSES.includes(status)) {
772
+ return false;
773
+ }
774
+ return input?.refetchInterval ?? 3e3;
775
+ },
776
+ retry: (failureCount, error) => {
777
+ if (error instanceof shared.ChipiApiError || error?.status) {
778
+ return false;
779
+ }
780
+ return failureCount < 3;
781
+ },
782
+ ...input?.queryOptions
783
+ });
784
+ const fetchTransactionStatus = async (newInput) => {
785
+ return queryClient.fetchQuery({
786
+ queryKey: buildQueryKey(newInput.hash),
787
+ queryFn: async () => {
788
+ const bearerToken = await newInput.getBearerToken();
789
+ if (!bearerToken) throw new Error("Bearer token is required");
790
+ return chipiSDK.getTransactionStatus(newInput.hash, bearerToken);
791
+ },
792
+ retry: (failureCount, error) => {
793
+ if (error instanceof shared.ChipiApiError || error?.status) {
794
+ return false;
795
+ }
796
+ return failureCount < 3;
797
+ }
798
+ });
799
+ };
800
+ return {
801
+ ...query,
802
+ fetchTransactionStatus
803
+ };
804
+ }
706
805
  function usePurchaseSku() {
707
806
  const { chipiSDK } = useChipiContext();
708
807
  const mutation = reactQuery.useMutation({
@@ -1059,6 +1158,240 @@ function useExecuteWithSession() {
1059
1158
  reset: mutation.reset
1060
1159
  };
1061
1160
  }
1161
+ function useX402Payment(config) {
1162
+ const { chipiSDK } = useChipiContext();
1163
+ const {
1164
+ wallet,
1165
+ encryptKey,
1166
+ getBearerToken: getBearerTokenFn,
1167
+ bearerToken: staticBearerToken,
1168
+ maxPaymentAmount: maxPaymentAmountProp,
1169
+ maxAmount,
1170
+ allowedRecipients,
1171
+ session,
1172
+ onPaymentComplete
1173
+ } = config;
1174
+ const maxPaymentAmount = maxPaymentAmountProp ?? maxAmount;
1175
+ const getBearerToken = react.useMemo(
1176
+ () => getBearerTokenFn ?? (staticBearerToken ? () => Promise.resolve(staticBearerToken) : () => Promise.resolve(void 0)),
1177
+ [getBearerTokenFn, staticBearerToken]
1178
+ );
1179
+ const [lastTxHash, setLastTxHash] = react.useState(null);
1180
+ const [lastAmount, setLastAmount] = react.useState(null);
1181
+ const [lastPayment, setLastPayment] = react.useState(null);
1182
+ const [error, setError] = react.useState(null);
1183
+ const paymentCountRef = react.useRef(0);
1184
+ const [paymentCount, setPaymentCount] = react.useState(0);
1185
+ const totalSpentRef = react.useRef(0n);
1186
+ const [totalSpent, setTotalSpent] = react.useState("0.000000");
1187
+ const parsePaymentRequired = react.useCallback((response) => {
1188
+ const headerValue = response.headers.get("payment-required");
1189
+ if (!headerValue) {
1190
+ throw new Error(
1191
+ "Server returned 402 but no PAYMENT-REQUIRED header. The server may not support x402 or is misconfigured."
1192
+ );
1193
+ }
1194
+ try {
1195
+ return JSON.parse(headerValue);
1196
+ } catch {
1197
+ throw new Error("Malformed PAYMENT-REQUIRED header: invalid JSON");
1198
+ }
1199
+ }, []);
1200
+ const validateRequirement = react.useCallback(
1201
+ (requirement) => {
1202
+ if (requirement.scheme !== "exact") {
1203
+ throw new Error(
1204
+ `Unsupported payment scheme: "${requirement.scheme}". Only "exact" is supported.`
1205
+ );
1206
+ }
1207
+ if (requirement.network !== "starknet-mainnet") {
1208
+ throw new Error(
1209
+ `Unsupported network: "${requirement.network}". Only "starknet-mainnet" is supported.`
1210
+ );
1211
+ }
1212
+ const USDC_MAINNET = "0x033068F6539f8e6e6b131e6B2B814e6c34A5224bC66947c47DaB9dFeE93b35fb";
1213
+ const normalizeAddr = (a) => a.toLowerCase().replace(/^0x0+/, "0x");
1214
+ if (normalizeAddr(requirement.asset) !== normalizeAddr(USDC_MAINNET)) {
1215
+ throw new Error(`Unsupported asset: ${requirement.asset}. Only USDC is supported.`);
1216
+ }
1217
+ if (!requirement.payTo) {
1218
+ throw new Error("Invalid payment requirement: missing payTo address");
1219
+ }
1220
+ const timeoutSeconds = Number(requirement.maxTimeoutSeconds);
1221
+ if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
1222
+ throw new Error("Invalid payment requirement: maxTimeoutSeconds must be a positive number");
1223
+ }
1224
+ let requiredAmount;
1225
+ try {
1226
+ requiredAmount = BigInt(requirement.maxAmountRequired);
1227
+ } catch {
1228
+ throw new Error("Invalid payment requirement: maxAmountRequired must be an integer string");
1229
+ }
1230
+ if (requiredAmount <= 0n) {
1231
+ throw new Error("Invalid payment requirement: maxAmountRequired must be > 0");
1232
+ }
1233
+ if (maxPaymentAmount) {
1234
+ const trimmed = maxPaymentAmount.trim();
1235
+ if (!/^\d+(\.\d{1,6})?$/.test(trimmed)) {
1236
+ throw new Error(`Invalid maxPaymentAmount format: "${maxPaymentAmount}"`);
1237
+ }
1238
+ const [whole, frac = ""] = trimmed.split(".");
1239
+ const fracPadded = (frac + "000000").slice(0, 6);
1240
+ const maxBaseUnits = BigInt((whole || "0") + fracPadded);
1241
+ if (requiredAmount > maxBaseUnits) {
1242
+ const requiredHuman = (Number(requiredAmount) / 1e6).toFixed(6);
1243
+ throw new Error(
1244
+ `Payment amount ${requiredHuman} USDC exceeds maximum allowed ${maxPaymentAmount} USDC`
1245
+ );
1246
+ }
1247
+ }
1248
+ if (allowedRecipients && allowedRecipients.length > 0) {
1249
+ const normalize = (a) => a.toLowerCase().replace(/^0x0+/, "0x");
1250
+ const normalized = normalize(requirement.payTo);
1251
+ const isAllowed = allowedRecipients.some((addr) => normalize(addr) === normalized);
1252
+ if (!isAllowed) {
1253
+ throw new Error(`Recipient ${requirement.payTo} is not in the allowed recipients list`);
1254
+ }
1255
+ }
1256
+ },
1257
+ [maxPaymentAmount, allowedRecipients]
1258
+ );
1259
+ const signPayment = react.useCallback(
1260
+ async (requirement) => {
1261
+ if (!wallet) {
1262
+ throw new Error("Wallet is required for x402 payments");
1263
+ }
1264
+ if (!encryptKey) {
1265
+ throw new Error("Encryption key (PIN) is required for x402 payments");
1266
+ }
1267
+ validateRequirement(requirement);
1268
+ const nonce = crypto.randomUUID();
1269
+ const validUntil = Math.floor(Date.now() / 1e3) + requirement.maxTimeoutSeconds;
1270
+ if (session) {
1271
+ const bearerToken = await getBearerToken();
1272
+ if (!bearerToken) throw new Error("Bearer token is required");
1273
+ const txHash = await chipiSDK.executeTransactionWithSession({
1274
+ params: {
1275
+ encryptKey,
1276
+ wallet,
1277
+ session,
1278
+ calls: [
1279
+ {
1280
+ contractAddress: requirement.asset,
1281
+ entrypoint: "transfer",
1282
+ calldata: [requirement.payTo, requirement.maxAmountRequired, "0x0"]
1283
+ }
1284
+ ]
1285
+ },
1286
+ bearerToken
1287
+ });
1288
+ return {
1289
+ x402Version: 1,
1290
+ scheme: "exact",
1291
+ network: "starknet-mainnet",
1292
+ payload: {
1293
+ signature: { r: txHash, s: "session" },
1294
+ fromAddress: wallet.publicKey,
1295
+ toAddress: requirement.payTo,
1296
+ amount: requirement.maxAmountRequired,
1297
+ asset: requirement.asset,
1298
+ validUntil,
1299
+ nonce
1300
+ }
1301
+ };
1302
+ }
1303
+ const typedData = core.buildX402TypedData({
1304
+ from_address: wallet.publicKey,
1305
+ to_address: requirement.payTo,
1306
+ amount: requirement.maxAmountRequired,
1307
+ asset: requirement.asset,
1308
+ valid_until: String(validUntil),
1309
+ nonce
1310
+ });
1311
+ const signature = await chipiSDK.signTypedData({
1312
+ params: {
1313
+ encryptKey,
1314
+ wallet,
1315
+ typedData
1316
+ }
1317
+ });
1318
+ return {
1319
+ x402Version: 1,
1320
+ scheme: "exact",
1321
+ network: "starknet-mainnet",
1322
+ payload: {
1323
+ signature,
1324
+ fromAddress: wallet.publicKey,
1325
+ toAddress: requirement.payTo,
1326
+ amount: requirement.maxAmountRequired,
1327
+ asset: requirement.asset,
1328
+ validUntil,
1329
+ nonce
1330
+ }
1331
+ };
1332
+ },
1333
+ [wallet, encryptKey, session, getBearerToken, chipiSDK, validateRequirement]
1334
+ );
1335
+ const paymentMutation = reactQuery.useMutation(
1336
+ {
1337
+ mutationFn: async ({ url, init }) => {
1338
+ const response = await globalThis.fetch(url, init);
1339
+ if (response.status !== 402) {
1340
+ return response;
1341
+ }
1342
+ const requirement = parsePaymentRequired(response);
1343
+ const payment = await signPayment(requirement);
1344
+ const humanAmount = (Number(BigInt(requirement.maxAmountRequired)) / 1e6).toFixed(6);
1345
+ const isSessionPayment = payment.payload.signature.s === "session";
1346
+ const txHash = isSessionPayment ? payment.payload.signature.r : null;
1347
+ setLastAmount(humanAmount);
1348
+ setLastTxHash(txHash);
1349
+ setLastPayment({ txHash, amount: humanAmount, timestamp: Date.now() });
1350
+ totalSpentRef.current += BigInt(requirement.maxAmountRequired);
1351
+ setTotalSpent((Number(totalSpentRef.current) / 1e6).toFixed(6));
1352
+ paymentCountRef.current += 1;
1353
+ setPaymentCount(paymentCountRef.current);
1354
+ const headers = new Headers(init?.headers);
1355
+ headers.set("X-PAYMENT", JSON.stringify(payment));
1356
+ const paidResponse = await globalThis.fetch(url, { ...init, headers });
1357
+ if (paidResponse.status === 402) {
1358
+ throw new Error(
1359
+ "Server returned 402 after payment was submitted. Payment may have failed verification."
1360
+ );
1361
+ }
1362
+ if (onPaymentComplete) {
1363
+ void Promise.resolve(onPaymentComplete(txHash ?? "", humanAmount)).catch(() => {
1364
+ });
1365
+ }
1366
+ return paidResponse;
1367
+ },
1368
+ onError: (err) => {
1369
+ setError(err);
1370
+ },
1371
+ onSuccess: () => {
1372
+ setError(null);
1373
+ }
1374
+ }
1375
+ );
1376
+ const x402Fetch = react.useCallback(
1377
+ async (url, init) => {
1378
+ return paymentMutation.mutateAsync({ url, init });
1379
+ },
1380
+ [paymentMutation]
1381
+ );
1382
+ return {
1383
+ x402Fetch,
1384
+ payFetch: x402Fetch,
1385
+ signPayment,
1386
+ isPaying: paymentMutation.isPending,
1387
+ lastTxHash,
1388
+ lastAmount,
1389
+ lastPayment,
1390
+ totalSpent,
1391
+ error: error || paymentMutation.error || null,
1392
+ paymentCount
1393
+ };
1394
+ }
1062
1395
 
1063
1396
  exports.useAddSessionKeyToContract = useAddSessionKeyToContract;
1064
1397
  exports.useApprove = useApprove;
@@ -1073,7 +1406,9 @@ exports.useGetSku = useGetSku;
1073
1406
  exports.useGetSkuList = useGetSkuList;
1074
1407
  exports.useGetSkuPurchase = useGetSkuPurchase;
1075
1408
  exports.useGetTokenBalance = useGetTokenBalance;
1409
+ exports.useGetTransaction = useGetTransaction;
1076
1410
  exports.useGetTransactionList = useGetTransactionList;
1411
+ exports.useGetTransactionStatus = useGetTransactionStatus;
1077
1412
  exports.useGetWallet = useGetWallet;
1078
1413
  exports.useMigrateWalletToPasskey = useMigrateWalletToPasskey;
1079
1414
  exports.usePurchaseSku = usePurchaseSku;
@@ -1081,5 +1416,6 @@ exports.useRecordSendTransaction = useRecordSendTransaction;
1081
1416
  exports.useRevokeSessionKey = useRevokeSessionKey;
1082
1417
  exports.useTransfer = useTransfer;
1083
1418
  exports.useUpdateWalletEncryption = useUpdateWalletEncryption;
1419
+ exports.useX402Payment = useX402Payment;
1084
1420
  //# sourceMappingURL=hooks.js.map
1085
1421
  //# sourceMappingURL=hooks.js.map