@alleyboss/micropay-solana-x402-paywall 3.5.0 → 3.5.2
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 +38 -0
- package/dist/agent/index.cjs +451 -0
- package/dist/agent/index.d.cts +77 -1
- package/dist/agent/index.d.ts +77 -1
- package/dist/agent/index.js +452 -2
- package/dist/fetch/index.cjs +19 -0
- package/dist/fetch/index.js +19 -0
- package/dist/index.cjs +451 -0
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +451 -1
- package/dist/next/index.cjs +29 -45
- package/dist/next/index.d.cts +1 -1
- package/dist/next/index.d.ts +1 -1
- package/dist/next/index.js +29 -45
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -117,6 +117,12 @@ const x402Fetch = createX402Fetch({
|
|
|
117
117
|
windowMs: 60_000, // Per minute
|
|
118
118
|
},
|
|
119
119
|
});
|
|
120
|
+
|
|
121
|
+
// 💡 Header Compatibility:
|
|
122
|
+
// Automatically detects requirements from:
|
|
123
|
+
// - WWW-Authenticate: X402 ... (Standard)
|
|
124
|
+
// - X-Payment-Requirements: json (Simple)
|
|
125
|
+
// - payment-required: base64 (Upstream Middleware)
|
|
120
126
|
```
|
|
121
127
|
|
|
122
128
|
**Security Error Codes:**
|
|
@@ -229,6 +235,19 @@ const withMicropay = createX402Middleware({
|
|
|
229
235
|
| **Setup** | Zero-config | Requires RPC URL |
|
|
230
236
|
| **Best For** | Quick startups, MVPs | Production, High-Volume, Agents |
|
|
231
237
|
|
|
238
|
+
## 🔧 What's New in v3.5.2
|
|
239
|
+
|
|
240
|
+
**Middleware Fix**: The `createX402Middleware` now generates 402 responses directly, fixing a bug where the upstream library multiplied payment amounts by 1M. Your configured `price` in lamports is now used exactly as specified.
|
|
241
|
+
|
|
242
|
+
```typescript
|
|
243
|
+
// price: '1000000' → 0.001 SOL (correct!)
|
|
244
|
+
const withPayment = createX402Middleware({
|
|
245
|
+
walletAddress: 'YOUR_WALLET',
|
|
246
|
+
price: '1000000', // This is now used correctly
|
|
247
|
+
network: 'devnet'
|
|
248
|
+
});
|
|
249
|
+
```
|
|
250
|
+
|
|
232
251
|
## 🌐 PayAI Format Support (New in v3.3.13)
|
|
233
252
|
|
|
234
253
|
Native support for the **PayAI payment format** - a universal payment protocol that works across Solana, Ethereum, Base, and other chains.
|
|
@@ -298,6 +317,25 @@ flowchart LR
|
|
|
298
317
|
F --> G((Unlock Data))
|
|
299
318
|
```
|
|
300
319
|
|
|
320
|
+
### ⚡ The Sexy Way (New in v3.5.1)
|
|
321
|
+
|
|
322
|
+
```typescript
|
|
323
|
+
import { createPayingAgent } from '@alleyboss/micropay-solana-x402-paywall/agent';
|
|
324
|
+
|
|
325
|
+
// One liner - that's it!
|
|
326
|
+
const agent = createPayingAgent(process.env.SOLANA_PRIVATE_KEY!);
|
|
327
|
+
|
|
328
|
+
// Fetch with auto-payment
|
|
329
|
+
const response = await agent.get('https://api.example.com/premium');
|
|
330
|
+
const data = await response.json();
|
|
331
|
+
|
|
332
|
+
// Check balance
|
|
333
|
+
const { sol } = await agent.getBalance();
|
|
334
|
+
console.log(`Agent has ${sol} SOL`);
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
### The Verbose Way (Full Control)
|
|
338
|
+
|
|
301
339
|
```typescript
|
|
302
340
|
import { executeAgentPayment } from '@alleyboss/micropay-solana-x402-paywall/agent';
|
|
303
341
|
import { Keypair, Connection } from '@solana/web3.js';
|
package/dist/agent/index.cjs
CHANGED
|
@@ -351,8 +351,459 @@ async function getRemainingCredits(token, secret) {
|
|
|
351
351
|
};
|
|
352
352
|
}
|
|
353
353
|
|
|
354
|
+
// src/fetch/types.ts
|
|
355
|
+
var X402ErrorCode = {
|
|
356
|
+
/** User rejected the payment */
|
|
357
|
+
USER_REJECTED: "USER_REJECTED",
|
|
358
|
+
/** Insufficient wallet balance */
|
|
359
|
+
INSUFFICIENT_BALANCE: "INSUFFICIENT_BALANCE",
|
|
360
|
+
/** Transaction failed on-chain */
|
|
361
|
+
TRANSACTION_FAILED: "TRANSACTION_FAILED",
|
|
362
|
+
/** Network/RPC error */
|
|
363
|
+
NETWORK_ERROR: "NETWORK_ERROR",
|
|
364
|
+
/** Invalid 402 response format */
|
|
365
|
+
INVALID_402_RESPONSE: "INVALID_402_RESPONSE",
|
|
366
|
+
/** Payment timeout */
|
|
367
|
+
TIMEOUT: "TIMEOUT",
|
|
368
|
+
/** Wallet not connected */
|
|
369
|
+
WALLET_NOT_CONNECTED: "WALLET_NOT_CONNECTED",
|
|
370
|
+
/** Payment amount exceeds maxPaymentPerRequest */
|
|
371
|
+
AMOUNT_EXCEEDS_LIMIT: "AMOUNT_EXCEEDS_LIMIT",
|
|
372
|
+
/** Recipient address not in allowedRecipients whitelist */
|
|
373
|
+
RECIPIENT_NOT_ALLOWED: "RECIPIENT_NOT_ALLOWED",
|
|
374
|
+
/** Rate limit exceeded */
|
|
375
|
+
RATE_LIMIT_EXCEEDED: "RATE_LIMIT_EXCEEDED"
|
|
376
|
+
};
|
|
377
|
+
|
|
378
|
+
// src/fetch/errors.ts
|
|
379
|
+
var X402PaymentError = class _X402PaymentError extends Error {
|
|
380
|
+
constructor(message, code, requirements, cause) {
|
|
381
|
+
super(message);
|
|
382
|
+
this.code = code;
|
|
383
|
+
this.requirements = requirements;
|
|
384
|
+
this.cause = cause;
|
|
385
|
+
if (Error.captureStackTrace) {
|
|
386
|
+
Error.captureStackTrace(this, _X402PaymentError);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
name = "X402PaymentError";
|
|
390
|
+
/**
|
|
391
|
+
* Check if error is retryable
|
|
392
|
+
*/
|
|
393
|
+
get isRetryable() {
|
|
394
|
+
const retryableCodes = [
|
|
395
|
+
X402ErrorCode.NETWORK_ERROR,
|
|
396
|
+
X402ErrorCode.TIMEOUT,
|
|
397
|
+
X402ErrorCode.TRANSACTION_FAILED
|
|
398
|
+
];
|
|
399
|
+
return retryableCodes.includes(this.code);
|
|
400
|
+
}
|
|
401
|
+
/**
|
|
402
|
+
* Convert to JSON-serializable object
|
|
403
|
+
*/
|
|
404
|
+
toJSON() {
|
|
405
|
+
return {
|
|
406
|
+
name: this.name,
|
|
407
|
+
message: this.message,
|
|
408
|
+
code: this.code,
|
|
409
|
+
requirements: this.requirements,
|
|
410
|
+
isRetryable: this.isRetryable
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
};
|
|
414
|
+
function userRejectedError(requirements) {
|
|
415
|
+
return new X402PaymentError(
|
|
416
|
+
"User rejected the payment request",
|
|
417
|
+
X402ErrorCode.USER_REJECTED,
|
|
418
|
+
requirements
|
|
419
|
+
);
|
|
420
|
+
}
|
|
421
|
+
function insufficientBalanceError(requirements, balance) {
|
|
422
|
+
return new X402PaymentError(
|
|
423
|
+
`Insufficient balance: have ${balance} lamports, need ${requirements.amount}`,
|
|
424
|
+
X402ErrorCode.INSUFFICIENT_BALANCE,
|
|
425
|
+
requirements
|
|
426
|
+
);
|
|
427
|
+
}
|
|
428
|
+
function transactionFailedError(requirements, cause) {
|
|
429
|
+
return new X402PaymentError(
|
|
430
|
+
`Transaction failed: ${cause?.message ?? "Unknown error"}`,
|
|
431
|
+
X402ErrorCode.TRANSACTION_FAILED,
|
|
432
|
+
requirements,
|
|
433
|
+
cause
|
|
434
|
+
);
|
|
435
|
+
}
|
|
436
|
+
function networkError(cause) {
|
|
437
|
+
return new X402PaymentError(
|
|
438
|
+
`Network error: ${cause?.message ?? "Connection failed"}`,
|
|
439
|
+
X402ErrorCode.NETWORK_ERROR,
|
|
440
|
+
void 0,
|
|
441
|
+
cause
|
|
442
|
+
);
|
|
443
|
+
}
|
|
444
|
+
function invalid402ResponseError(details) {
|
|
445
|
+
return new X402PaymentError(
|
|
446
|
+
`Invalid 402 response: ${details ?? "Missing or malformed payment requirements"}`,
|
|
447
|
+
X402ErrorCode.INVALID_402_RESPONSE
|
|
448
|
+
);
|
|
449
|
+
}
|
|
450
|
+
function timeoutError(requirements) {
|
|
451
|
+
return new X402PaymentError(
|
|
452
|
+
"Payment flow timed out",
|
|
453
|
+
X402ErrorCode.TIMEOUT,
|
|
454
|
+
requirements
|
|
455
|
+
);
|
|
456
|
+
}
|
|
457
|
+
function walletNotConnectedError() {
|
|
458
|
+
return new X402PaymentError(
|
|
459
|
+
"Wallet is not connected",
|
|
460
|
+
X402ErrorCode.WALLET_NOT_CONNECTED
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
function amountExceedsLimitError(requirements, limit) {
|
|
464
|
+
return new X402PaymentError(
|
|
465
|
+
`Payment amount ${requirements.amount} exceeds limit of ${limit} lamports`,
|
|
466
|
+
X402ErrorCode.AMOUNT_EXCEEDS_LIMIT,
|
|
467
|
+
requirements
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
function recipientNotAllowedError(requirements, recipient) {
|
|
471
|
+
return new X402PaymentError(
|
|
472
|
+
`Recipient ${recipient} is not in the allowed recipients list`,
|
|
473
|
+
X402ErrorCode.RECIPIENT_NOT_ALLOWED,
|
|
474
|
+
requirements
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
function rateLimitExceededError(limit, windowMs) {
|
|
478
|
+
return new X402PaymentError(
|
|
479
|
+
`Rate limit exceeded: max ${limit} payments per ${windowMs / 1e3}s`,
|
|
480
|
+
X402ErrorCode.RATE_LIMIT_EXCEEDED
|
|
481
|
+
);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// src/shared/constants.ts
|
|
485
|
+
var RPC_ENDPOINTS = {
|
|
486
|
+
"mainnet-beta": "https://api.mainnet-beta.solana.com",
|
|
487
|
+
"devnet": "https://api.devnet.solana.com",
|
|
488
|
+
"testnet": "https://api.testnet.solana.com"
|
|
489
|
+
};
|
|
490
|
+
var DEFAULT_CONFIRMATION_TIMEOUT = 3e4;
|
|
491
|
+
var DEFAULT_MAX_RETRIES = 3;
|
|
492
|
+
var DEFAULT_RATE_LIMIT_WINDOW_MS = 6e4;
|
|
493
|
+
var DEFAULT_RATE_LIMIT_MAX_PAYMENTS = 10;
|
|
494
|
+
|
|
495
|
+
// src/fetch/x402Fetch.ts
|
|
496
|
+
function isKeypair(wallet) {
|
|
497
|
+
return wallet instanceof web3_js.Keypair;
|
|
498
|
+
}
|
|
499
|
+
function isWalletConnected(wallet) {
|
|
500
|
+
if (isKeypair(wallet)) return true;
|
|
501
|
+
return wallet.connected && wallet.publicKey != null;
|
|
502
|
+
}
|
|
503
|
+
function getPublicKey(wallet) {
|
|
504
|
+
if (isKeypair(wallet)) return wallet.publicKey;
|
|
505
|
+
if (!wallet.publicKey) throw walletNotConnectedError();
|
|
506
|
+
return wallet.publicKey;
|
|
507
|
+
}
|
|
508
|
+
function parse402Response(response) {
|
|
509
|
+
const x402Header = response.headers.get("X-Payment-Requirements");
|
|
510
|
+
if (x402Header) {
|
|
511
|
+
try {
|
|
512
|
+
const parsed = JSON.parse(x402Header);
|
|
513
|
+
return {
|
|
514
|
+
payTo: parsed.payTo ?? parsed.recipient,
|
|
515
|
+
amount: String(parsed.amount),
|
|
516
|
+
asset: parsed.asset ?? "SOL",
|
|
517
|
+
network: parsed.network ?? "solana-mainnet",
|
|
518
|
+
description: parsed.description,
|
|
519
|
+
resource: parsed.resource,
|
|
520
|
+
maxAge: parsed.maxAge
|
|
521
|
+
};
|
|
522
|
+
} catch {
|
|
523
|
+
throw invalid402ResponseError("Invalid X-Payment-Requirements header");
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
const wwwAuth = response.headers.get("WWW-Authenticate");
|
|
527
|
+
if (wwwAuth?.startsWith("X402")) {
|
|
528
|
+
try {
|
|
529
|
+
const base64Part = wwwAuth.slice(5).trim();
|
|
530
|
+
const jsonStr = atob(base64Part);
|
|
531
|
+
const parsed = JSON.parse(jsonStr);
|
|
532
|
+
return {
|
|
533
|
+
payTo: parsed.payTo ?? parsed.recipient,
|
|
534
|
+
amount: String(parsed.amount),
|
|
535
|
+
asset: parsed.asset ?? "SOL",
|
|
536
|
+
network: parsed.network ?? "solana-mainnet",
|
|
537
|
+
description: parsed.description,
|
|
538
|
+
resource: parsed.resource,
|
|
539
|
+
maxAge: parsed.maxAge
|
|
540
|
+
};
|
|
541
|
+
} catch {
|
|
542
|
+
throw invalid402ResponseError("Invalid WWW-Authenticate header");
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
const paymentRequired = response.headers.get("payment-required");
|
|
546
|
+
if (paymentRequired) {
|
|
547
|
+
try {
|
|
548
|
+
const jsonStr = atob(paymentRequired.trim());
|
|
549
|
+
const parsed = JSON.parse(jsonStr);
|
|
550
|
+
const option = Array.isArray(parsed.accepts) && parsed.accepts.length > 0 ? parsed.accepts[0] : parsed;
|
|
551
|
+
return {
|
|
552
|
+
payTo: option.payTo ?? option.recipient,
|
|
553
|
+
amount: String(option.amount),
|
|
554
|
+
asset: option.asset ?? "SOL",
|
|
555
|
+
network: option.network ?? "solana-mainnet",
|
|
556
|
+
description: parsed.description ?? option.description,
|
|
557
|
+
resource: parsed.resource ?? option.resource,
|
|
558
|
+
maxAge: parsed.maxAge ?? option.maxAge
|
|
559
|
+
};
|
|
560
|
+
} catch {
|
|
561
|
+
throw invalid402ResponseError("Invalid payment-required header");
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
throw invalid402ResponseError("No payment requirements found in 402 response");
|
|
565
|
+
}
|
|
566
|
+
function buildPaymentHeader(signature) {
|
|
567
|
+
const payload = {
|
|
568
|
+
x402Version: 2,
|
|
569
|
+
scheme: "exact",
|
|
570
|
+
payload: { signature }
|
|
571
|
+
};
|
|
572
|
+
return `X402 ${btoa(JSON.stringify(payload))}`;
|
|
573
|
+
}
|
|
574
|
+
function createX402Fetch(config) {
|
|
575
|
+
const {
|
|
576
|
+
wallet,
|
|
577
|
+
network = "mainnet-beta",
|
|
578
|
+
connection: providedConnection,
|
|
579
|
+
// Reserved for future facilitator integration
|
|
580
|
+
onPaymentRequired,
|
|
581
|
+
onPaymentSuccess,
|
|
582
|
+
onPaymentError,
|
|
583
|
+
priorityFee,
|
|
584
|
+
maxRetries = DEFAULT_MAX_RETRIES,
|
|
585
|
+
timeout = DEFAULT_CONFIRMATION_TIMEOUT,
|
|
586
|
+
// Security options
|
|
587
|
+
maxPaymentPerRequest,
|
|
588
|
+
allowedRecipients,
|
|
589
|
+
// UX options
|
|
590
|
+
commitment = "confirmed",
|
|
591
|
+
rateLimit
|
|
592
|
+
} = config;
|
|
593
|
+
const paymentTimestamps = [];
|
|
594
|
+
const rateLimitMax = rateLimit?.maxPayments ?? DEFAULT_RATE_LIMIT_MAX_PAYMENTS;
|
|
595
|
+
const rateLimitWindow = rateLimit?.windowMs ?? DEFAULT_RATE_LIMIT_WINDOW_MS;
|
|
596
|
+
function checkRateLimit() {
|
|
597
|
+
const now = Date.now();
|
|
598
|
+
while (paymentTimestamps.length > 0 && paymentTimestamps[0] < now - rateLimitWindow) {
|
|
599
|
+
paymentTimestamps.shift();
|
|
600
|
+
}
|
|
601
|
+
if (paymentTimestamps.length >= rateLimitMax) {
|
|
602
|
+
throw rateLimitExceededError(rateLimitMax, rateLimitWindow);
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
function recordPayment() {
|
|
606
|
+
paymentTimestamps.push(Date.now());
|
|
607
|
+
}
|
|
608
|
+
function validateSecurityRequirements(requirements) {
|
|
609
|
+
const amountLamports = BigInt(requirements.amount);
|
|
610
|
+
if (maxPaymentPerRequest !== void 0 && amountLamports > maxPaymentPerRequest) {
|
|
611
|
+
throw amountExceedsLimitError(requirements, maxPaymentPerRequest);
|
|
612
|
+
}
|
|
613
|
+
if (allowedRecipients !== void 0 && allowedRecipients.length > 0) {
|
|
614
|
+
if (!allowedRecipients.includes(requirements.payTo)) {
|
|
615
|
+
throw recipientNotAllowedError(requirements, requirements.payTo);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
const connection = providedConnection ?? new web3_js.Connection(RPC_ENDPOINTS[network], {
|
|
620
|
+
commitment
|
|
621
|
+
});
|
|
622
|
+
async function executePayment(requirements) {
|
|
623
|
+
const payer = getPublicKey(wallet);
|
|
624
|
+
const recipient = new web3_js.PublicKey(requirements.payTo);
|
|
625
|
+
const amountLamports = BigInt(requirements.amount);
|
|
626
|
+
const balance = await connection.getBalance(payer);
|
|
627
|
+
if (BigInt(balance) < amountLamports) {
|
|
628
|
+
throw insufficientBalanceError(requirements, BigInt(balance));
|
|
629
|
+
}
|
|
630
|
+
const instructions = [];
|
|
631
|
+
if (priorityFee?.enabled) {
|
|
632
|
+
instructions.push(
|
|
633
|
+
web3_js.ComputeBudgetProgram.setComputeUnitPrice({
|
|
634
|
+
microLamports: priorityFee.microLamports ?? 5e3
|
|
635
|
+
})
|
|
636
|
+
);
|
|
637
|
+
}
|
|
638
|
+
instructions.push(
|
|
639
|
+
web3_js.SystemProgram.transfer({
|
|
640
|
+
fromPubkey: payer,
|
|
641
|
+
toPubkey: recipient,
|
|
642
|
+
lamports: amountLamports
|
|
643
|
+
})
|
|
644
|
+
);
|
|
645
|
+
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
|
|
646
|
+
const messageV0 = new web3_js.TransactionMessage({
|
|
647
|
+
payerKey: payer,
|
|
648
|
+
recentBlockhash: blockhash,
|
|
649
|
+
instructions
|
|
650
|
+
}).compileToV0Message();
|
|
651
|
+
const tx = new web3_js.VersionedTransaction(messageV0);
|
|
652
|
+
if (isKeypair(wallet)) {
|
|
653
|
+
tx.sign([wallet]);
|
|
654
|
+
} else {
|
|
655
|
+
const signerWallet = wallet;
|
|
656
|
+
if (!signerWallet.signTransaction) {
|
|
657
|
+
throw new X402PaymentError(
|
|
658
|
+
"Wallet does not support transaction signing. Use a SignerWalletAdapter.",
|
|
659
|
+
"WALLET_NOT_CONNECTED"
|
|
660
|
+
);
|
|
661
|
+
}
|
|
662
|
+
const signedTx = await signerWallet.signTransaction(tx);
|
|
663
|
+
if (signedTx.signatures[0]) {
|
|
664
|
+
tx.signatures[0] = signedTx.signatures[0];
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
const signature = await connection.sendTransaction(tx, {
|
|
668
|
+
maxRetries
|
|
669
|
+
});
|
|
670
|
+
await connection.confirmTransaction({
|
|
671
|
+
signature,
|
|
672
|
+
blockhash,
|
|
673
|
+
lastValidBlockHeight
|
|
674
|
+
}, commitment);
|
|
675
|
+
return signature;
|
|
676
|
+
}
|
|
677
|
+
async function x402Fetch(input, init) {
|
|
678
|
+
const { skipPayment, paymentOverride, ...fetchInit } = init ?? {};
|
|
679
|
+
let response;
|
|
680
|
+
try {
|
|
681
|
+
response = await fetch(input, fetchInit);
|
|
682
|
+
} catch (error) {
|
|
683
|
+
throw networkError(error instanceof Error ? error : void 0);
|
|
684
|
+
}
|
|
685
|
+
if (response.status !== 402) {
|
|
686
|
+
return response;
|
|
687
|
+
}
|
|
688
|
+
if (skipPayment) {
|
|
689
|
+
return response;
|
|
690
|
+
}
|
|
691
|
+
if (!isWalletConnected(wallet)) {
|
|
692
|
+
throw walletNotConnectedError();
|
|
693
|
+
}
|
|
694
|
+
let requirements;
|
|
695
|
+
try {
|
|
696
|
+
requirements = parse402Response(response);
|
|
697
|
+
if (paymentOverride) {
|
|
698
|
+
requirements = { ...requirements, ...paymentOverride };
|
|
699
|
+
}
|
|
700
|
+
} catch (error) {
|
|
701
|
+
if (error instanceof X402PaymentError) throw error;
|
|
702
|
+
throw invalid402ResponseError(error instanceof Error ? error.message : void 0);
|
|
703
|
+
}
|
|
704
|
+
validateSecurityRequirements(requirements);
|
|
705
|
+
checkRateLimit();
|
|
706
|
+
if (onPaymentRequired) {
|
|
707
|
+
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
|
|
708
|
+
const shouldProceed = await onPaymentRequired(requirements, url);
|
|
709
|
+
if (!shouldProceed) {
|
|
710
|
+
throw userRejectedError(requirements);
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
let signature;
|
|
714
|
+
try {
|
|
715
|
+
const paymentPromise = executePayment(requirements);
|
|
716
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
717
|
+
setTimeout(() => reject(timeoutError(requirements)), timeout);
|
|
718
|
+
});
|
|
719
|
+
signature = await Promise.race([paymentPromise, timeoutPromise]);
|
|
720
|
+
recordPayment();
|
|
721
|
+
if (onPaymentSuccess) {
|
|
722
|
+
await onPaymentSuccess(signature, requirements);
|
|
723
|
+
}
|
|
724
|
+
} catch (error) {
|
|
725
|
+
if (error instanceof X402PaymentError) {
|
|
726
|
+
if (onPaymentError) {
|
|
727
|
+
await onPaymentError(error, requirements);
|
|
728
|
+
}
|
|
729
|
+
throw error;
|
|
730
|
+
}
|
|
731
|
+
const wrappedError = transactionFailedError(
|
|
732
|
+
requirements,
|
|
733
|
+
error instanceof Error ? error : void 0
|
|
734
|
+
);
|
|
735
|
+
if (onPaymentError) {
|
|
736
|
+
await onPaymentError(wrappedError, requirements);
|
|
737
|
+
}
|
|
738
|
+
throw wrappedError;
|
|
739
|
+
}
|
|
740
|
+
const retryHeaders = new Headers(fetchInit?.headers);
|
|
741
|
+
retryHeaders.set("Authorization", buildPaymentHeader(signature));
|
|
742
|
+
try {
|
|
743
|
+
return await fetch(input, {
|
|
744
|
+
...fetchInit,
|
|
745
|
+
headers: retryHeaders
|
|
746
|
+
});
|
|
747
|
+
} catch (error) {
|
|
748
|
+
throw networkError(error instanceof Error ? error : void 0);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
return x402Fetch;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// src/agent/payingAgent.ts
|
|
755
|
+
function createPayingAgent(privateKey, config = {}) {
|
|
756
|
+
const {
|
|
757
|
+
network = "mainnet-beta",
|
|
758
|
+
rpcUrl,
|
|
759
|
+
maxPaymentPerRequest,
|
|
760
|
+
allowedRecipients,
|
|
761
|
+
priorityFee = true
|
|
762
|
+
} = config;
|
|
763
|
+
let keypair;
|
|
764
|
+
if (privateKey.includes(",")) {
|
|
765
|
+
const bytes = new Uint8Array(privateKey.split(",").map((n) => parseInt(n.trim(), 10)));
|
|
766
|
+
keypair = web3_js.Keypair.fromSecretKey(bytes);
|
|
767
|
+
} else {
|
|
768
|
+
keypair = web3_js.Keypair.fromSecretKey(bs58__default.default.decode(privateKey));
|
|
769
|
+
}
|
|
770
|
+
const endpoint = rpcUrl ?? RPC_ENDPOINTS[network];
|
|
771
|
+
const connection = new web3_js.Connection(endpoint, "confirmed");
|
|
772
|
+
const fetchConfig = {
|
|
773
|
+
wallet: keypair,
|
|
774
|
+
network,
|
|
775
|
+
connection,
|
|
776
|
+
maxPaymentPerRequest,
|
|
777
|
+
allowedRecipients,
|
|
778
|
+
priorityFee: priorityFee ? { enabled: true, microLamports: 5e3 } : void 0
|
|
779
|
+
};
|
|
780
|
+
const x402Fetch = createX402Fetch(fetchConfig);
|
|
781
|
+
return {
|
|
782
|
+
get: (url, init) => x402Fetch(url, { ...init, method: "GET" }),
|
|
783
|
+
post: (url, body, init) => x402Fetch(url, {
|
|
784
|
+
...init,
|
|
785
|
+
method: "POST",
|
|
786
|
+
body: JSON.stringify(body),
|
|
787
|
+
headers: {
|
|
788
|
+
"Content-Type": "application/json",
|
|
789
|
+
...init?.headers
|
|
790
|
+
}
|
|
791
|
+
}),
|
|
792
|
+
fetch: (url, init) => x402Fetch(url, init),
|
|
793
|
+
publicKey: keypair.publicKey.toBase58(),
|
|
794
|
+
getBalance: async () => {
|
|
795
|
+
const lamports = await connection.getBalance(keypair.publicKey);
|
|
796
|
+
return {
|
|
797
|
+
lamports: BigInt(lamports),
|
|
798
|
+
sol: lamports / 1e9
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
}
|
|
803
|
+
|
|
354
804
|
exports.addCredits = addCredits;
|
|
355
805
|
exports.createCreditSession = createCreditSession;
|
|
806
|
+
exports.createPayingAgent = createPayingAgent;
|
|
356
807
|
exports.executeAgentPayment = executeAgentPayment;
|
|
357
808
|
exports.generateAgentKeypair = generateAgentKeypair;
|
|
358
809
|
exports.getAgentBalance = getAgentBalance;
|
package/dist/agent/index.d.cts
CHANGED
|
@@ -218,4 +218,80 @@ declare function getRemainingCredits(token: string, secret: string): Promise<{
|
|
|
218
218
|
bundleExpiry?: number;
|
|
219
219
|
}>;
|
|
220
220
|
|
|
221
|
-
|
|
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 };
|
package/dist/agent/index.d.ts
CHANGED
|
@@ -218,4 +218,80 @@ declare function getRemainingCredits(token: string, secret: string): Promise<{
|
|
|
218
218
|
bundleExpiry?: number;
|
|
219
219
|
}>;
|
|
220
220
|
|
|
221
|
-
|
|
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 };
|