@alleyboss/micropay-solana-x402-paywall 3.3.15 → 3.5.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.
@@ -218,4 +218,80 @@ declare function getRemainingCredits(token: string, secret: string): Promise<{
218
218
  bundleExpiry?: number;
219
219
  }>;
220
220
 
221
- export { type AgentPaymentResult, type CreditSessionClaims, type CreditSessionConfig, type CreditSessionData, type CreditValidation, type ExecuteAgentPaymentParams, type UseCreditResult, addCredits, createCreditSession, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession };
221
+ /**
222
+ * Supported Solana networks
223
+ */
224
+ declare const SOLANA_NETWORKS: readonly ["mainnet-beta", "devnet", "testnet"];
225
+ type SolanaNetwork = (typeof SOLANA_NETWORKS)[number];
226
+
227
+ /**
228
+ * @fileoverview Shaw-style Agent Helper
229
+ * The sexiest way to create a paying AI agent
230
+ *
231
+ * @example
232
+ * ```typescript
233
+ * import { createPayingAgent } from '@alleyboss/micropay-solana-x402-paywall/agent';
234
+ *
235
+ * const agent = createPayingAgent(process.env.SOLANA_PRIVATE_KEY!);
236
+ * const data = await agent.get('https://api.example.com/premium');
237
+ * ```
238
+ */
239
+
240
+ /**
241
+ * Configuration for creating a paying agent
242
+ */
243
+ interface PayingAgentConfig {
244
+ /** Network: 'mainnet-beta' | 'devnet' | 'testnet' */
245
+ network?: SolanaNetwork;
246
+ /** Custom RPC URL */
247
+ rpcUrl?: string;
248
+ /** Max payment per request in lamports (safety limit) */
249
+ maxPaymentPerRequest?: bigint;
250
+ /** Allowed recipient addresses (whitelist) */
251
+ allowedRecipients?: string[];
252
+ /** Enable priority fees for faster confirmation */
253
+ priorityFee?: boolean;
254
+ }
255
+ /**
256
+ * Paying agent interface - fetch-like methods with auto-payment
257
+ */
258
+ interface PayingAgent {
259
+ /** GET request with auto-payment */
260
+ get: (url: string, init?: RequestInit) => Promise<Response>;
261
+ /** POST request with auto-payment */
262
+ post: (url: string, body: unknown, init?: RequestInit) => Promise<Response>;
263
+ /** Generic fetch with auto-payment */
264
+ fetch: (url: string, init?: RequestInit) => Promise<Response>;
265
+ /** Get the agent's public key */
266
+ publicKey: string;
267
+ /** Get the agent's balance */
268
+ getBalance: () => Promise<{
269
+ lamports: bigint;
270
+ sol: number;
271
+ }>;
272
+ }
273
+ /**
274
+ * Create a paying AI agent - the sexiest one-liner for agent developers
275
+ *
276
+ * @param privateKey - Base58 or comma-separated Uint8Array string
277
+ * @param config - Optional configuration
278
+ * @returns PayingAgent with fetch-like methods
279
+ *
280
+ * @example
281
+ * ```typescript
282
+ * const agent = createPayingAgent(process.env.SOLANA_PRIVATE_KEY!);
283
+ *
284
+ * // Simple GET
285
+ * const response = await agent.get('https://api.example.com/premium');
286
+ *
287
+ * // POST with body
288
+ * const result = await agent.post('https://api.example.com/ai', { prompt: 'Hello' });
289
+ *
290
+ * // Check balance
291
+ * const { sol } = await agent.getBalance();
292
+ * console.log(`Agent has ${sol} SOL`);
293
+ * ```
294
+ */
295
+ declare function createPayingAgent(privateKey: string, config?: PayingAgentConfig): PayingAgent;
296
+
297
+ export { type AgentPaymentResult, type CreditSessionClaims, type CreditSessionConfig, type CreditSessionData, type CreditValidation, type ExecuteAgentPaymentParams, type PayingAgent, type PayingAgentConfig, type UseCreditResult, addCredits, createCreditSession, createPayingAgent, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession };
@@ -1,4 +1,4 @@
1
- import { PublicKey, SystemProgram, LAMPORTS_PER_SOL, Keypair, TransactionMessage, VersionedTransaction, ComputeBudgetProgram } from '@solana/web3.js';
1
+ import { PublicKey, SystemProgram, LAMPORTS_PER_SOL, Keypair, Connection, TransactionMessage, VersionedTransaction, ComputeBudgetProgram } from '@solana/web3.js';
2
2
  import bs58 from 'bs58';
