@alleyboss/micropay-solana-x402-paywall 3.2.2 → 3.3.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/README.md +30 -0
- package/dist/agent/index.cjs +2 -2
- package/dist/agent/index.d.cts +1 -1
- package/dist/agent/index.d.ts +1 -1
- package/dist/agent/index.js +2 -2
- package/dist/client/index.cjs +220 -0
- package/dist/client/index.d.cts +101 -1
- package/dist/client/index.d.ts +101 -1
- package/dist/client/index.js +218 -2
- package/dist/index.cjs +278 -154
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +276 -156
- package/dist/next/index.cjs +58 -23
- package/dist/next/index.js +58 -23
- package/dist/pricing/index.cjs +54 -38
- package/dist/pricing/index.d.cts +8 -9
- package/dist/pricing/index.d.ts +8 -9
- package/dist/pricing/index.js +54 -38
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -47,8 +47,8 @@ function buildSolanaPayUrl(params) {
|
|
|
47
47
|
}
|
|
48
48
|
return url.toString();
|
|
49
49
|
}
|
|
50
|
-
function createPaymentFlow(
|
|
51
|
-
const { network, recipientWallet, amount, asset = "native", memo } =
|
|
50
|
+
function createPaymentFlow(config) {
|
|
51
|
+
const { network, recipientWallet, amount, asset = "native", memo } = config;
|
|
52
52
|
let decimals = 9;
|
|
53
53
|
let mintAddress;
|
|
54
54
|
if (asset === "usdc") {
|
|
@@ -64,7 +64,7 @@ function createPaymentFlow(config2) {
|
|
|
64
64
|
const naturalAmount = Number(amount) / Math.pow(10, decimals);
|
|
65
65
|
return {
|
|
66
66
|
/** Get the payment configuration */
|
|
67
|
-
getConfig: () => ({ ...
|
|
67
|
+
getConfig: () => ({ ...config }),
|
|
68
68
|
/** Get amount in natural display units (e.g., 0.01 SOL) */
|
|
69
69
|
getDisplayAmount: () => naturalAmount,
|
|
70
70
|
/** Get amount formatted with symbol */
|
|
@@ -252,10 +252,265 @@ function usePaywallResource({
|
|
|
252
252
|
unlock
|
|
253
253
|
};
|
|
254
254
|
}
|
|
255
|
+
|
|
256
|
+
// src/pricing/utils.ts
|
|
257
|
+
function lamportsToSol(lamports) {
|
|
258
|
+
return Number(lamports) / 1e9;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// src/pricing/index.ts
|
|
262
|
+
var priceCache = null;
|
|
263
|
+
var currentConfig = {};
|
|
264
|
+
function configurePricing(newConfig) {
|
|
265
|
+
currentConfig = { ...currentConfig, ...newConfig };
|
|
266
|
+
}
|
|
267
|
+
var PROVIDERS = [
|
|
268
|
+
{
|
|
269
|
+
name: "coincap",
|
|
270
|
+
url: "https://api.coincap.io/v2/assets/solana",
|
|
271
|
+
parse: (data) => parseFloat(data.data?.priceUsd || "0")
|
|
272
|
+
},
|
|
273
|
+
{
|
|
274
|
+
name: "binance",
|
|
275
|
+
url: "https://api.binance.com/api/v3/ticker/price?symbol=SOLUSDT",
|
|
276
|
+
parse: (data) => parseFloat(data.price || "0")
|
|
277
|
+
},
|
|
278
|
+
{
|
|
279
|
+
name: "coingecko",
|
|
280
|
+
url: "https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd",
|
|
281
|
+
parse: (data) => data.solana?.usd || 0
|
|
282
|
+
},
|
|
283
|
+
{
|
|
284
|
+
name: "kraken",
|
|
285
|
+
url: "https://api.kraken.com/0/public/Ticker?pair=SOLUSD",
|
|
286
|
+
parse: (data) => parseFloat(data.result?.SOLUSD?.c?.[0] || "0")
|
|
287
|
+
}
|
|
288
|
+
];
|
|
289
|
+
async function fetchFromProvider(provider, timeout) {
|
|
290
|
+
const controller = new AbortController();
|
|
291
|
+
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
292
|
+
try {
|
|
293
|
+
const response = await fetch(provider.url, {
|
|
294
|
+
headers: { "Accept": "application/json" },
|
|
295
|
+
signal: controller.signal
|
|
296
|
+
});
|
|
297
|
+
if (!response.ok) {
|
|
298
|
+
throw new Error(`HTTP ${response.status}`);
|
|
299
|
+
}
|
|
300
|
+
const data = await response.json();
|
|
301
|
+
const price = provider.parse(data);
|
|
302
|
+
if (!price || price <= 0) {
|
|
303
|
+
throw new Error("Invalid price");
|
|
304
|
+
}
|
|
305
|
+
return { price, source: provider.name };
|
|
306
|
+
} finally {
|
|
307
|
+
clearTimeout(timeoutId);
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
async function fetchPriceParallel(timeout) {
|
|
311
|
+
const promises = PROVIDERS.map(
|
|
312
|
+
(provider) => fetchFromProvider(provider, timeout).catch(() => null)
|
|
313
|
+
);
|
|
314
|
+
const results = await Promise.all(promises);
|
|
315
|
+
const validResult = results.find((r) => r !== null);
|
|
316
|
+
if (validResult) {
|
|
317
|
+
return validResult;
|
|
318
|
+
}
|
|
319
|
+
throw new Error("All providers failed");
|
|
320
|
+
}
|
|
321
|
+
async function fetchPriceSequential(timeout) {
|
|
322
|
+
for (const provider of PROVIDERS) {
|
|
323
|
+
try {
|
|
324
|
+
return await fetchFromProvider(provider, timeout);
|
|
325
|
+
} catch {
|
|
326
|
+
continue;
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
throw new Error("All providers failed");
|
|
330
|
+
}
|
|
331
|
+
async function getSolPrice() {
|
|
332
|
+
const cacheTTL = currentConfig.cacheTTL ?? 6e4;
|
|
333
|
+
const timeout = currentConfig.timeout ?? 3e3;
|
|
334
|
+
const useParallel = currentConfig.parallelFetch ?? true;
|
|
335
|
+
const now = Date.now();
|
|
336
|
+
if (priceCache && now - priceCache.timestamp < cacheTTL) {
|
|
337
|
+
return priceCache.data;
|
|
338
|
+
}
|
|
339
|
+
if (currentConfig.customProvider) {
|
|
340
|
+
try {
|
|
341
|
+
const price = await currentConfig.customProvider();
|
|
342
|
+
if (price > 0) {
|
|
343
|
+
const data = {
|
|
344
|
+
solPrice: price,
|
|
345
|
+
fetchedAt: /* @__PURE__ */ new Date(),
|
|
346
|
+
source: "custom"
|
|
347
|
+
};
|
|
348
|
+
priceCache = { data, timestamp: now };
|
|
349
|
+
return data;
|
|
350
|
+
}
|
|
351
|
+
} catch {
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
try {
|
|
355
|
+
const result = useParallel ? await fetchPriceParallel(timeout) : await fetchPriceSequential(timeout);
|
|
356
|
+
const data = {
|
|
357
|
+
solPrice: result.price,
|
|
358
|
+
fetchedAt: /* @__PURE__ */ new Date(),
|
|
359
|
+
source: result.source
|
|
360
|
+
};
|
|
361
|
+
priceCache = { data, timestamp: now };
|
|
362
|
+
return data;
|
|
363
|
+
} catch {
|
|
364
|
+
if (priceCache) {
|
|
365
|
+
return {
|
|
366
|
+
...priceCache.data,
|
|
367
|
+
source: `${priceCache.data.source} (stale)`
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
throw new Error(
|
|
371
|
+
"Failed to fetch SOL price from all providers. Configure a custom provider or ensure network connectivity."
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
async function lamportsToUsd(lamports) {
|
|
376
|
+
const { solPrice } = await getSolPrice();
|
|
377
|
+
const sol = Number(lamports) / 1e9;
|
|
378
|
+
return sol * solPrice;
|
|
379
|
+
}
|
|
380
|
+
async function usdToLamports(usd) {
|
|
381
|
+
const { solPrice } = await getSolPrice();
|
|
382
|
+
const sol = usd / solPrice;
|
|
383
|
+
return BigInt(Math.floor(sol * 1e9));
|
|
384
|
+
}
|
|
385
|
+
async function formatPriceDisplay(lamports) {
|
|
386
|
+
const { solPrice } = await getSolPrice();
|
|
387
|
+
const sol = Number(lamports) / 1e9;
|
|
388
|
+
const usd = sol * solPrice;
|
|
389
|
+
return `${sol.toFixed(4)} SOL (~$${usd.toFixed(2)})`;
|
|
390
|
+
}
|
|
391
|
+
function formatPriceSync(lamports, solPrice) {
|
|
392
|
+
const sol = Number(lamports) / 1e9;
|
|
393
|
+
const usd = sol * solPrice;
|
|
394
|
+
return {
|
|
395
|
+
sol,
|
|
396
|
+
usd,
|
|
397
|
+
formatted: `${sol.toFixed(4)} SOL (~$${usd.toFixed(2)})`
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
function clearPriceCache() {
|
|
401
|
+
priceCache = null;
|
|
402
|
+
}
|
|
403
|
+
function getProviders() {
|
|
404
|
+
return PROVIDERS.map((p) => ({ name: p.name, url: p.url }));
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// src/client/hooks.ts
|
|
408
|
+
function usePricing(refreshIntervalMs = 6e4) {
|
|
409
|
+
const [priceData, setPriceData] = react.useState(null);
|
|
410
|
+
const [isLoading, setIsLoading] = react.useState(true);
|
|
411
|
+
const [error, setError] = react.useState(null);
|
|
412
|
+
const intervalRef = react.useRef(null);
|
|
413
|
+
const fetchPrice = react.useCallback(async () => {
|
|
414
|
+
try {
|
|
415
|
+
setIsLoading(true);
|
|
416
|
+
setError(null);
|
|
417
|
+
const data = await getSolPrice();
|
|
418
|
+
setPriceData(data);
|
|
419
|
+
} catch (err) {
|
|
420
|
+
setError(err instanceof Error ? err.message : "Failed to fetch price");
|
|
421
|
+
} finally {
|
|
422
|
+
setIsLoading(false);
|
|
423
|
+
}
|
|
424
|
+
}, []);
|
|
425
|
+
react.useEffect(() => {
|
|
426
|
+
fetchPrice();
|
|
427
|
+
if (refreshIntervalMs > 0) {
|
|
428
|
+
intervalRef.current = setInterval(fetchPrice, refreshIntervalMs);
|
|
429
|
+
}
|
|
430
|
+
return () => {
|
|
431
|
+
if (intervalRef.current) {
|
|
432
|
+
clearInterval(intervalRef.current);
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
}, [fetchPrice, refreshIntervalMs]);
|
|
436
|
+
return {
|
|
437
|
+
solPrice: priceData?.solPrice ?? null,
|
|
438
|
+
source: priceData?.source ?? null,
|
|
439
|
+
fetchedAt: priceData?.fetchedAt ?? null,
|
|
440
|
+
isLoading,
|
|
441
|
+
error,
|
|
442
|
+
refresh: fetchPrice
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
function useLamportsToUsd(lamports) {
|
|
446
|
+
const { solPrice, isLoading } = usePricing();
|
|
447
|
+
if (isLoading || !solPrice || lamports === null) {
|
|
448
|
+
return { usd: null, formatted: null, isLoading };
|
|
449
|
+
}
|
|
450
|
+
const lamportsBigInt = typeof lamports === "number" ? BigInt(lamports) : lamports;
|
|
451
|
+
const sol = Number(lamportsBigInt) / 1e9;
|
|
452
|
+
const usd = sol * solPrice;
|
|
453
|
+
return {
|
|
454
|
+
usd,
|
|
455
|
+
formatted: `$${usd.toFixed(2)}`,
|
|
456
|
+
isLoading: false
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
function useMicropay() {
|
|
460
|
+
const [status, setStatus] = react.useState("idle");
|
|
461
|
+
const [error, setError] = react.useState(null);
|
|
462
|
+
const [signature, setSignature] = react.useState(null);
|
|
463
|
+
const reset = react.useCallback(() => {
|
|
464
|
+
setStatus("idle");
|
|
465
|
+
setError(null);
|
|
466
|
+
setSignature(null);
|
|
467
|
+
}, []);
|
|
468
|
+
const pay = react.useCallback(async (_options) => {
|
|
469
|
+
setStatus("pending");
|
|
470
|
+
setError(null);
|
|
471
|
+
try {
|
|
472
|
+
throw new Error(
|
|
473
|
+
"useMicropay requires implementation of onSign/onSend callbacks. See documentation for wallet adapter integration."
|
|
474
|
+
);
|
|
475
|
+
} catch (err) {
|
|
476
|
+
const errorMessage = err instanceof Error ? err.message : "Payment failed";
|
|
477
|
+
setError(errorMessage);
|
|
478
|
+
setStatus("error");
|
|
479
|
+
return { success: false, error: errorMessage };
|
|
480
|
+
}
|
|
481
|
+
}, []);
|
|
482
|
+
return {
|
|
483
|
+
status,
|
|
484
|
+
error,
|
|
485
|
+
signature,
|
|
486
|
+
pay,
|
|
487
|
+
reset
|
|
488
|
+
};
|
|
489
|
+
}
|
|
490
|
+
function useFormatPrice(lamports) {
|
|
491
|
+
const { solPrice, isLoading } = usePricing();
|
|
492
|
+
if (isLoading || !solPrice || lamports === null) {
|
|
493
|
+
return {
|
|
494
|
+
sol: null,
|
|
495
|
+
usd: null,
|
|
496
|
+
formatted: "Loading...",
|
|
497
|
+
isLoading
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
const lamportsBigInt = typeof lamports === "number" ? BigInt(lamports) : lamports;
|
|
501
|
+
const sol = Number(lamportsBigInt) / 1e9;
|
|
502
|
+
const usd = sol * solPrice;
|
|
503
|
+
return {
|
|
504
|
+
sol,
|
|
505
|
+
usd,
|
|
506
|
+
formatted: `${sol.toFixed(4)} SOL (~$${usd.toFixed(2)})`,
|
|
507
|
+
isLoading: false
|
|
508
|
+
};
|
|
509
|
+
}
|
|
255
510
|
var DEFAULT_COMPUTE_UNITS = 2e5;
|
|
256
511
|
var DEFAULT_MICRO_LAMPORTS = 1e3;
|
|
257
|
-
function createPriorityFeeInstructions(
|
|
258
|
-
const { enabled = false, microLamports, computeUnits } =
|
|
512
|
+
function createPriorityFeeInstructions(config = {}) {
|
|
513
|
+
const { enabled = false, microLamports, computeUnits } = config;
|
|
259
514
|
if (!enabled) {
|
|
260
515
|
return [];
|
|
261
516
|
}
|
|
@@ -266,14 +521,14 @@ function createPriorityFeeInstructions(config2 = {}) {
|
|
|
266
521
|
instructions.push(web3_js.ComputeBudgetProgram.setComputeUnitPrice({ microLamports: price }));
|
|
267
522
|
return instructions;
|
|
268
523
|
}
|
|
269
|
-
async function buildVersionedTransaction(
|
|
524
|
+
async function buildVersionedTransaction(config) {
|
|
270
525
|
const {
|
|
271
526
|
connection,
|
|
272
527
|
payer,
|
|
273
528
|
instructions,
|
|
274
529
|
priorityFee,
|
|
275
530
|
recentBlockhash
|
|
276
|
-
} =
|
|
531
|
+
} = config;
|
|
277
532
|
const priorityIxs = createPriorityFeeInstructions(priorityFee);
|
|
278
533
|
const allInstructions = [...priorityIxs, ...instructions];
|
|
279
534
|
let blockhash;
|
|
@@ -389,9 +644,9 @@ async function getAgentBalance(connection, agentKeypair) {
|
|
|
389
644
|
balanceSol: balance / web3_js.LAMPORTS_PER_SOL
|
|
390
645
|
};
|
|
391
646
|
}
|
|
392
|
-
async function hasAgentSufficientBalance(connection, agentKeypair, requiredLamports) {
|
|
647
|
+
async function hasAgentSufficientBalance(connection, agentKeypair, requiredLamports, feeBufferLamports = 5000000n) {
|
|
393
648
|
const { balance } = await getAgentBalance(connection, agentKeypair);
|
|
394
|
-
const totalRequired = requiredLamports +
|
|
649
|
+
const totalRequired = requiredLamports + feeBufferLamports;
|
|
395
650
|
return {
|
|
396
651
|
sufficient: balance >= totalRequired,
|
|
397
652
|
balance,
|
|
@@ -440,20 +695,20 @@ function validateWalletAddress(address) {
|
|
|
440
695
|
const base58Regex = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
|
|
441
696
|
return base58Regex.test(address);
|
|
442
697
|
}
|
|
443
|
-
async function createCreditSession(walletAddress, purchaseId,
|
|
698
|
+
async function createCreditSession(walletAddress, purchaseId, config) {
|
|
444
699
|
if (!validateWalletAddress(walletAddress)) {
|
|
445
700
|
throw new Error("Invalid wallet address format");
|
|
446
701
|
}
|
|
447
|
-
if (
|
|
702
|
+
if (config.initialCredits <= 0 || config.initialCredits > MAX_CREDITS) {
|
|
448
703
|
throw new Error(`Credits must be between 1 and ${MAX_CREDITS}`);
|
|
449
704
|
}
|
|
450
|
-
if (!
|
|
705
|
+
if (!config.durationHours || config.durationHours <= 0 || config.durationHours > 8760) {
|
|
451
706
|
throw new Error("Session duration must be between 1 and 8760 hours (1 year)");
|
|
452
707
|
}
|
|
453
708
|
const sessionId = uuidv4();
|
|
454
709
|
const now = Math.floor(Date.now() / 1e3);
|
|
455
|
-
const expiresAt = now +
|
|
456
|
-
const bundleExpiry =
|
|
710
|
+
const expiresAt = now + config.durationHours * 3600;
|
|
711
|
+
const bundleExpiry = config.bundleExpiryHours ? now + config.bundleExpiryHours * 3600 : expiresAt;
|
|
457
712
|
const session = {
|
|
458
713
|
id: sessionId,
|
|
459
714
|
walletAddress,
|
|
@@ -461,22 +716,22 @@ async function createCreditSession(walletAddress, purchaseId, config2) {
|
|
|
461
716
|
siteWideUnlock: false,
|
|
462
717
|
createdAt: now,
|
|
463
718
|
expiresAt,
|
|
464
|
-
credits:
|
|
719
|
+
credits: config.initialCredits,
|
|
465
720
|
bundleExpiry,
|
|
466
|
-
bundleType:
|
|
721
|
+
bundleType: config.bundleType
|
|
467
722
|
};
|
|
468
723
|
const payload = {
|
|
469
724
|
sub: walletAddress,
|
|
470
725
|
sid: sessionId,
|
|
471
726
|
articles: session.unlockedArticles,
|
|
472
727
|
siteWide: false,
|
|
473
|
-
credits:
|
|
728
|
+
credits: config.initialCredits,
|
|
474
729
|
bundleExpiry,
|
|
475
|
-
bundleType:
|
|
730
|
+
bundleType: config.bundleType,
|
|
476
731
|
iat: now,
|
|
477
732
|
exp: expiresAt
|
|
478
733
|
};
|
|
479
|
-
const token = await new jose.SignJWT(payload).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(`${
|
|
734
|
+
const token = await new jose.SignJWT(payload).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(`${config.durationHours}h`).sign(getSecretKey(config.secret));
|
|
480
735
|
return { token, session };
|
|
481
736
|
}
|
|
482
737
|
async function validateCreditSession(token, secret) {
|
|
@@ -594,141 +849,6 @@ async function getRemainingCredits(token, secret) {
|
|
|
594
849
|
};
|
|
595
850
|
}
|
|
596
851
|
|
|
597
|
-
// src/pricing/utils.ts
|
|
598
|
-
function lamportsToSol(lamports) {
|
|
599
|
-
return Number(lamports) / 1e9;
|
|
600
|
-
}
|
|
601
|
-
|
|
602
|
-
// src/pricing/index.ts
|
|
603
|
-
var cachedPrice = null;
|
|
604
|
-
var config = {};
|
|
605
|
-
var lastProviderIndex = -1;
|
|
606
|
-
function configurePricing(newConfig) {
|
|
607
|
-
config = { ...config, ...newConfig };
|
|
608
|
-
cachedPrice = null;
|
|
609
|
-
}
|
|
610
|
-
var PROVIDERS = [
|
|
611
|
-
{
|
|
612
|
-
name: "coincap",
|
|
613
|
-
url: "https://api.coincap.io/v2/assets/solana",
|
|
614
|
-
parse: (data) => parseFloat(data.data?.priceUsd || "0")
|
|
615
|
-
},
|
|
616
|
-
{
|
|
617
|
-
name: "binance",
|
|
618
|
-
url: "https://api.binance.com/api/v3/ticker/price?symbol=SOLUSDT",
|
|
619
|
-
parse: (data) => parseFloat(data.price || "0")
|
|
620
|
-
},
|
|
621
|
-
{
|
|
622
|
-
name: "coingecko",
|
|
623
|
-
url: "https://api.coingecko.com/api/v3/simple/price?ids=solana&vs_currencies=usd",
|
|
624
|
-
parse: (data) => data.solana?.usd || 0
|
|
625
|
-
},
|
|
626
|
-
{
|
|
627
|
-
name: "kraken",
|
|
628
|
-
url: "https://api.kraken.com/0/public/Ticker?pair=SOLUSD",
|
|
629
|
-
parse: (data) => parseFloat(data.result?.SOLUSD?.c?.[0] || "0")
|
|
630
|
-
}
|
|
631
|
-
];
|
|
632
|
-
async function fetchFromProvider(provider, timeout) {
|
|
633
|
-
const controller = new AbortController();
|
|
634
|
-
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
635
|
-
try {
|
|
636
|
-
const response = await fetch(provider.url, {
|
|
637
|
-
headers: { "Accept": "application/json" },
|
|
638
|
-
signal: controller.signal
|
|
639
|
-
});
|
|
640
|
-
if (!response.ok) {
|
|
641
|
-
throw new Error(`HTTP ${response.status}`);
|
|
642
|
-
}
|
|
643
|
-
const data = await response.json();
|
|
644
|
-
const price = provider.parse(data);
|
|
645
|
-
if (!price || price <= 0) {
|
|
646
|
-
throw new Error("Invalid price");
|
|
647
|
-
}
|
|
648
|
-
return price;
|
|
649
|
-
} finally {
|
|
650
|
-
clearTimeout(timeoutId);
|
|
651
|
-
}
|
|
652
|
-
}
|
|
653
|
-
async function getSolPrice() {
|
|
654
|
-
const cacheTTL = config.cacheTTL ?? 6e4;
|
|
655
|
-
const timeout = config.timeout ?? 5e3;
|
|
656
|
-
if (cachedPrice && Date.now() - cachedPrice.fetchedAt.getTime() < cacheTTL) {
|
|
657
|
-
return cachedPrice;
|
|
658
|
-
}
|
|
659
|
-
if (config.customProvider) {
|
|
660
|
-
try {
|
|
661
|
-
const price = await config.customProvider();
|
|
662
|
-
if (price > 0) {
|
|
663
|
-
cachedPrice = {
|
|
664
|
-
solPrice: price,
|
|
665
|
-
fetchedAt: /* @__PURE__ */ new Date(),
|
|
666
|
-
source: "custom"
|
|
667
|
-
};
|
|
668
|
-
return cachedPrice;
|
|
669
|
-
}
|
|
670
|
-
} catch {
|
|
671
|
-
}
|
|
672
|
-
}
|
|
673
|
-
for (let i = 0; i < PROVIDERS.length; i++) {
|
|
674
|
-
const idx = (lastProviderIndex + 1 + i) % PROVIDERS.length;
|
|
675
|
-
const provider = PROVIDERS[idx];
|
|
676
|
-
try {
|
|
677
|
-
const price = await fetchFromProvider(provider, timeout);
|
|
678
|
-
lastProviderIndex = idx;
|
|
679
|
-
cachedPrice = {
|
|
680
|
-
solPrice: price,
|
|
681
|
-
fetchedAt: /* @__PURE__ */ new Date(),
|
|
682
|
-
source: provider.name
|
|
683
|
-
};
|
|
684
|
-
return cachedPrice;
|
|
685
|
-
} catch {
|
|
686
|
-
continue;
|
|
687
|
-
}
|
|
688
|
-
}
|
|
689
|
-
if (cachedPrice) {
|
|
690
|
-
return {
|
|
691
|
-
...cachedPrice,
|
|
692
|
-
source: `${cachedPrice.source} (stale)`
|
|
693
|
-
};
|
|
694
|
-
}
|
|
695
|
-
throw new Error(
|
|
696
|
-
"Failed to fetch SOL price from all providers. Configure a custom provider or ensure network connectivity."
|
|
697
|
-
);
|
|
698
|
-
}
|
|
699
|
-
async function lamportsToUsd(lamports) {
|
|
700
|
-
const { solPrice } = await getSolPrice();
|
|
701
|
-
const sol = Number(lamports) / 1e9;
|
|
702
|
-
return sol * solPrice;
|
|
703
|
-
}
|
|
704
|
-
async function usdToLamports(usd) {
|
|
705
|
-
const { solPrice } = await getSolPrice();
|
|
706
|
-
const sol = usd / solPrice;
|
|
707
|
-
return BigInt(Math.floor(sol * 1e9));
|
|
708
|
-
}
|
|
709
|
-
async function formatPriceDisplay(lamports) {
|
|
710
|
-
const { solPrice } = await getSolPrice();
|
|
711
|
-
const sol = Number(lamports) / 1e9;
|
|
712
|
-
const usd = sol * solPrice;
|
|
713
|
-
return `${sol.toFixed(4)} SOL (~$${usd.toFixed(2)})`;
|
|
714
|
-
}
|
|
715
|
-
function formatPriceSync(lamports, solPrice) {
|
|
716
|
-
const sol = Number(lamports) / 1e9;
|
|
717
|
-
const usd = sol * solPrice;
|
|
718
|
-
return {
|
|
719
|
-
sol,
|
|
720
|
-
usd,
|
|
721
|
-
formatted: `${sol.toFixed(4)} SOL (~$${usd.toFixed(2)})`
|
|
722
|
-
};
|
|
723
|
-
}
|
|
724
|
-
function clearPriceCache() {
|
|
725
|
-
cachedPrice = null;
|
|
726
|
-
lastProviderIndex = -1;
|
|
727
|
-
}
|
|
728
|
-
function getProviders() {
|
|
729
|
-
return PROVIDERS.map((p) => ({ name: p.name, url: p.url }));
|
|
730
|
-
}
|
|
731
|
-
|
|
732
852
|
exports.addCredits = addCredits;
|
|
733
853
|
exports.buildSolanaPayUrl = buildSolanaPayUrl;
|
|
734
854
|
exports.clearPriceCache = clearPriceCache;
|
|
@@ -752,7 +872,11 @@ exports.lamportsToUsd = lamportsToUsd;
|
|
|
752
872
|
exports.sendSolanaPayment = sendSolanaPayment;
|
|
753
873
|
exports.usdToLamports = usdToLamports;
|
|
754
874
|
exports.useCredit = useCredit;
|
|
875
|
+
exports.useFormatPrice = useFormatPrice;
|
|
876
|
+
exports.useLamportsToUsd = useLamportsToUsd;
|
|
877
|
+
exports.useMicropay = useMicropay;
|
|
755
878
|
exports.usePaywallResource = usePaywallResource;
|
|
879
|
+
exports.usePricing = usePricing;
|
|
756
880
|
exports.validateCreditSession = validateCreditSession;
|
|
757
881
|
Object.keys(core).forEach(function (k) {
|
|
758
882
|
if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
|
package/dist/index.d.cts
CHANGED
|
@@ -2,7 +2,7 @@ export * from '@x402/core';
|
|
|
2
2
|
export * from '@x402/core/types';
|
|
3
3
|
export * from '@x402/core/client';
|
|
4
4
|
export * from '@x402/svm';
|
|
5
|
-
export { PaymentFlowConfig, PaymentResult, PaywallConfig, PaywallState, SendPaymentParams, SolanaPayUrlParams, WalletAdapterInterface, buildSolanaPayUrl, createPaymentFlow, createPaymentReference, createX402AuthorizationHeader, sendSolanaPayment, usePaywallResource } from './client/index.cjs';
|
|
5
|
+
export { PaymentFlowConfig, PaymentResult, PaymentStatus, PaywallConfig, PaywallState, SendPaymentParams, SolanaPayUrlParams, WalletAdapterInterface, buildSolanaPayUrl, createPaymentFlow, createPaymentReference, createX402AuthorizationHeader, sendSolanaPayment, useFormatPrice, useLamportsToUsd, useMicropay, usePaywallResource, usePricing } from './client/index.cjs';
|
|
6
6
|
export { AgentPaymentResult, CreditSessionClaims, CreditSessionConfig, CreditSessionData, CreditValidation, ExecuteAgentPaymentParams, UseCreditResult, addCredits, createCreditSession, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession } from './agent/index.cjs';
|
|
7
7
|
export { CustomPriceProvider, PriceConfig, PriceData, clearPriceCache, configurePricing, formatPriceDisplay, formatPriceSync, getProviders, getSolPrice, lamportsToSol, lamportsToUsd, usdToLamports } from './pricing/index.cjs';
|
|
8
8
|
import '@solana/web3.js';
|
package/dist/index.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ export * from '@x402/core';
|
|
|
2
2
|
export * from '@x402/core/types';
|
|
3
3
|
export * from '@x402/core/client';
|
|
4
4
|
export * from '@x402/svm';
|
|
5
|
-
export { PaymentFlowConfig, PaymentResult, PaywallConfig, PaywallState, SendPaymentParams, SolanaPayUrlParams, WalletAdapterInterface, buildSolanaPayUrl, createPaymentFlow, createPaymentReference, createX402AuthorizationHeader, sendSolanaPayment, usePaywallResource } from './client/index.js';
|
|
5
|
+
export { PaymentFlowConfig, PaymentResult, PaymentStatus, PaywallConfig, PaywallState, SendPaymentParams, SolanaPayUrlParams, WalletAdapterInterface, buildSolanaPayUrl, createPaymentFlow, createPaymentReference, createX402AuthorizationHeader, sendSolanaPayment, useFormatPrice, useLamportsToUsd, useMicropay, usePaywallResource, usePricing } from './client/index.js';
|
|
6
6
|
export { AgentPaymentResult, CreditSessionClaims, CreditSessionConfig, CreditSessionData, CreditValidation, ExecuteAgentPaymentParams, UseCreditResult, addCredits, createCreditSession, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession } from './agent/index.js';
|
|
7
7
|
export { CustomPriceProvider, PriceConfig, PriceData, clearPriceCache, configurePricing, formatPriceDisplay, formatPriceSync, getProviders, getSolPrice, lamportsToSol, lamportsToUsd, usdToLamports } from './pricing/index.js';
|
|
8
8
|
import '@solana/web3.js';
|