@redditech/x402-solana 0.0.0-stage → 0.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/LICENSE +21 -0
  3. package/README.md +301 -2
  4. package/dist/budget-policy.d.ts +68 -0
  5. package/dist/budget-policy.js +234 -0
  6. package/dist/buyer.d.ts +54 -0
  7. package/dist/buyer.js +147 -0
  8. package/dist/client.d.ts +80 -0
  9. package/dist/client.js +225 -0
  10. package/dist/direct-auth.d.ts +94 -0
  11. package/dist/direct-auth.js +120 -0
  12. package/dist/direct-payment.d.ts +33 -0
  13. package/dist/direct-payment.js +65 -0
  14. package/dist/ed25519.d.ts +6 -0
  15. package/dist/ed25519.js +42 -0
  16. package/dist/escrow-http.d.ts +125 -0
  17. package/dist/escrow-http.js +192 -0
  18. package/dist/escrow-readiness.d.ts +132 -0
  19. package/dist/escrow-readiness.js +171 -0
  20. package/dist/index.d.ts +26 -0
  21. package/dist/index.js +42 -0
  22. package/dist/jupiter.d.ts +36 -0
  23. package/dist/jupiter.js +120 -0
  24. package/dist/metered.d.ts +58 -0
  25. package/dist/metered.js +82 -0
  26. package/dist/middleware.d.ts +9 -0
  27. package/dist/middleware.js +71 -0
  28. package/dist/nonce.d.ts +57 -0
  29. package/dist/nonce.js +123 -0
  30. package/dist/payment.d.ts +202 -0
  31. package/dist/payment.js +967 -0
  32. package/dist/provider.d.ts +371 -0
  33. package/dist/provider.js +492 -0
  34. package/dist/rating.d.ts +552 -0
  35. package/dist/rating.js +829 -0
  36. package/dist/session-auth.d.ts +168 -0
  37. package/dist/session-auth.js +341 -0
  38. package/dist/session.d.ts +220 -0
  39. package/dist/session.js +297 -0
  40. package/dist/spl-token-observer.d.ts +70 -0
  41. package/dist/spl-token-observer.js +319 -0
  42. package/dist/token-escrow.d.ts +125 -0
  43. package/dist/token-escrow.js +163 -0
  44. package/dist/types.d.ts +148 -0
  45. package/dist/types.js +2 -0
  46. package/package.json +109 -4
