@redditech/x402-solana 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +90 -0
- package/LICENSE +21 -0
- package/README.md +301 -2
- package/dist/budget-policy.d.ts +68 -0
- package/dist/budget-policy.js +234 -0
- package/dist/buyer.d.ts +54 -0
- package/dist/buyer.js +147 -0
- package/dist/client.d.ts +80 -0
- package/dist/client.js +225 -0
- package/dist/direct-auth.d.ts +94 -0
- package/dist/direct-auth.js +120 -0
- package/dist/direct-payment.d.ts +33 -0
- package/dist/direct-payment.js +65 -0
- package/dist/ed25519.d.ts +6 -0
- package/dist/ed25519.js +42 -0
- package/dist/escrow-http.d.ts +125 -0
- package/dist/escrow-http.js +192 -0
- package/dist/escrow-readiness.d.ts +132 -0
- package/dist/escrow-readiness.js +171 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +42 -0
- package/dist/jupiter.d.ts +36 -0
- package/dist/jupiter.js +120 -0
- package/dist/metered.d.ts +58 -0
- package/dist/metered.js +82 -0
- package/dist/middleware.d.ts +9 -0
- package/dist/middleware.js +71 -0
- package/dist/nonce.d.ts +57 -0
- package/dist/nonce.js +123 -0
- package/dist/payment.d.ts +202 -0
- package/dist/payment.js +967 -0
- package/dist/provider.d.ts +371 -0
- package/dist/provider.js +492 -0
- package/dist/rating.d.ts +552 -0
- package/dist/rating.js +829 -0
- package/dist/session-auth.d.ts +168 -0
- package/dist/session-auth.js +341 -0
- package/dist/session.d.ts +220 -0
- package/dist/session.js +297 -0
- package/dist/spl-token-observer.d.ts +70 -0
- package/dist/spl-token-observer.js +319 -0
- package/dist/token-escrow.d.ts +125 -0
- package/dist/token-escrow.js +163 -0
- package/dist/types.d.ts +148 -0
- package/dist/types.js +2 -0
- package/package.json +109 -4
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.evaluateBudgetPolicy = evaluateBudgetPolicy;
|
|
4
|
+
exports.assetNetworkKey = assetNetworkKey;
|
|
5
|
+
function evaluateBudgetPolicy(input) {
|
|
6
|
+
const state = { reasonCodes: [], remainingBudget: {}, auditNotes: [] };
|
|
7
|
+
const quoted = normalizeQuote(input.quote, state);
|
|
8
|
+
if (!input.policy) {
|
|
9
|
+
state.reasonCodes.push('budget_policy_missing');
|
|
10
|
+
state.auditNotes.push('Denied: budget policy is required before buyer preflight can authorize spend.');
|
|
11
|
+
return decision(false, state, quoted);
|
|
12
|
+
}
|
|
13
|
+
if (!quoted)
|
|
14
|
+
return decision(false, state, null);
|
|
15
|
+
if (input.policy.schemaVersion !== 'reddi.budget-policy.v1') {
|
|
16
|
+
malformed(state, 'policy.schemaVersion must be reddi.budget-policy.v1');
|
|
17
|
+
return decision(false, state, quoted);
|
|
18
|
+
}
|
|
19
|
+
if (!isPlainObject(input.policy.limits)) {
|
|
20
|
+
malformed(state, 'policy.limits must be a plain object');
|
|
21
|
+
return decision(false, state, quoted);
|
|
22
|
+
}
|
|
23
|
+
const usage = input.usage ?? {};
|
|
24
|
+
checkPerRequest(input.policy.limits.perRequest, quoted.amount, state);
|
|
25
|
+
checkPerSession(input.policy.limits.perSession, quoted.amount, usage.sessionSpent, state);
|
|
26
|
+
checkSourceLimit('perSource', input.policy.limits.perSource, quoted.source, quoted.amount, usage.sourceSpent, state);
|
|
27
|
+
checkSourceLimit('perSpecialist', input.policy.limits.perSpecialist, quoted.specialist, quoted.amount, usage.specialistSpent, state);
|
|
28
|
+
checkAssetNetworkLimit(input.policy.limits.perAssetNetwork, quoted, usage.assetNetworkSpent, state);
|
|
29
|
+
checkCallCount(input.policy.limits.callCount, usage.callCount, state);
|
|
30
|
+
const allowed = state.reasonCodes.length === 0;
|
|
31
|
+
if (allowed) {
|
|
32
|
+
state.reasonCodes.push('allowed');
|
|
33
|
+
state.auditNotes.push('Allowed: quoted spend is within all configured local buyer budget limits.');
|
|
34
|
+
}
|
|
35
|
+
return decision(allowed, state, quoted);
|
|
36
|
+
}
|
|
37
|
+
function normalizeQuote(quote, state) {
|
|
38
|
+
const amount = normalizeAmount(quote.amount);
|
|
39
|
+
if (amount === undefined || amount <= 0n || !quote.asset || !quote.network) {
|
|
40
|
+
state.reasonCodes.push('invalid_quote');
|
|
41
|
+
state.auditNotes.push('Denied: quote must include a positive integer amount, asset, and network.');
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
amount,
|
|
46
|
+
asset: normalizeAsset(quote.asset),
|
|
47
|
+
network: normalizeNetwork(quote.network),
|
|
48
|
+
source: quote.source,
|
|
49
|
+
specialist: quote.specialist,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
function checkPerRequest(limit, amount, state) {
|
|
53
|
+
if (!limit)
|
|
54
|
+
return;
|
|
55
|
+
const max = normalizeLimit(limit, 'perRequest', state);
|
|
56
|
+
if (max === undefined)
|
|
57
|
+
return;
|
|
58
|
+
const remaining = max - amount;
|
|
59
|
+
state.remainingBudget.perRequest = stringifyRemaining(remaining);
|
|
60
|
+
if (remaining < 0n) {
|
|
61
|
+
state.reasonCodes.push('request_amount_exceeds_limit');
|
|
62
|
+
state.auditNotes.push(`Denied: request quote ${amount} exceeds per-request limit ${max}.`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function checkPerSession(limit, amount, spent, state) {
|
|
66
|
+
if (!limit)
|
|
67
|
+
return;
|
|
68
|
+
const max = normalizeLimit(limit, 'perSession', state);
|
|
69
|
+
const used = normalizeUsage(spent, 'sessionSpent', state);
|
|
70
|
+
if (max === undefined || used === undefined)
|
|
71
|
+
return;
|
|
72
|
+
const remaining = max - used - amount;
|
|
73
|
+
state.remainingBudget.perSession = stringifyRemaining(remaining);
|
|
74
|
+
if (remaining < 0n) {
|
|
75
|
+
state.reasonCodes.push('session_budget_exceeded');
|
|
76
|
+
state.auditNotes.push(`Denied: session spend ${used} plus quote ${amount} exceeds session limit ${max}.`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function checkSourceLimit(kind, limits, id, amount, usage, state) {
|
|
80
|
+
if (!limits)
|
|
81
|
+
return;
|
|
82
|
+
if (!isPlainObject(limits)) {
|
|
83
|
+
malformed(state, `${kind} must be a plain object keyed by source or specialist id`);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (!id)
|
|
87
|
+
return;
|
|
88
|
+
const key = id;
|
|
89
|
+
const limit = limits[key];
|
|
90
|
+
if (!limit)
|
|
91
|
+
return;
|
|
92
|
+
const max = normalizeLimit(limit, `${kind}.${key}`, state);
|
|
93
|
+
const used = normalizeUsage(usage?.[key], `${kind}.${key}.spent`, state);
|
|
94
|
+
if (max === undefined || used === undefined)
|
|
95
|
+
return;
|
|
96
|
+
const remaining = max - used - amount;
|
|
97
|
+
if (kind === 'perSource')
|
|
98
|
+
state.remainingBudget.perSource = stringifyRemaining(remaining);
|
|
99
|
+
else
|
|
100
|
+
state.remainingBudget.perSpecialist = stringifyRemaining(remaining);
|
|
101
|
+
if (remaining < 0n) {
|
|
102
|
+
state.reasonCodes.push(kind === 'perSource' ? 'source_budget_exceeded' : 'specialist_budget_exceeded');
|
|
103
|
+
state.auditNotes.push(`Denied: ${kind} spend ${used} plus quote ${amount} exceeds limit ${max} for ${key}.`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function checkAssetNetworkLimit(limits, quote, usage, state) {
|
|
107
|
+
if (!limits)
|
|
108
|
+
return;
|
|
109
|
+
if (!Array.isArray(limits) || limits.length === 0) {
|
|
110
|
+
malformed(state, 'perAssetNetwork must be a non-empty array');
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
for (const limit of limits) {
|
|
114
|
+
if (!isPlainObject(limit)) {
|
|
115
|
+
malformed(state, 'perAssetNetwork entries must be plain objects');
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (typeof limit.asset !== 'string' || typeof limit.network !== 'string') {
|
|
119
|
+
malformed(state, 'perAssetNetwork entries must include string asset and network');
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const matches = limits.filter((limit) => normalizeAsset(limit.asset) === quote.asset && normalizeNetwork(limit.network) === quote.network);
|
|
124
|
+
if (matches.length === 0) {
|
|
125
|
+
state.reasonCodes.push('unsupported_asset_network');
|
|
126
|
+
state.auditNotes.push(`Denied: ${quote.asset} on ${quote.network} is not in the local budget policy asset/network allowlist.`);
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const max = normalizeLimit(matches[0], `perAssetNetwork.${quote.asset}.${quote.network}`, state);
|
|
130
|
+
const used = normalizeUsage(usage?.[assetNetworkKey(quote.asset, quote.network)], `perAssetNetwork.${quote.asset}.${quote.network}.spent`, state);
|
|
131
|
+
if (max === undefined || used === undefined)
|
|
132
|
+
return;
|
|
133
|
+
const remaining = max - used - quote.amount;
|
|
134
|
+
state.remainingBudget.perAssetNetwork = stringifyRemaining(remaining);
|
|
135
|
+
if (remaining < 0n) {
|
|
136
|
+
state.reasonCodes.push('asset_network_budget_exceeded');
|
|
137
|
+
state.auditNotes.push(`Denied: ${quote.asset}/${quote.network} spend ${used} plus quote ${quote.amount} exceeds limit ${max}.`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
function checkCallCount(limit, usedCalls, state) {
|
|
141
|
+
if (!limit)
|
|
142
|
+
return;
|
|
143
|
+
if (!isPlainObject(limit)) {
|
|
144
|
+
malformed(state, 'callCount must be a plain object');
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (!Number.isInteger(limit.maxCalls) || limit.maxCalls < 0) {
|
|
148
|
+
malformed(state, 'callCount.maxCalls must be a non-negative integer');
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const used = usedCalls ?? 0;
|
|
152
|
+
if (!Number.isInteger(used) || used < 0) {
|
|
153
|
+
malformed(state, 'usage.callCount must be a non-negative integer');
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const remaining = limit.maxCalls - used - 1;
|
|
157
|
+
state.remainingBudget.callCount = Math.max(0, remaining);
|
|
158
|
+
if (remaining < 0) {
|
|
159
|
+
state.reasonCodes.push('call_count_exceeded');
|
|
160
|
+
state.auditNotes.push(`Denied: call count ${used} plus this call exceeds limit ${limit.maxCalls}.`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function normalizeLimit(limit, path, state) {
|
|
164
|
+
if (!isPlainObject(limit)) {
|
|
165
|
+
malformed(state, `${path} must be a plain object`);
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
const amount = normalizeAmount(limit.maxAmount);
|
|
169
|
+
if (amount === undefined || amount < 0n) {
|
|
170
|
+
malformed(state, `${path}.maxAmount must be a non-negative integer amount`);
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
return amount;
|
|
174
|
+
}
|
|
175
|
+
function normalizeUsage(amount, path, state) {
|
|
176
|
+
if (amount === undefined)
|
|
177
|
+
return 0n;
|
|
178
|
+
const normalized = normalizeAmount(amount);
|
|
179
|
+
if (normalized === undefined || normalized < 0n) {
|
|
180
|
+
malformed(state, `${path} must be a non-negative integer amount`);
|
|
181
|
+
return undefined;
|
|
182
|
+
}
|
|
183
|
+
return normalized;
|
|
184
|
+
}
|
|
185
|
+
function normalizeAmount(amount) {
|
|
186
|
+
if (typeof amount === 'bigint')
|
|
187
|
+
return amount;
|
|
188
|
+
if (typeof amount === 'number') {
|
|
189
|
+
if (!Number.isSafeInteger(amount))
|
|
190
|
+
return undefined;
|
|
191
|
+
return BigInt(amount);
|
|
192
|
+
}
|
|
193
|
+
if (typeof amount === 'string' && /^\d+$/.test(amount))
|
|
194
|
+
return BigInt(amount);
|
|
195
|
+
return undefined;
|
|
196
|
+
}
|
|
197
|
+
function isPlainObject(value) {
|
|
198
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value) && Object.getPrototypeOf(value) === Object.prototype;
|
|
199
|
+
}
|
|
200
|
+
function decision(allowed, state, quote) {
|
|
201
|
+
return {
|
|
202
|
+
schemaVersion: 'reddi.budget-policy-decision.v1',
|
|
203
|
+
allowed,
|
|
204
|
+
reasonCodes: dedupeReasons(state.reasonCodes),
|
|
205
|
+
quotedAmount: quote ? {
|
|
206
|
+
amount: String(quote.amount),
|
|
207
|
+
asset: quote.asset,
|
|
208
|
+
network: quote.network,
|
|
209
|
+
source: quote.source,
|
|
210
|
+
specialist: quote.specialist,
|
|
211
|
+
} : null,
|
|
212
|
+
remainingBudget: state.remainingBudget,
|
|
213
|
+
auditNotes: state.auditNotes,
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
function malformed(state, note) {
|
|
217
|
+
state.reasonCodes.push('malformed_limit');
|
|
218
|
+
state.auditNotes.push(`Denied: ${note}.`);
|
|
219
|
+
}
|
|
220
|
+
function stringifyRemaining(value) {
|
|
221
|
+
return String(value < 0n ? 0n : value);
|
|
222
|
+
}
|
|
223
|
+
function dedupeReasons(reasons) {
|
|
224
|
+
return Array.from(new Set(reasons));
|
|
225
|
+
}
|
|
226
|
+
function assetNetworkKey(asset, network) {
|
|
227
|
+
return `${normalizeAsset(asset)}:${normalizeNetwork(network)}`;
|
|
228
|
+
}
|
|
229
|
+
function normalizeAsset(asset) {
|
|
230
|
+
return asset.trim().toUpperCase();
|
|
231
|
+
}
|
|
232
|
+
function normalizeNetwork(network) {
|
|
233
|
+
return network.trim().toLowerCase();
|
|
234
|
+
}
|
package/dist/buyer.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { PublicKey, TransactionInstruction } from '@solana/web3.js';
|
|
2
|
+
import type { SolanaPaymentNetwork, X402Challenge, X402FeeTerms, X402PaymentReceipt } from './types';
|
|
3
|
+
/** What the buyer chose to buy, taken from the listing they selected, never from the challenge. */
|
|
4
|
+
export interface BuyerListing {
|
|
5
|
+
/** Provider wallet named on the listing. */
|
|
6
|
+
payTo: string;
|
|
7
|
+
/** Listed price per call, as a decimal amount of `currency`. */
|
|
8
|
+
amount: string | number;
|
|
9
|
+
currency: string;
|
|
10
|
+
}
|
|
11
|
+
export interface BuyerDirectPaymentInput {
|
|
12
|
+
/** Raw `x402-request` header value from the provider's 402 response, or an already parsed object. */
|
|
13
|
+
challenge: unknown;
|
|
14
|
+
listing: BuyerListing;
|
|
15
|
+
/** Network the buyer's wallet is connected to. */
|
|
16
|
+
network: SolanaPaymentNetwork;
|
|
17
|
+
/** Most the buyer will pay for this call, as a decimal amount of the listing currency. */
|
|
18
|
+
spendCap: string | number;
|
|
19
|
+
payer: PublicKey;
|
|
20
|
+
/** Required for a token currency: the buyer's own configured mint for the listing currency. */
|
|
21
|
+
mint?: PublicKey;
|
|
22
|
+
/** Older name for `mint`, kept for USDC callers. */
|
|
23
|
+
usdcMint?: PublicKey;
|
|
24
|
+
payerTokenAccount?: PublicKey;
|
|
25
|
+
/** Highest fee rate the buyer accepts. Defaults to the rate in force now (protocolFeeBpsAt). */
|
|
26
|
+
maxFeeBps?: number;
|
|
27
|
+
}
|
|
28
|
+
export type BuyerPaymentRefusalReason = 'invalid_challenge' | 'wrong_network' | 'wrong_payee' | 'wrong_currency' | 'price_above_listing' | 'above_spend_cap' | 'fee_terms_rejected';
|
|
29
|
+
export type BuyerDirectPaymentPlan = {
|
|
30
|
+
ok: true;
|
|
31
|
+
challenge: X402Challenge;
|
|
32
|
+
instructions: TransactionInstruction[];
|
|
33
|
+
/** Everything the buyer pays for the call, in base units. Equals the challenge amount. */
|
|
34
|
+
totalBaseUnits: bigint;
|
|
35
|
+
fee?: X402FeeTerms;
|
|
36
|
+
/** Builds the receipt to send back once the wallet has signed and the transaction is confirmed. */
|
|
37
|
+
receiptFor(signature: string): X402PaymentReceipt;
|
|
38
|
+
} | {
|
|
39
|
+
ok: false;
|
|
40
|
+
reason: BuyerPaymentRefusalReason;
|
|
41
|
+
message: string;
|
|
42
|
+
};
|
|
43
|
+
/** Reads a provider challenge without trusting its shape. Returns undefined when a required field is missing or mistyped. */
|
|
44
|
+
export declare function parseX402Challenge(value: unknown): X402Challenge | undefined;
|
|
45
|
+
/**
|
|
46
|
+
* Decides whether a buyer should pay a provider's challenge, and if so builds
|
|
47
|
+
* the payment instructions. Every check runs before any instruction exists:
|
|
48
|
+
* the challenge must name the wallet's network, the provider and currency of
|
|
49
|
+
* the listing the buyer selected, a price no higher than the listed price and
|
|
50
|
+
* the buyer's spend cap, and fee terms that add up at an accepted rate.
|
|
51
|
+
*
|
|
52
|
+
* This signs nothing and sends nothing. The wallet does both.
|
|
53
|
+
*/
|
|
54
|
+
export declare function planBuyerDirectPayment(input: BuyerDirectPaymentInput): BuyerDirectPaymentPlan;
|
package/dist/buyer.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseX402Challenge = parseX402Challenge;
|
|
4
|
+
exports.planBuyerDirectPayment = planBuyerDirectPayment;
|
|
5
|
+
const direct_payment_1 = require("./direct-payment");
|
|
6
|
+
const payment_1 = require("./payment");
|
|
7
|
+
const NETWORKS = ['solana-devnet', 'solana-mainnet-beta', 'solana-testnet'];
|
|
8
|
+
function refuse(reason, message) {
|
|
9
|
+
return { ok: false, reason, message };
|
|
10
|
+
}
|
|
11
|
+
/** Reads a provider challenge without trusting its shape. Returns undefined when a required field is missing or mistyped. */
|
|
12
|
+
function parseX402Challenge(value) {
|
|
13
|
+
let candidate = value;
|
|
14
|
+
if (typeof value === 'string') {
|
|
15
|
+
try {
|
|
16
|
+
candidate = JSON.parse(value);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
if (!candidate || typeof candidate !== 'object' || Array.isArray(candidate))
|
|
23
|
+
return undefined;
|
|
24
|
+
const c = candidate;
|
|
25
|
+
const isText = (v) => typeof v === 'string' && v.length > 0;
|
|
26
|
+
if (!isText(c.network) || !NETWORKS.includes(c.network))
|
|
27
|
+
return undefined;
|
|
28
|
+
if (!isText(c.payTo) || !(0, payment_1.isValidSolanaPublicKey)(c.payTo))
|
|
29
|
+
return undefined;
|
|
30
|
+
if (!isText(c.currency) || !isText(c.nonce) || !isText(c.endpoint))
|
|
31
|
+
return undefined;
|
|
32
|
+
if (typeof c.amount !== 'string' && typeof c.amount !== 'number')
|
|
33
|
+
return undefined;
|
|
34
|
+
if (c.memo !== undefined && typeof c.memo !== 'string')
|
|
35
|
+
return undefined;
|
|
36
|
+
let fee;
|
|
37
|
+
if (c.fee !== undefined) {
|
|
38
|
+
const f = c.fee;
|
|
39
|
+
if (!f || typeof f !== 'object')
|
|
40
|
+
return undefined;
|
|
41
|
+
if (typeof f.bps !== 'number' || !Number.isInteger(f.bps) || f.bps < 0)
|
|
42
|
+
return undefined;
|
|
43
|
+
if (!isText(f.payTo) || !(0, payment_1.isValidSolanaPublicKey)(f.payTo))
|
|
44
|
+
return undefined;
|
|
45
|
+
if (!isText(f.amount) || !isText(f.providerAmount))
|
|
46
|
+
return undefined;
|
|
47
|
+
if (f.cap !== undefined && !isText(f.cap))
|
|
48
|
+
return undefined;
|
|
49
|
+
fee = { bps: f.bps, payTo: f.payTo, amount: f.amount, providerAmount: f.providerAmount, ...(isText(f.cap) ? { cap: f.cap } : {}) };
|
|
50
|
+
}
|
|
51
|
+
const challenge = {
|
|
52
|
+
version: isText(c.version) ? c.version : '1',
|
|
53
|
+
network: c.network,
|
|
54
|
+
payTo: c.payTo,
|
|
55
|
+
amount: c.amount,
|
|
56
|
+
currency: c.currency,
|
|
57
|
+
endpoint: c.endpoint,
|
|
58
|
+
nonce: c.nonce,
|
|
59
|
+
};
|
|
60
|
+
if (typeof c.memo === 'string')
|
|
61
|
+
challenge.memo = c.memo;
|
|
62
|
+
if (fee)
|
|
63
|
+
challenge.fee = fee;
|
|
64
|
+
return challenge;
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Decides whether a buyer should pay a provider's challenge, and if so builds
|
|
68
|
+
* the payment instructions. Every check runs before any instruction exists:
|
|
69
|
+
* the challenge must name the wallet's network, the provider and currency of
|
|
70
|
+
* the listing the buyer selected, a price no higher than the listed price and
|
|
71
|
+
* the buyer's spend cap, and fee terms that add up at an accepted rate.
|
|
72
|
+
*
|
|
73
|
+
* This signs nothing and sends nothing. The wallet does both.
|
|
74
|
+
*/
|
|
75
|
+
function planBuyerDirectPayment(input) {
|
|
76
|
+
const challenge = parseX402Challenge(input.challenge);
|
|
77
|
+
if (!challenge)
|
|
78
|
+
return refuse('invalid_challenge', 'the provider challenge is missing a required field or is not valid');
|
|
79
|
+
if (challenge.network !== input.network) {
|
|
80
|
+
return refuse('wrong_network', `the challenge is for ${challenge.network} but the wallet is on ${input.network}`);
|
|
81
|
+
}
|
|
82
|
+
if (challenge.payTo !== input.listing.payTo) {
|
|
83
|
+
return refuse('wrong_payee', 'the challenge pays a different wallet from the selected listing');
|
|
84
|
+
}
|
|
85
|
+
if (challenge.currency !== input.listing.currency) {
|
|
86
|
+
return refuse('wrong_currency', `the challenge asks for ${challenge.currency} but the listing is priced in ${input.listing.currency}`);
|
|
87
|
+
}
|
|
88
|
+
const currency = (0, payment_1.directPaymentCurrency)(challenge.currency);
|
|
89
|
+
const decimals = currency?.decimals;
|
|
90
|
+
if (currency === undefined || decimals === undefined)
|
|
91
|
+
return refuse('wrong_currency', `direct payment in ${challenge.currency} is not supported`);
|
|
92
|
+
const price = (0, payment_1.decimalToBaseUnits)(challenge.amount, decimals);
|
|
93
|
+
const listed = (0, payment_1.decimalToBaseUnits)(input.listing.amount, decimals);
|
|
94
|
+
const cap = (0, payment_1.decimalToBaseUnits)(input.spendCap, decimals);
|
|
95
|
+
if (price === undefined)
|
|
96
|
+
return refuse('invalid_challenge', 'the challenge amount is not a valid positive amount');
|
|
97
|
+
if (listed === undefined)
|
|
98
|
+
return refuse('price_above_listing', 'the selected listing has no valid price to compare against');
|
|
99
|
+
if (cap === undefined)
|
|
100
|
+
return refuse('above_spend_cap', 'a spend cap greater than zero is required');
|
|
101
|
+
if (price > listed)
|
|
102
|
+
return refuse('price_above_listing', 'the challenge asks for more than the listed price');
|
|
103
|
+
if (price > cap)
|
|
104
|
+
return refuse('above_spend_cap', 'the challenge asks for more than the spend cap');
|
|
105
|
+
const tokenMint = currency.tokenProgram === undefined
|
|
106
|
+
? undefined
|
|
107
|
+
: input.mint ?? (challenge.currency === 'USDC' ? input.usdcMint : undefined);
|
|
108
|
+
let instructions;
|
|
109
|
+
try {
|
|
110
|
+
instructions = (0, direct_payment_1.buildDirectPaymentInstructions)({
|
|
111
|
+
challenge,
|
|
112
|
+
payer: input.payer,
|
|
113
|
+
mint: tokenMint,
|
|
114
|
+
payerTokenAccount: input.payerTokenAccount,
|
|
115
|
+
maxFeeBps: input.maxFeeBps ?? (0, payment_1.protocolFeeBpsAt)(),
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
const message = error instanceof Error ? error.message : 'payment instructions could not be built';
|
|
120
|
+
return refuse(/fee/.test(message) ? 'fee_terms_rejected' : 'invalid_challenge', message);
|
|
121
|
+
}
|
|
122
|
+
const payer = input.payer.toBase58();
|
|
123
|
+
const mint = tokenMint?.toBase58();
|
|
124
|
+
return {
|
|
125
|
+
ok: true,
|
|
126
|
+
challenge,
|
|
127
|
+
instructions,
|
|
128
|
+
totalBaseUnits: price,
|
|
129
|
+
fee: challenge.fee,
|
|
130
|
+
receiptFor(signature) {
|
|
131
|
+
if (!signature || /^mock_/i.test(signature))
|
|
132
|
+
throw new Error('a real transaction signature is required');
|
|
133
|
+
const receipt = {
|
|
134
|
+
network: challenge.network,
|
|
135
|
+
payTo: challenge.payTo,
|
|
136
|
+
amount: challenge.amount,
|
|
137
|
+
currency: challenge.currency,
|
|
138
|
+
nonce: challenge.nonce,
|
|
139
|
+
signature,
|
|
140
|
+
payer,
|
|
141
|
+
};
|
|
142
|
+
if (mint)
|
|
143
|
+
receipt.mint = mint;
|
|
144
|
+
return receipt;
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { Keypair, PublicKey, type Connection } from '@solana/web3.js';
|
|
2
|
+
import type { X402Challenge, X402PaymentReceipt } from './types';
|
|
3
|
+
declare const APPROVAL_PHRASE = "EXECUTE_DEVNET_X402_SPECIALIST_CALL";
|
|
4
|
+
export type DevnetUsdcTransferResult = {
|
|
5
|
+
signature: string;
|
|
6
|
+
destinationTokenAccount: string;
|
|
7
|
+
};
|
|
8
|
+
export type DevnetUsdcPaymentClient = {
|
|
9
|
+
getSolBalanceLamports(publicKey: PublicKey): Promise<number>;
|
|
10
|
+
getUsdcBalanceMicroUnits(owner: PublicKey, mint: PublicKey): Promise<bigint>;
|
|
11
|
+
getOrCreateDestinationTokenAccount(payTo: PublicKey, mint: PublicKey): Promise<string>;
|
|
12
|
+
submitUsdcTransfer(input: {
|
|
13
|
+
payer: Keypair;
|
|
14
|
+
payTo: PublicKey;
|
|
15
|
+
mint: PublicKey;
|
|
16
|
+
amountMicroUnits: bigint;
|
|
17
|
+
destinationTokenAccount: string;
|
|
18
|
+
challenge: X402Challenge;
|
|
19
|
+
}): Promise<DevnetUsdcTransferResult>;
|
|
20
|
+
};
|
|
21
|
+
export type DevnetUsdcPaymentConfig = {
|
|
22
|
+
rpcUrl: string;
|
|
23
|
+
usdcMint: string;
|
|
24
|
+
walletKeypairPath: string;
|
|
25
|
+
endpointAllowlist: string[];
|
|
26
|
+
maxUsdcMicroUnits: bigint | number | string;
|
|
27
|
+
minFeeLamports?: number;
|
|
28
|
+
};
|
|
29
|
+
export type DevnetUsdcPaymentReadiness = {
|
|
30
|
+
schemaVersion: 'reddi.x402-solana.devnet-usdc-payment-readiness.v1';
|
|
31
|
+
ready: boolean;
|
|
32
|
+
boundary: 'solana-devnet-only-no-mainnet';
|
|
33
|
+
reasons: string[];
|
|
34
|
+
payer: string | null;
|
|
35
|
+
challenge: Pick<X402Challenge, 'network' | 'payTo' | 'amount' | 'currency' | 'endpoint' | 'nonce'>;
|
|
36
|
+
spend: {
|
|
37
|
+
amountMicroUnits: string;
|
|
38
|
+
maxUsdcMicroUnits: string;
|
|
39
|
+
capRespected: boolean;
|
|
40
|
+
};
|
|
41
|
+
balances: {
|
|
42
|
+
solLamports: number | null;
|
|
43
|
+
usdcMicroUnits: string | null;
|
|
44
|
+
};
|
|
45
|
+
destinationTokenAccount: string | null;
|
|
46
|
+
};
|
|
47
|
+
export type ExecuteDevnetUsdcPaymentInput = {
|
|
48
|
+
challenge: X402Challenge;
|
|
49
|
+
config: DevnetUsdcPaymentConfig;
|
|
50
|
+
client: DevnetUsdcPaymentClient;
|
|
51
|
+
approvalPhrase: typeof APPROVAL_PHRASE;
|
|
52
|
+
};
|
|
53
|
+
export declare function loadDevnetKeypair(path: string): Keypair;
|
|
54
|
+
export declare function assertDevnetRpcUrl(rpcUrl: string): void;
|
|
55
|
+
export declare function assertEndpointAllowed(endpoint: string, allowlist: string[]): void;
|
|
56
|
+
export declare function usdcAmountToMicroUnits(amount: string | number): bigint;
|
|
57
|
+
export declare function validateDevnetUsdcChallenge(challenge: X402Challenge, config: DevnetUsdcPaymentConfig): {
|
|
58
|
+
payTo: PublicKey;
|
|
59
|
+
mint: PublicKey;
|
|
60
|
+
amountMicroUnits: bigint;
|
|
61
|
+
maxUsdcMicroUnits: bigint;
|
|
62
|
+
};
|
|
63
|
+
export declare function prepareDevnetUsdcPayment(input: {
|
|
64
|
+
challenge: X402Challenge;
|
|
65
|
+
config: DevnetUsdcPaymentConfig;
|
|
66
|
+
client: Pick<DevnetUsdcPaymentClient, 'getSolBalanceLamports' | 'getUsdcBalanceMicroUnits' | 'getOrCreateDestinationTokenAccount'>;
|
|
67
|
+
}): Promise<DevnetUsdcPaymentReadiness>;
|
|
68
|
+
export declare function executeDevnetUsdcPayment(input: ExecuteDevnetUsdcPaymentInput): Promise<X402PaymentReceipt>;
|
|
69
|
+
export declare function createSolanaDevnetUsdcPaymentClient(connection: Connection): DevnetUsdcPaymentClient;
|
|
70
|
+
export declare function challengeFromX402RequestHeader(header: string): X402Challenge;
|
|
71
|
+
/**
|
|
72
|
+
* The proof headers for presenting a devnet USDC receipt with `body`, signed by
|
|
73
|
+
* the same wallet file that paid. Send them with `x402-payment` on the paid retry.
|
|
74
|
+
*/
|
|
75
|
+
export declare function devnetUsdcPaymentProofHeaders(input: {
|
|
76
|
+
receipt: X402PaymentReceipt;
|
|
77
|
+
body: Uint8Array | string;
|
|
78
|
+
walletKeypairPath: string;
|
|
79
|
+
}): Promise<Record<string, string>>;
|
|
80
|
+
export {};
|