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