3
3
  import { SignJWT, jwtVerify } from 'jose';
4
4
 
@@ -345,4 +345,435 @@ async function getRemainingCredits(token, secret) {
345
345
  };
346
346
  }
347
347
 
348
- export { addCredits, createCreditSession, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession };
348
+ // src/fetch/types.ts
349
+ var X402ErrorCode = {
350
+ /** User rejected the payment */
351
+ USER_REJECTED: "USER_REJECTED",
352
+ /** Insufficient wallet balance */
353
+ INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE",
354
+ /** Transaction failed on-chain */
355
+ TRANSACTION_FAILED: "TRANSACTION_FAILED",
356
+ /** Network/RPC error */
357
+ NETWORK_ERROR: "NETWORK_ERROR",
358
+ /** Invalid 402 response format */
359
+ INVALID_402_RESPONSE: "INVALID_402_RESPONSE",
360
+ /** Payment timeout */
361
+ TIMEOUT: "TIMEOUT",
362
+ /** Wallet not connected */
363
+ WALLET_NOT_CONNECTED: "WALLET_NOT_CONNECTED",
364
+ /** Payment amount exceeds maxPaymentPerRequest */
365
+ AMOUNT_EXCEEDS_LIMIT: "AMOUNT_EXCEEDS_LIMIT",
366
+ /** Recipient address not in allowedRecipients whitelist */
367
+ RECIPIENT_NOT_ALLOWED: "RECIPIENT_NOT_ALLOWED",
368
+ /** Rate limit exceeded */
369
+ RATE_LIMIT_EXCEEDED: "RATE_LIMIT_EXCEEDED"
370
+ };
371
+
372
+ // src/fetch/errors.ts
373
+ var X402PaymentError = class _X402PaymentError extends Error {
374
+ constructor(message, code, requirements, cause) {
375
+ super(message);
376
+ this.code = code;
377
+ this.requirements = requirements;
378
+ this.cause = cause;
379
+ if (Error.captureStackTrace) {
380
+ Error.captureStackTrace(this, _X402PaymentError);
381
+ }
382
+ }
383
+ name = "X402PaymentError";
384
+ /**
385
+ * Check if error is retryable
386
+ */
387
+ get isRetryable() {
388
+ const retryableCodes = [
389
+ X402ErrorCode.NETWORK_ERROR,
390
+ X402ErrorCode.TIMEOUT,
391
+ X402ErrorCode.TRANSACTION_FAILED
392
+ ];
393
+ return retryableCodes.includes(this.code);
394
+ }
395
+ /**
396
+ * Convert to JSON-serializable object
397
+ */
398
+ toJSON() {
399
+ return {
400
+ name: this.name,
401
+ message: this.message,
402
+ code: this.code,
403
+ requirements: this.requirements,
404
+ isRetryable: this.isRetryable
405
+ };
406
+ }
407
+ };
408
+ function userRejectedError(requirements) {
409
+ return new X402PaymentError(
410
+ "User rejected the payment request",
411
+ X402ErrorCode.USER_REJECTED,
412
+ requirements
413
+ );
414
+ }
415
+ function insufficientBalanceError(requirements, balance) {
416
+ return new X402PaymentError(
417
+ `Insufficient balance: have ${balance} lamports, need ${requirements.amount}`,
418
+ X402ErrorCode.INSUFFICIENT_BALANCE,
419
+ requirements
420
+ );
421
+ }
422
+ function transactionFailedError(requirements, cause) {
423
+ return new X402PaymentError(
424
+ `Transaction failed: ${cause?.message ?? "Unknown error"}`,
425
+ X402ErrorCode.TRANSACTION_FAILED,
426
+ requirements,
427
+ cause
428
+ );
429
+ }
430
+ function networkError(cause) {
431
+ return new X402PaymentError(
432
+ `Network error: ${cause?.message ?? "Connection failed"}`,
433
+ X402ErrorCode.NETWORK_ERROR,
434
+ void 0,
435
+ cause
436
+ );
437
+ }
438
+ function invalid402ResponseError(details) {
439
+ return new X402PaymentError(
440
+ `Invalid 402 response: ${details ?? "Missing or malformed payment requirements"}`,
441
+ X402ErrorCode.INVALID_402_RESPONSE
442
+ );
443
+ }
444
+ function timeoutError(requirements) {
445
+ return new X402PaymentError(
446
+ "Payment flow timed out",
447
+ X402ErrorCode.TIMEOUT,
448
+ requirements
449
+ );
450
+ }
451
+ function walletNotConnectedError() {
452
+ return new X402PaymentError(
453
+ "Wallet is not connected",
454
+ X402ErrorCode.WALLET_NOT_CONNECTED
455
+ );
456
+ }
457
+ function amountExceedsLimitError(requirements, limit) {
458
+ return new X402PaymentError(
459
+ `Payment amount ${requirements.amount} exceeds limit of ${limit} lamports`,
460
+ X402ErrorCode.AMOUNT_EXCEEDS_LIMIT,
461
+ requirements
462
+ );
463
+ }
464
+ function recipientNotAllowedError(requirements, recipient) {
465
+ return new X402PaymentError(
466
+ `Recipient ${recipient} is not in the allowed recipients list`,
467
+ X402ErrorCode.RECIPIENT_NOT_ALLOWED,
468
+ requirements
469
+ );
470
+ }
471
+ function rateLimitExceededError(limit, windowMs) {
472
+ return new X402PaymentError(
473
+ `Rate limit exceeded: max ${limit} payments per ${windowMs / 1e3}s`,
474
+ X402ErrorCode.RATE_LIMIT_EXCEEDED
475
+ );
476
+ }
477
+
478
+ // src/shared/constants.ts
479
+ var RPC_ENDPOINTS = {
480
+ "mainnet-beta": "https://api.mainnet-beta.solana.com",
481
+ "devnet": "https://api.devnet.solana.com",
482
+ "testnet": "https://api.testnet.solana.com"
483
+ };
484
+ var DEFAULT_CONFIRMATION_TIMEOUT = 3e4;
485
+ var DEFAULT_MAX_RETRIES = 3;
486
+ var DEFAULT_RATE_LIMIT_WINDOW_MS = 6e4;
487
+ var DEFAULT_RATE_LIMIT_MAX_PAYMENTS = 10;
488
+
489
+ // src/fetch/x402Fetch.ts
490
+ function isKeypair(wallet) {
491
+ return wallet instanceof Keypair;
492
+ }
493
+ function isWalletConnected(wallet) {
494
+ if (isKeypair(wallet)) return true;
495
+ return wallet.connected && wallet.publicKey != null;
496
+ }
497
+ function getPublicKey(wallet) {
498
+ if (isKeypair(wallet)) return wallet.publicKey;
499
+ if (!wallet.publicKey) throw walletNotConnectedError();
500
+ return wallet.publicKey;
501
+ }
502
+ function parse402Response(response) {
503
+ const x402Header = response.headers.get("X-Payment-Requirements");
504
+ if (x402Header) {
505
+ try {
506
+ const parsed = JSON.parse(x402Header);
507
+ return {
508
+ payTo: parsed.payTo ?? parsed.recipient,
509
+ amount: String(parsed.amount),
510
+ asset: parsed.asset ?? "SOL",
511
+ network: parsed.network ?? "solana-mainnet",
512
+ description: parsed.description,
513
+ resource: parsed.resource,
514
+ maxAge: parsed.maxAge
515
+ };
516
+ } catch {
517
+ throw invalid402ResponseError("Invalid X-Payment-Requirements header");
518
+ }
519
+ }
520
+ const wwwAuth = response.headers.get("WWW-Authenticate");
521
+ if (wwwAuth?.startsWith("X402")) {
522
+ try {
523
+ const base64Part = wwwAuth.slice(5).trim();
524
+ const jsonStr = atob(base64Part);
525
+ const parsed = JSON.parse(jsonStr);
526
+ return {
527
+ payTo: parsed.payTo ?? parsed.recipient,
528
+ amount: String(parsed.amount),
529
+ asset: parsed.asset ?? "SOL",
530
+ network: parsed.network ?? "solana-mainnet",
531
+ description: parsed.description,
532
+ resource: parsed.resource,
533
+ maxAge: parsed.maxAge
534
+ };
535
+ } catch {
536
+ throw invalid402ResponseError("Invalid WWW-Authenticate header");
537
+ }
538
+ }
539
+ throw invalid402ResponseError("No payment requirements found in 402 response");
540
+ }
541
+ function buildPaymentHeader(signature) {
542
+ const payload = {
543
+ x402Version: 2,
544
+ scheme: "exact",
545
+ payload: { signature }
546
+ };
547
+ return `X402 ${btoa(JSON.stringify(payload))}`;
548
+ }
549
+ function createX402Fetch(config) {
550
+ const {
551
+ wallet,
552
+ network = "mainnet-beta",
553
+ connection: providedConnection,
554
+ // Reserved for future facilitator integration
555
+ onPaymentRequired,
556
+ onPaymentSuccess,
557
+ onPaymentError,
558
+ priorityFee,
559
+ maxRetries = DEFAULT_MAX_RETRIES,
560
+ timeout = DEFAULT_CONFIRMATION_TIMEOUT,
561
+ // Security options
562
+ maxPaymentPerRequest,
563
+ allowedRecipients,
564
+ // UX options
565
+ commitment = "confirmed",
566
+ rateLimit
567
+ } = config;
568
+ const paymentTimestamps = [];
569
+ const rateLimitMax = rateLimit?.maxPayments ?? DEFAULT_RATE_LIMIT_MAX_PAYMENTS;
570
+ const rateLimitWindow = rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS;
571
+ function checkRateLimit() {
572
+ const now = Date.now();
573
+ while (paymentTimestamps.length > 0 && paymentTimestamps[0] < now - rateLimitWindow) {
574
+ paymentTimestamps.shift();
575
+ }
576
+ if (paymentTimestamps.length >= rateLimitMax) {
577
+ throw rateLimitExceededError(rateLimitMax, rateLimitWindow);
578
+ }
579
+ }
580
+ function recordPayment() {
581
+ paymentTimestamps.push(Date.now());
582
+ }
583
+ function validateSecurityRequirements(requirements) {
584
+ const amountLamports = BigInt(requirements.amount);
585
+ if (maxPaymentPerRequest !== void 0 && amountLamports > maxPaymentPerRequest) {
586
+ throw amountExceedsLimitError(requirements, maxPaymentPerRequest);
587
+ }
588
+ if (allowedRecipients !== void 0 && allowedRecipients.length > 0) {
589
+ if (!allowedRecipients.includes(requirements.payTo)) {
590
+ throw recipientNotAllowedError(requirements, requirements.payTo);
591
+ }
592
+ }
593
+ }
594
+ const connection = providedConnection ?? new Connection(RPC_ENDPOINTS[network], {
595
+ commitment
596
+ });
597
+ async function executePayment(requirements) {
598
+ const payer = getPublicKey(wallet);
599
+ const recipient = new PublicKey(requirements.payTo);
600
+ const amountLamports = BigInt(requirements.amount);
601
+ const balance = await connection.getBalance(payer);
602
+ if (BigInt(balance) < amountLamports) {
603
+ throw insufficientBalanceError(requirements, BigInt(balance));
604
+ }
605
+ const instructions = [];
606
+ if (priorityFee?.enabled) {
607
+ instructions.push(
608
+ ComputeBudgetProgram.setComputeUnitPrice({
609
+ microLamports: priorityFee.microLamports ?? 5e3
610
+ })
611
+ );
612
+ }
613
+ instructions.push(
614
+ SystemProgram.transfer({
615
+ fromPubkey: payer,
616
+ toPubkey: recipient,
617
+ lamports: amountLamports
618
+ })
619
+ );
620
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
621
+ const messageV0 = new TransactionMessage({
622
+ payerKey: payer,
623
+ recentBlockhash: blockhash,
624
+ instructions
625
+ }).compileToV0Message();
626
+ const tx = new VersionedTransaction(messageV0);
627
+ if (isKeypair(wallet)) {
628
+ tx.sign([wallet]);
629
+ } else {
630
+ const signerWallet = wallet;
631
+ if (!signerWallet.signTransaction) {
632
+ throw new X402PaymentError(
633
+ "Wallet does not support transaction signing. Use a SignerWalletAdapter.",
634
+ "WALLET_NOT_CONNECTED"
635
+ );
636
+ }
637
+ const signedTx = await signerWallet.signTransaction(tx);
638
+ if (signedTx.signatures[0]) {
639
+ tx.signatures[0] = signedTx.signatures[0];
640
+ }
641
+ }
642
+ const signature = await connection.sendTransaction(tx, {
643
+ maxRetries
644
+ });
645
+ await connection.confirmTransaction({
646
+ signature,
647
+ blockhash,
648
+ lastValidBlockHeight
649
+ }, commitment);
650
+ return signature;
651
+ }
652
+ async function x402Fetch(input, init) {
653
+ const { skipPayment, paymentOverride, ...fetchInit } = init ?? {};
654
+ let response;
655
+ try {
656
+ response = await fetch(input, fetchInit);
657
+ } catch (error) {
658
+ throw networkError(error instanceof Error ? error : void 0);
659
+ }
660
+ if (response.status !== 402) {
661
+ return response;
662
+ }
663
+ if (skipPayment) {
664
+ return response;
665
+ }
666
+ if (!isWalletConnected(wallet)) {
667
+ throw walletNotConnectedError();
668
+ }
669
+ let requirements;
670
+ try {
671
+ requirements = parse402Response(response);
672
+ if (paymentOverride) {
673
+ requirements = { ...requirements, ...paymentOverride };
674
+ }
675
+ } catch (error) {
676
+ if (error instanceof X402PaymentError) throw error;
677
+ throw invalid402ResponseError(error instanceof Error ? error.message : void 0);
678
+ }
679
+ validateSecurityRequirements(requirements);
680
+ checkRateLimit();
681
+ if (onPaymentRequired) {
682
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
683
+ const shouldProceed = await onPaymentRequired(requirements, url);
684
+ if (!shouldProceed) {
685
+ throw userRejectedError(requirements);
686
+ }
687
+ }
688
+ let signature;
689
+ try {
690
+ const paymentPromise = executePayment(requirements);
691
+ const timeoutPromise = new Promise((_, reject) => {
692
+ setTimeout(() => reject(timeoutError(requirements)), timeout);
693
+ });
694
+ signature = await Promise.race([paymentPromise, timeoutPromise]);
695
+ recordPayment();
696
+ if (onPaymentSuccess) {
697
+ await onPaymentSuccess(signature, requirements);
698
+ }
699
+ } catch (error) {
700
+ if (error instanceof X402PaymentError) {
701
+ if (onPaymentError) {
702
+ await onPaymentError(error, requirements);
703
+ }
704
+ throw error;
705
+ }
706
+ const wrappedError = transactionFailedError(
707
+ requirements,
708
+ error instanceof Error ? error : void 0
709
+ );
710
+ if (onPaymentError) {
711
+ await onPaymentError(wrappedError, requirements);
712
+ }
713
+ throw wrappedError;
714
+ }
715
+ const retryHeaders = new Headers(fetchInit?.headers);
716
+ retryHeaders.set("Authorization", buildPaymentHeader(signature));
717
+ try {
718
+ return await fetch(input, {
719
+ ...fetchInit,
720
+ headers: retryHeaders
721
+ });
722
+ } catch (error) {
723
+ throw networkError(error instanceof Error ? error : void 0);
724
+ }
725
+ }
726
+ return x402Fetch;
727
+ }
728
+
729
+ // src/agent/payingAgent.ts
730
+ function createPayingAgent(privateKey, config = {}) {
731
+ const {
732
+ network = "mainnet-beta",
733
+ rpcUrl,
734
+ maxPaymentPerRequest,
735
+ allowedRecipients,
736
+ priorityFee = true
737
+ } = config;
738
+ let keypair;
739
+ if (privateKey.includes(",")) {
740
+ const bytes = new Uint8Array(privateKey.split(",").map((n) => parseInt(n.trim(), 10)));
741
+ keypair = Keypair.fromSecretKey(bytes);
742
+ } else {
743
+ keypair = Keypair.fromSecretKey(bs58.decode(privateKey));
744
+ }
745
+ const endpoint = rpcUrl ?? RPC_ENDPOINTS[network];
746
+ const connection = new Connection(endpoint, "confirmed");
747
+ const fetchConfig = {
748
+ wallet: keypair,
749
+ network,
750
+ connection,
751
+ maxPaymentPerRequest,
752
+ allowedRecipients,
753
+ priorityFee: priorityFee ? { enabled: true, microLamports: 5e3 } : void 0
754
+ };
755
+ const x402Fetch = createX402Fetch(fetchConfig);
756
+ return {
757
+ get: (url, init) => x402Fetch(url, { ...init, method: "GET" }),
758
+ post: (url, body, init) => x402Fetch(url, {
759
+ ...init,
760
+ method: "POST",
761
+ body: JSON.stringify(body),
762
+ headers: {
763
+ "Content-Type": "application/json",
764
+ ...init?.headers
765
+ }
766
+ }),
767
+ fetch: (url, init) => x402Fetch(url, init),
768
+ publicKey: keypair.publicKey.toBase58(),
769
+ getBalance: async () => {
770
+ const lamports = await connection.getBalance(keypair.publicKey);
771
+ return {
772
+ lamports: BigInt(lamports),
773
+ sol: lamports / 1e9
774
+ };
775
+ }
776
+ };
777
+ }
778
+
779
+ export { addCredits, createCreditSession, createPayingAgent, executeAgentPayment, generateAgentKeypair, getAgentBalance, getRemainingCredits, hasAgentSufficientBalance, keypairFromBase58, useCredit, validateCreditSession };