package/dist/client.js ADDED
@@ -0,0 +1,225 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.loadDevnetKeypair = loadDevnetKeypair;
4
+ exports.assertDevnetRpcUrl = assertDevnetRpcUrl;
5
+ exports.assertEndpointAllowed = assertEndpointAllowed;
6
+ exports.usdcAmountToMicroUnits = usdcAmountToMicroUnits;
7
+ exports.validateDevnetUsdcChallenge = validateDevnetUsdcChallenge;
8
+ exports.prepareDevnetUsdcPayment = prepareDevnetUsdcPayment;
9
+ exports.executeDevnetUsdcPayment = executeDevnetUsdcPayment;
10
+ exports.createSolanaDevnetUsdcPaymentClient = createSolanaDevnetUsdcPaymentClient;
11
+ exports.challengeFromX402RequestHeader = challengeFromX402RequestHeader;
12
+ exports.devnetUsdcPaymentProofHeaders = devnetUsdcPaymentProofHeaders;
13
+ const node_fs_1 = require("node:fs");
14
+ const web3_js_1 = require("@solana/web3.js");
15
+ const spl_token_1 = require("@solana/spl-token");
16
+ const payment_1 = require("./payment");
17
+ const direct_auth_1 = require("./direct-auth");
18
+ const DEVNET_NETWORK = 'solana-devnet';
19
+ const DEFAULT_MIN_FEE_LAMPORTS = 5000;
20
+ const APPROVAL_PHRASE = 'EXECUTE_DEVNET_X402_SPECIALIST_CALL';
21
+ function loadDevnetKeypair(path) {
22
+ if (!path || !(0, node_fs_1.existsSync)(path))
23
+ throw new Error('devnet_wallet_keypair_unavailable');
24
+ const secret = JSON.parse((0, node_fs_1.readFileSync)(path, 'utf8'));
25
+ if (!Array.isArray(secret))
26
+ throw new Error('devnet_wallet_keypair_invalid');
27
+ return web3_js_1.Keypair.fromSecretKey(Uint8Array.from(secret));
28
+ }
29
+ function assertDevnetRpcUrl(rpcUrl) {
30
+ let parsed;
31
+ try {
32
+ parsed = new URL(rpcUrl);
33
+ }
34
+ catch {
35
+ throw new Error('invalid_devnet_rpc_url');
36
+ }
37
+ if (!['http:', 'https:'].includes(parsed.protocol))
38
+ throw new Error('unsupported_devnet_rpc_url_protocol');
39
+ const host = parsed.hostname.toLowerCase();
40
+ if (host.includes('mainnet'))
41
+ throw new Error('mainnet_rpc_url_forbidden');
42
+ const allowed = host === 'api.devnet.solana.com' || host === 'localhost' || host === '127.0.0.1' || host === '::1' || host.includes('devnet');
43
+ if (!allowed)
44
+ throw new Error(`unsupported_devnet_rpc_url_host:${parsed.hostname}`);
45
+ }
46
+ function assertEndpointAllowed(endpoint, allowlist) {
47
+ if (!allowlist.length)
48
+ throw new Error('specialist_endpoint_allowlist_required');
49
+ let parsed;
50
+ try {
51
+ parsed = new URL(endpoint);
52
+ }
53
+ catch {
54
+ throw new Error('invalid_specialist_endpoint_url');
55
+ }
56
+ if (!['http:', 'https:'].includes(parsed.protocol))
57
+ throw new Error('unsupported_specialist_endpoint_protocol');
58
+ if (!allowlist.includes(endpoint))
59
+ throw new Error('specialist_endpoint_not_allowlisted');
60
+ }
61
+ function usdcAmountToMicroUnits(amount) {
62
+ const text = String(amount);
63
+ if (!/^\d+(\.\d{1,6})?$/.test(text))
64
+ throw new Error('invalid_usdc_amount');
65
+ const [wholeRaw, fracRaw = ''] = text.split('.');
66
+ const whole = BigInt(wholeRaw || '0');
67
+ const frac = BigInt((fracRaw + '000000').slice(0, 6));
68
+ const microUnits = whole * 1000000n + frac;
69
+ if (microUnits <= 0n)
70
+ throw new Error('invalid_usdc_amount');
71
+ return microUnits;
72
+ }
73
+ function normalizeCap(value) {
74
+ const cap = BigInt(value);
75
+ if (cap <= 0n)
76
+ throw new Error('invalid_devnet_usdc_spend_cap');
77
+ return cap;
78
+ }
79
+ function validateDevnetUsdcChallenge(challenge, config) {
80
+ assertDevnetRpcUrl(config.rpcUrl);
81
+ assertEndpointAllowed(challenge.endpoint, config.endpointAllowlist);
82
+ if (challenge.network !== DEVNET_NETWORK)
83
+ throw new Error('x402_challenge_not_solana_devnet');
84
+ if (String(challenge.currency).toUpperCase() !== 'USDC')
85
+ throw new Error('x402_challenge_currency_must_be_USDC');
86
+ if (!challenge.nonce)
87
+ throw new Error('x402_challenge_nonce_required');
88
+ if (!(0, payment_1.isValidSolanaPublicKey)(challenge.payTo))
89
+ throw new Error('x402_challenge_payee_invalid');
90
+ if (!(0, payment_1.isValidSolanaPublicKey)(config.usdcMint))
91
+ throw new Error('devnet_usdc_mint_invalid');
92
+ const amountMicroUnits = usdcAmountToMicroUnits(challenge.amount);
93
+ const maxUsdcMicroUnits = normalizeCap(config.maxUsdcMicroUnits);
94
+ if (amountMicroUnits > maxUsdcMicroUnits)
95
+ throw new Error(`devnet_usdc_spend_cap_exceeded:${amountMicroUnits}>${maxUsdcMicroUnits}`);
96
+ return {
97
+ payTo: new web3_js_1.PublicKey(challenge.payTo),
98
+ mint: new web3_js_1.PublicKey(config.usdcMint),
99
+ amountMicroUnits,
100
+ maxUsdcMicroUnits,
101
+ };
102
+ }
103
+ async function prepareDevnetUsdcPayment(input) {
104
+ const reasons = [];
105
+ let payer = null;
106
+ let payTo;
107
+ let mint;
108
+ let amountMicroUnits;
109
+ let maxUsdcMicroUnits;
110
+ try {
111
+ ({ payTo, mint, amountMicroUnits, maxUsdcMicroUnits } = validateDevnetUsdcChallenge(input.challenge, input.config));
112
+ payer = loadDevnetKeypair(input.config.walletKeypairPath);
113
+ }
114
+ catch (error) {
115
+ return readiness(input.challenge, null, '0', String(input.config.maxUsdcMicroUnits), false, reasons.concat(error instanceof Error ? error.message : String(error)), null, null, null);
116
+ }
117
+ const solLamports = await input.client.getSolBalanceLamports(payer.publicKey);
118
+ const usdcMicroUnits = await input.client.getUsdcBalanceMicroUnits(payer.publicKey, mint);
119
+ const destinationTokenAccount = await input.client.getOrCreateDestinationTokenAccount(payTo, mint);
120
+ const minFeeLamports = input.config.minFeeLamports ?? DEFAULT_MIN_FEE_LAMPORTS;
121
+ if (solLamports < minFeeLamports)
122
+ reasons.push(`insufficient_sol_for_fees:${solLamports}<${minFeeLamports}`);
123
+ if (usdcMicroUnits < amountMicroUnits)
124
+ reasons.push(`insufficient_usdc:${usdcMicroUnits}<${amountMicroUnits}`);
125
+ return readiness(input.challenge, payer.publicKey.toBase58(), String(amountMicroUnits), String(maxUsdcMicroUnits), amountMicroUnits <= maxUsdcMicroUnits, reasons, solLamports, String(usdcMicroUnits), destinationTokenAccount);
126
+ }
127
+ function readiness(challenge, payer, amountMicroUnits, maxUsdcMicroUnits, capRespected, reasons, solLamports, usdcMicroUnits, destinationTokenAccount) {
128
+ return {
129
+ schemaVersion: 'reddi.x402-solana.devnet-usdc-payment-readiness.v1',
130
+ ready: reasons.length === 0,
131
+ boundary: 'solana-devnet-only-no-mainnet',
132
+ reasons,
133
+ payer,
134
+ challenge: {
135
+ network: challenge.network,
136
+ payTo: challenge.payTo,
137
+ amount: challenge.amount,
138
+ currency: challenge.currency,
139
+ endpoint: challenge.endpoint,
140
+ nonce: challenge.nonce,
141
+ },
142
+ spend: { amountMicroUnits, maxUsdcMicroUnits, capRespected },
143
+ balances: { solLamports, usdcMicroUnits },
144
+ destinationTokenAccount,
145
+ };
146
+ }
147
+ async function executeDevnetUsdcPayment(input) {
148
+ if (input.approvalPhrase !== APPROVAL_PHRASE)
149
+ throw new Error('missing_devnet_x402_specialist_call_approval_phrase');
150
+ const { payTo, mint, amountMicroUnits } = validateDevnetUsdcChallenge(input.challenge, input.config);
151
+ const payer = loadDevnetKeypair(input.config.walletKeypairPath);
152
+ const readiness = await prepareDevnetUsdcPayment({ challenge: input.challenge, config: input.config, client: input.client });
153
+ if (!readiness.ready)
154
+ throw new Error(`devnet_usdc_payment_not_ready:${readiness.reasons.join(',')}`);
155
+ const destinationTokenAccount = readiness.destinationTokenAccount ?? await input.client.getOrCreateDestinationTokenAccount(payTo, mint);
156
+ const result = await input.client.submitUsdcTransfer({ payer, payTo, mint, amountMicroUnits, destinationTokenAccount, challenge: input.challenge });
157
+ return {
158
+ network: DEVNET_NETWORK,
159
+ payTo: input.challenge.payTo,
160
+ amount: input.challenge.amount,
161
+ currency: 'USDC',
162
+ nonce: input.challenge.nonce,
163
+ signature: result.signature,
164
+ txSignature: result.signature,
165
+ payer: payer.publicKey.toBase58(),
166
+ mint: mint.toBase58(),
167
+ destinationTokenAccount: result.destinationTokenAccount,
168
+ };
169
+ }
170
+ function createSolanaDevnetUsdcPaymentClient(connection) {
171
+ return {
172
+ async getSolBalanceLamports(publicKey) {
173
+ return connection.getBalance(publicKey, 'confirmed');
174
+ },
175
+ async getUsdcBalanceMicroUnits(owner, mint) {
176
+ const tokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(mint, owner, false, spl_token_1.TOKEN_PROGRAM_ID, spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID);
177
+ const accountInfo = await connection.getAccountInfo(tokenAccount, 'confirmed');
178
+ if (!accountInfo)
179
+ return 0n;
180
+ const balance = await connection.getTokenAccountBalance(tokenAccount, 'confirmed');
181
+ return BigInt(balance.value.amount);
182
+ },
183
+ async getOrCreateDestinationTokenAccount(payTo, mint) {
184
+ return (0, spl_token_1.getAssociatedTokenAddressSync)(mint, payTo, false, spl_token_1.TOKEN_PROGRAM_ID, spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID).toBase58();
185
+ },
186
+ async submitUsdcTransfer(input) {
187
+ const sourceTokenAccount = (0, spl_token_1.getAssociatedTokenAddressSync)(input.mint, input.payer.publicKey, false, spl_token_1.TOKEN_PROGRAM_ID, spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID);
188
+ const destinationTokenAccount = new web3_js_1.PublicKey(input.destinationTokenAccount);
189
+ const tx = new web3_js_1.Transaction();
190
+ const destinationInfo = await connection.getAccountInfo(destinationTokenAccount, 'confirmed');
191
+ if (!destinationInfo) {
192
+ tx.add((0, spl_token_1.createAssociatedTokenAccountInstruction)(input.payer.publicKey, destinationTokenAccount, input.payTo, input.mint, spl_token_1.TOKEN_PROGRAM_ID, spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID));
193
+ }
194
+ tx.add((0, spl_token_1.createTransferCheckedInstruction)(sourceTokenAccount, input.mint, destinationTokenAccount, input.payer.publicKey, input.amountMicroUnits, 6, [], spl_token_1.TOKEN_PROGRAM_ID));
195
+ const signature = await (0, web3_js_1.sendAndConfirmTransaction)(connection, tx, [input.payer], { commitment: 'confirmed' });
196
+ return { signature, destinationTokenAccount: destinationTokenAccount.toBase58() };
197
+ },
198
+ };
199
+ }
200
+ function challengeFromX402RequestHeader(header) {
201
+ const parsed = JSON.parse(header);
202
+ return (0, payment_1.buildX402Challenge)({
203
+ version: typeof parsed.version === 'string' ? parsed.version : '1',
204
+ network: parsed.network,
205
+ payTo: typeof parsed.payTo === 'string' ? parsed.payTo : parsed.paymentAddress,
206
+ amount: parsed.amount,
207
+ currency: parsed.currency,
208
+ endpoint: parsed.endpoint,
209
+ nonce: parsed.nonce,
210
+ memo: typeof parsed.memo === 'string' ? parsed.memo : undefined,
211
+ });
212
+ }
213
+ /**
214
+ * The proof headers for presenting a devnet USDC receipt with `body`, signed by
215
+ * the same wallet file that paid. Send them with `x402-payment` on the paid retry.
216
+ */
217
+ async function devnetUsdcPaymentProofHeaders(input) {
218
+ const payer = loadDevnetKeypair(input.walletKeypairPath);
219
+ const txSignature = input.receipt.signature ?? input.receipt.txSignature;
220
+ if (!txSignature)
221
+ throw new Error('devnet_receipt_signature_missing');
222
+ if (input.receipt.payer !== payer.publicKey.toBase58())
223
+ throw new Error('devnet_receipt_payer_is_not_this_wallet');
224
+ return (0, direct_auth_1.directPaymentProofHeaders)({ network: input.receipt.network, txSignature, payTo: input.receipt.payTo, body: input.body, sign: (0, direct_auth_1.keypairSigner)(payer) });
225
+ }
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Proof that a direct per-call payment is being presented by the wallet that
3
+ * paid it.
4
+ *
5
+ * A confirmed transfer is public: its signature, payer and amount can be read
6
+ * by anyone. Without a proof, someone who sees a buyer's payment could present
7
+ * it first and be served, and the buyer would then be refused as a duplicate.
8
+ * So the request that presents a direct receipt carries a signature over the
9
+ * network, the transaction signature, the payee and the SHA-256 of the request
10
+ * body, made by the wallet that signed the transfer, or by a key that wallet
11
+ * handed this provider for a while (so a browser wallet signs once, not on
12
+ * every call).
13
+ *
14
+ * Headers:
15
+ * - `x402-payment-proof`: base64 of the signature over `directPaymentProofMessage(...)`.
16
+ * - `x402-payment-delegation` (optional): base64 of JSON `{provider, sessionKey, expiresAt, signature}`,
17
+ * `signature` base64 of the payer's signature over `directPaymentDelegationMessage(...)`.
18
+ * With it, the proof is signed by `sessionKey`; without it, by the payer.
19
+ *
20
+ * Verification uses Node's crypto; signing takes a callback, so the buyer can
21
+ * sign with a wallet adapter, a Keypair or anything else.
22
+ */
23
+ import type { Keypair } from '@solana/web3.js';
24
+ import type { HeaderReader } from './provider';
25
+ import { type Signer } from './session-auth';
26
+ import type { PayerProofCheck, ProvenDirectPayment, SolanaPaymentNetwork } from './types';
27
+ export declare const PAYMENT_PROOF_HEADER = "x402-payment-proof";
28
+ export declare const PAYMENT_DELEGATION_HEADER = "x402-payment-delegation";
29
+ export interface DirectPaymentDelegation {
30
+ /** The provider's payee wallet. */
31
+ provider: string;
32
+ sessionKey: string;
33
+ /** Whole seconds since the epoch, at most `MAX_SESSION_DELEGATION_SECONDS` ahead. */
34
+ expiresAt: number;
35
+ }
36
+ export type DirectPaymentProofFailure = {
37
+ ok: false;
38
+ reason: 'payer_proof_required' | 'payer_proof_invalid' | 'payer_proof_expired';
39
+ message: string;
40
+ };
41
+ /** The text the payer wallet signs to let `sessionKey` prove its direct payments to `provider`. */
42
+ export declare function directPaymentDelegationMessage(d: DirectPaymentDelegation): string;
43
+ /** The bytes signed for one request that presents a direct payment. */
44
+ export declare function directPaymentProofMessage(input: {
45
+ network: SolanaPaymentNetwork;
46
+ txSignature: string;
47
+ payTo: string;
48
+ bodyHash: string;
49
+ }): string;
50
+ /** Buyer side: a signer for a server-held Keypair (a browser wallet passes its own `signMessage`). */
51
+ export declare function keypairSigner(keypair: Keypair): Signer;
52
+ /**
53
+ * Buyer side: the delegation header value, signed once by the payer wallet.
54
+ * Keep it with the session key, in memory only, and reuse it until it expires.
55
+ * Use `delegationExpiresAt()` (a day) for `expiresAt` rather than the maximum.
56
+ */
57
+ export declare function directPaymentDelegationHeaderValue(d: DirectPaymentDelegation, signWithPayer: Signer): Promise<string>;
58
+ /**
59
+ * Buyer side: the headers for one request that presents a direct payment.
60
+ * `sign` is the payer wallet, or the session key named in `delegation`.
61
+ * `body` must be the exact bytes sent.
62
+ */
63
+ export declare function directPaymentProofHeaders(input: {
64
+ network: SolanaPaymentNetwork;
65
+ txSignature: string;
66
+ payTo: string;
67
+ body: Uint8Array | string;
68
+ sign: Signer;
69
+ delegation?: string;
70
+ }): Promise<Record<string, string>>;
71
+ /**
72
+ * Provider side: checks that the request was signed by the wallet that made
73
+ * the payment (`paid.payer`, which the receipt verifier has already tied to
74
+ * the transaction), or by a key it delegated to this provider. `body` is the
75
+ * raw request body exactly as received.
76
+ */
77
+ export declare function verifyDirectPaymentProof(input: {
78
+ headers: HeaderReader;
79
+ paid: ProvenDirectPayment;
80
+ body?: Uint8Array | string;
81
+ nowMs: number;
82
+ }): {
83
+ ok: true;
84
+ signer: string;
85
+ } | DirectPaymentProofFailure;
86
+ /**
87
+ * Provider side: the check to pass to `SolanaReceiptVerifier.verifyReceipt`
88
+ * for one request. `body` is the raw request body exactly as received.
89
+ */
90
+ export declare function directPaymentProofCheck(input: {
91
+ headers: HeaderReader;
92
+ body?: Uint8Array | string;
93
+ nowMs?: number;
94
+ }): PayerProofCheck;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PAYMENT_DELEGATION_HEADER = exports.PAYMENT_PROOF_HEADER = void 0;
4
+ exports.directPaymentDelegationMessage = directPaymentDelegationMessage;
5
+ exports.directPaymentProofMessage = directPaymentProofMessage;
6
+ exports.keypairSigner = keypairSigner;
7
+ exports.directPaymentDelegationHeaderValue = directPaymentDelegationHeaderValue;
8
+ exports.directPaymentProofHeaders = directPaymentProofHeaders;
9
+ exports.verifyDirectPaymentProof = verifyDirectPaymentProof;
10
+ exports.directPaymentProofCheck = directPaymentProofCheck;
11
+ const ed25519_1 = require("./ed25519");
12
+ const session_auth_1 = require("./session-auth");
13
+ exports.PAYMENT_PROOF_HEADER = 'x402-payment-proof';
14
+ exports.PAYMENT_DELEGATION_HEADER = 'x402-payment-delegation';
15
+ /** The text the payer wallet signs to let `sessionKey` prove its direct payments to `provider`. */
16
+ function directPaymentDelegationMessage(d) {
17
+ return [
18
+ 'Reddi Agent Protocol direct payments',
19
+ 'I let this key prove my direct payments to this provider.',
20
+ `provider: ${d.provider}`,
21
+ `session key: ${d.sessionKey}`,
22
+ `expires: ${new Date(d.expiresAt * 1000).toISOString()}`,
23
+ ].join('\n');
24
+ }
25
+ /** The bytes signed for one request that presents a direct payment. */
26
+ function directPaymentProofMessage(input) {
27
+ return ['reddi-direct/1', input.network, input.txSignature, input.payTo, input.bodyHash].join('\n');
28
+ }
29
+ /** Buyer side: a signer for a server-held Keypair (a browser wallet passes its own `signMessage`). */
30
+ function keypairSigner(keypair) {
31
+ return (message) => (0, ed25519_1.ed25519Sign)(keypair, message);
32
+ }
33
+ /**
34
+ * Buyer side: the delegation header value, signed once by the payer wallet.
35
+ * Keep it with the session key, in memory only, and reuse it until it expires.
36
+ * Use `delegationExpiresAt()` (a day) for `expiresAt` rather than the maximum.
37
+ */
38
+ async function directPaymentDelegationHeaderValue(d, signWithPayer) {
39
+ const signature = await signWithPayer(new TextEncoder().encode(directPaymentDelegationMessage(d)));
40
+ return Buffer.from(JSON.stringify({ ...d, signature: Buffer.from(signature).toString('base64') }), 'utf8').toString('base64');
41
+ }
42
+ /**
43
+ * Buyer side: the headers for one request that presents a direct payment.
44
+ * `sign` is the payer wallet, or the session key named in `delegation`.
45
+ * `body` must be the exact bytes sent.
46
+ */
47
+ async function directPaymentProofHeaders(input) {
48
+ const message = directPaymentProofMessage({ network: input.network, txSignature: input.txSignature, payTo: input.payTo, bodyHash: (0, session_auth_1.sessionBodyHash)(input.body) });
49
+ const proof = Buffer.from(await input.sign(new TextEncoder().encode(message))).toString('base64');
50
+ return { [exports.PAYMENT_PROOF_HEADER]: proof, ...(input.delegation ? { [exports.PAYMENT_DELEGATION_HEADER]: input.delegation } : {}) };
51
+ }
52
+ /**
53
+ * Provider side: checks that the request was signed by the wallet that made
54
+ * the payment (`paid.payer`, which the receipt verifier has already tied to
55
+ * the transaction), or by a key it delegated to this provider. `body` is the
56
+ * raw request body exactly as received.
57
+ */
58
+ function verifyDirectPaymentProof(input) {
59
+ const proofValue = input.headers.get(exports.PAYMENT_PROOF_HEADER);
60
+ if (!proofValue) {
61
+ return { ok: false, reason: 'payer_proof_required', message: `A direct payment must be presented with ${exports.PAYMENT_PROOF_HEADER}: a signature over this request by the wallet that paid.` };
62
+ }
63
+ const invalid = (message) => ({ ok: false, reason: 'payer_proof_invalid', message });
64
+ const payer = (0, ed25519_1.publicKeyOf)(input.paid.payer);
65
+ const payTo = (0, ed25519_1.publicKeyOf)(input.paid.payTo);
66
+ if (!payer || !payTo)
67
+ return invalid('The payment does not name a valid payer and payee.');
68
+ let signer = payer;
69
+ const delegationValue = input.headers.get(exports.PAYMENT_DELEGATION_HEADER);
70
+ if (delegationValue) {
71
+ const raw = (0, ed25519_1.decodeBase64)(delegationValue);
72
+ if (!raw)
73
+ return invalid('The payment delegation is not base64.');
74
+ let parsed;
75
+ try {
76
+ const value = JSON.parse(raw.toString('utf8'));
77
+ if (!value || typeof value !== 'object' || Array.isArray(value))
78
+ return invalid('The payment delegation is not an object.');
79
+ parsed = value;
80
+ }
81
+ catch {
82
+ return invalid('The payment delegation is not JSON.');
83
+ }
84
+ const provider = (0, ed25519_1.publicKeyOf)(parsed.provider);
85
+ const sessionKey = (0, ed25519_1.publicKeyOf)(parsed.sessionKey);
86
+ const expiresAt = parsed.expiresAt;
87
+ const signature = typeof parsed.signature === 'string' ? (0, ed25519_1.decodeBase64)(parsed.signature) : undefined;
88
+ if (!provider || !sessionKey || typeof expiresAt !== 'number' || !Number.isSafeInteger(expiresAt) || !signature) {
89
+ return invalid('The payment delegation needs provider, sessionKey, a whole-second expiresAt and a signature.');
90
+ }
91
+ if (!provider.equals(payTo))
92
+ return invalid('The payment delegation names another provider.');
93
+ const nowSeconds = Math.floor(input.nowMs / 1000);
94
+ if (expiresAt <= nowSeconds)
95
+ return { ok: false, reason: 'payer_proof_expired', message: 'The payment delegation has expired. Sign a new one with the payer wallet.' };
96
+ if (expiresAt > nowSeconds + session_auth_1.MAX_SESSION_DELEGATION_SECONDS)
97
+ return invalid(`A payment delegation may run for at most ${session_auth_1.MAX_SESSION_DELEGATION_SECONDS} seconds.`);
98
+ const delegation = { provider: provider.toBase58(), sessionKey: sessionKey.toBase58(), expiresAt };
99
+ if (!(0, ed25519_1.ed25519Verify)(payer, new TextEncoder().encode(directPaymentDelegationMessage(delegation)), signature)) {
100
+ return invalid('The payment delegation is not signed by the wallet that paid.');
101
+ }
102
+ signer = sessionKey;
103
+ }
104
+ const proof = (0, ed25519_1.decodeBase64)(proofValue);
105
+ const message = directPaymentProofMessage({ network: input.paid.network, txSignature: input.paid.txSignature, payTo: payTo.toBase58(), bodyHash: (0, session_auth_1.sessionBodyHash)(input.body) });
106
+ if (!proof || !(0, ed25519_1.ed25519Verify)(signer, new TextEncoder().encode(message), proof)) {
107
+ return invalid('The request is not signed by the wallet that paid, or was changed after signing.');
108
+ }
109
+ return { ok: true, signer: signer.toBase58() };
110
+ }
111
+ /**
112
+ * Provider side: the check to pass to `SolanaReceiptVerifier.verifyReceipt`
113
+ * for one request. `body` is the raw request body exactly as received.
114
+ */
115
+ function directPaymentProofCheck(input) {
116
+ return (paid) => {
117
+ const result = verifyDirectPaymentProof({ headers: input.headers, paid, body: input.body, nowMs: input.nowMs ?? Date.now() });
118
+ return result.ok ? { ok: true } : result;
119
+ };
120
+ }
@@ -0,0 +1,33 @@
1
+ import { PublicKey, TransactionInstruction } from '@solana/web3.js';
2
+ import type { X402Challenge } from './types';
3
+ export interface DirectPaymentInput {
4
+ challenge: X402Challenge;
5
+ /** Wallet that pays and signs. */
6
+ payer: PublicKey;
7
+ /**
8
+ * Required for a token currency (USDC, AUDD, PYUSD, USDG): the buyer's own
9
+ * configured mint for that currency, never one named by the seller.
10
+ */
11
+ mint?: PublicKey;
12
+ /** Older name for `mint`, kept for USDC callers. */
13
+ usdcMint?: PublicKey;
14
+ /** Buyer's token account. Defaults to the buyer's associated token account. */
15
+ payerTokenAccount?: PublicKey;
16
+ /**
17
+ * Highest fee rate the buyer accepts, in basis points. Defaults to
18
+ * PROTOCOL_FEE_BPS, so a challenge stating a larger fee is refused before
19
+ * anything is signed.
20
+ */
21
+ maxFeeBps?: number;
22
+ }
23
+ /**
24
+ * Instructions for one direct per-call payment. With fee terms in the challenge
25
+ * the buyer pays the listed amount in total: the provider's share to the payee
26
+ * and the fee to the treasury, in the same transaction. This builds instructions
27
+ * only. It signs nothing and sends nothing.
28
+ *
29
+ * The split is recomputed from the listed amount and the stated rate, and must
30
+ * match the stated amounts exactly, so a challenge cannot make the buyer pay
31
+ * more than the listed price or route more than the stated rate to the fee.
32
+ */
33
+ export declare function buildDirectPaymentInstructions(input: DirectPaymentInput): TransactionInstruction[];
@@ -0,0 +1,65 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.buildDirectPaymentInstructions = buildDirectPaymentInstructions;
4
+ const web3_js_1 = require("@solana/web3.js");
5
+ const spl_token_1 = require("@solana/spl-token");
6
+ const payment_1 = require("./payment");
7
+ /**
8
+ * Instructions for one direct per-call payment. With fee terms in the challenge
9
+ * the buyer pays the listed amount in total: the provider's share to the payee
10
+ * and the fee to the treasury, in the same transaction. This builds instructions
11
+ * only. It signs nothing and sends nothing.
12
+ *
13
+ * The split is recomputed from the listed amount and the stated rate, and must
14
+ * match the stated amounts exactly, so a challenge cannot make the buyer pay
15
+ * more than the listed price or route more than the stated rate to the fee.
16
+ */
17
+ function buildDirectPaymentInstructions(input) {
18
+ const { challenge, payer } = input;
19
+ const currency = (0, payment_1.directPaymentCurrency)(challenge.currency);
20
+ if (currency === undefined)
21
+ throw new Error(`unsupported direct payment currency: ${challenge.currency}`);
22
+ const decimals = currency.decimals;
23
+ const price = (0, payment_1.decimalToBaseUnits)(challenge.amount, decimals);
24
+ if (price === undefined)
25
+ throw new Error('challenge amount is not a valid positive amount');
26
+ const payTo = new web3_js_1.PublicKey(challenge.payTo);
27
+ let providerUnits = price;
28
+ let feeUnits = BigInt(0);
29
+ let treasury;
30
+ if (challenge.fee) {
31
+ const maxFeeBps = input.maxFeeBps ?? (0, payment_1.protocolFeeBpsAt)();
32
+ if (challenge.fee.bps > maxFeeBps)
33
+ throw new Error(`challenge fee of ${challenge.fee.bps} bps exceeds the accepted ${maxFeeBps} bps`);
34
+ // The ceiling is the buyer's own rule for the currency, never the challenge's.
35
+ feeUnits = (0, payment_1.protocolFeeBaseUnits)(price, challenge.fee.bps, (0, payment_1.protocolFeeCapBaseUnits)(challenge.currency));
36
+ providerUnits = price - feeUnits;
37
+ const statedFee = challenge.fee.amount === '0' ? BigInt(0) : (0, payment_1.decimalToBaseUnits)(challenge.fee.amount, decimals);
38
+ const statedProvider = (0, payment_1.decimalToBaseUnits)(challenge.fee.providerAmount, decimals);
39
+ if (statedFee !== feeUnits || statedProvider !== providerUnits) {
40
+ throw new Error('challenge fee terms do not add up to the listed amount at the stated rate');
41
+ }
42
+ treasury = new web3_js_1.PublicKey(challenge.fee.payTo);
43
+ if (treasury.equals(payTo))
44
+ throw new Error('fee treasury must differ from the payee');
45
+ }
46
+ if (currency.tokenProgram === undefined) {
47
+ const instructions = [web3_js_1.SystemProgram.transfer({ fromPubkey: payer, toPubkey: payTo, lamports: providerUnits })];
48
+ if (treasury && feeUnits > BigInt(0))
49
+ instructions.push(web3_js_1.SystemProgram.transfer({ fromPubkey: payer, toPubkey: treasury, lamports: feeUnits }));
50
+ return instructions;
51
+ }
52
+ const mint = input.mint ?? (challenge.currency === 'USDC' ? input.usdcMint : undefined);
53
+ if (!mint)
54
+ throw new Error(`a configured mint is required for a ${challenge.currency} payment`);
55
+ // PYUSD and USDG are Token-2022 mints; their token accounts derive from that program.
56
+ const tokenProgram = new web3_js_1.PublicKey(currency.tokenProgram);
57
+ // Owners may be program-derived addresses, such as a multisig vault.
58
+ const tokenAccountOf = (owner) => (0, spl_token_1.getAssociatedTokenAddressSync)(mint, owner, true, tokenProgram);
59
+ const source = input.payerTokenAccount ?? tokenAccountOf(payer);
60
+ const transfer = (owner, units) => (0, spl_token_1.createTransferCheckedInstruction)(source, mint, tokenAccountOf(owner), payer, units, decimals, [], tokenProgram);
61
+ const instructions = [transfer(payTo, providerUnits)];
62
+ if (treasury && feeUnits > BigInt(0))
63
+ instructions.push(transfer(treasury, feeUnits));
64
+ return instructions;
65
+ }
@@ -0,0 +1,6 @@
1
+ import { PublicKey, type Keypair } from '@solana/web3.js';
2
+ /** Signs with a Keypair's secret key, as `nacl.sign.detached` would. */
3
+ export declare function ed25519Sign(keypair: Keypair, message: Uint8Array): Uint8Array;
4
+ export declare function ed25519Verify(publicKey: PublicKey, message: Uint8Array, signature: Uint8Array): boolean;
5
+ export declare function decodeBase64(value: string): Buffer | undefined;
6
+ export declare function publicKeyOf(value: unknown): PublicKey | undefined;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ed25519Sign = ed25519Sign;
4
+ exports.ed25519Verify = ed25519Verify;
5
+ exports.decodeBase64 = decodeBase64;
6
+ exports.publicKeyOf = publicKeyOf;
7
+ /** Internal helpers shared by the request-signature checks. Not exported from the package index. */
8
+ const crypto_1 = require("crypto");
9
+ const web3_js_1 = require("@solana/web3.js");
10
+ const ED25519_PKCS8_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');
11
+ /** Signs with a Keypair's secret key, as `nacl.sign.detached` would. */
12
+ function ed25519Sign(keypair, message) {
13
+ const key = (0, crypto_1.createPrivateKey)({ key: Buffer.concat([ED25519_PKCS8_PREFIX, Buffer.from(keypair.secretKey.subarray(0, 32))]), format: 'der', type: 'pkcs8' });
14
+ return new Uint8Array((0, crypto_1.sign)(null, Buffer.from(message), key));
15
+ }
16
+ const ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
17
+ function ed25519Verify(publicKey, message, signature) {
18
+ if (signature.length !== 64)
19
+ return false;
20
+ try {
21
+ const key = (0, crypto_1.createPublicKey)({ key: Buffer.concat([ED25519_SPKI_PREFIX, publicKey.toBuffer()]), format: 'der', type: 'spki' });
22
+ return (0, crypto_1.verify)(null, Buffer.from(message), key, Buffer.from(signature));
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ }
28
+ const BASE64 = /^[A-Za-z0-9+/]+={0,2}$/;
29
+ function decodeBase64(value) {
30
+ const trimmed = value.trim();
31
+ return trimmed.length > 0 && trimmed.length <= 4096 && BASE64.test(trimmed) ? Buffer.from(trimmed, 'base64') : undefined;
32
+ }
33
+ function publicKeyOf(value) {
34
+ if (typeof value !== 'string' || value.length > 64)
35
+ return undefined;
36
+ try {
37
+ return new web3_js_1.PublicKey(value);
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ }