@wasit-dev/core 0.8.0-beta.1 → 0.8.0-beta.3
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 +13 -2
- package/dist/baseline.d.ts +3 -1
- package/dist/baseline.js +23 -9
- package/dist/check.d.ts +1 -1
- package/dist/ci-report.js +20 -8
- package/dist/config-writer.d.ts +96 -0
- package/dist/config-writer.js +281 -0
- package/dist/guard/budget.d.ts +7 -4
- package/dist/guard/budget.js +11 -4
- package/dist/guard/ci-event.d.ts +6 -0
- package/dist/guard/ci-event.js +7 -3
- package/dist/guard/ci-mainnet.d.ts +59 -0
- package/dist/guard/ci-mainnet.js +149 -0
- package/dist/guard/horizon.d.ts +30 -0
- package/dist/guard/horizon.js +107 -0
- package/dist/guard/mainnet-optin.d.ts +3 -1
- package/dist/guard/mainnet-optin.js +8 -2
- package/dist/guard/mainnet-payer.d.ts +66 -0
- package/dist/guard/mainnet-payer.js +92 -0
- package/dist/guard/mainnet-plan.d.ts +133 -0
- package/dist/guard/mainnet-plan.js +208 -0
- package/dist/guard/mainnet-run.d.ts +87 -0
- package/dist/guard/mainnet-run.js +225 -0
- package/dist/guard/networks.d.ts +9 -8
- package/dist/guard/networks.js +21 -10
- package/dist/guard/optin.d.ts +106 -0
- package/dist/guard/optin.js +202 -0
- package/dist/guard/run-ledger.d.ts +212 -0
- package/dist/guard/run-ledger.js +426 -0
- package/dist/guard/run-lock.d.ts +62 -0
- package/dist/guard/run-lock.js +172 -0
- package/dist/guard/signed-terms.d.ts +135 -0
- package/dist/guard/signed-terms.js +252 -0
- package/dist/index.d.ts +18 -7
- package/dist/index.js +19 -5
- package/dist/mpp/channel-credential.d.ts +13 -1
- package/dist/mpp/channel-credential.js +18 -2
- package/dist/mpp/channel.d.ts +6 -0
- package/dist/mpp/channel.js +7 -3
- package/dist/mpp/charge.d.ts +31 -1
- package/dist/mpp/charge.js +74 -20
- package/dist/mpp/plan.d.ts +77 -0
- package/dist/mpp/plan.js +188 -0
- package/dist/mpp/suite.d.ts +6 -0
- package/dist/mpp/suite.js +2 -1
- package/dist/route-reader.d.ts +124 -0
- package/dist/route-reader.js +349 -0
- package/dist/wallet.d.ts +58 -1
- package/dist/wallet.js +128 -0
- package/dist/x402/chains/stellar.d.ts +39 -4
- package/dist/x402/chains/stellar.js +224 -19
- package/dist/x402/chains/svm.js +6 -2
- package/dist/x402/chains/types.d.ts +44 -2
- package/dist/x402/plan.d.ts +102 -0
- package/dist/x402/plan.js +380 -6
- package/dist/x402/rejected-request.d.ts +10 -0
- package/dist/x402/rejected-request.js +18 -0
- package/dist/x402/simulator.d.ts +34 -0
- package/dist/x402/simulator.js +461 -50
- package/package.json +9 -9
package/dist/x402/plan.js
CHANGED
|
@@ -9,11 +9,25 @@
|
|
|
9
9
|
* the payment gets a refusal, not a signature.
|
|
10
10
|
*
|
|
11
11
|
* It sends no payment, reads no key and signs nothing.
|
|
12
|
+
*
|
|
13
|
+
* A mainnet run (a live opt-in, spec B5) is planned by stricter rules: first
|
|
14
|
+
* the token's decimals, the payer's USDC (through the RPC and on public
|
|
15
|
+
* Horizon, $10 at most) and the RPC's latest ledger beside Horizon's are read,
|
|
16
|
+
* before the target is asked anything; then every endpoint must plan, by the
|
|
17
|
+
* mainnet rules. Any refusal stops the opt-in. A plan that passes is recorded
|
|
18
|
+
* on it, and is the only plan its checks pay by.
|
|
12
19
|
*/
|
|
20
|
+
import { isLoopbackUrl } from "../config.js";
|
|
21
|
+
import { ConfigurationError } from "../errors.js";
|
|
13
22
|
import { sanitizeText } from "../sanitize.js";
|
|
23
|
+
import { readHorizonAccount, readHorizonLatestLedger } from "../guard/horizon.js";
|
|
24
|
+
import { assertMainnetPayerBalance } from "../guard/mainnet-payer.js";
|
|
25
|
+
import { MAINNET_USDC, MainnetPlanRefusedError, PUBNET_HORIZON_URL, assertAnchorNearHorizon, assertBalancesAgree, assertMainnetDecimals, assertMainnetOption, assertMainnetPin, paidUrlOf, } from "../guard/mainnet-plan.js";
|
|
14
26
|
import { assertPaymentNetworkAllowed } from "../guard/networks.js";
|
|
15
|
-
import {
|
|
27
|
+
import { MainnetRunRefusedError, anchorOfOptIn, isLiveOptIn, recordMainnetPlan } from "../guard/optin.js";
|
|
28
|
+
import { PER_PAYMENT_CAP_USD, PER_RUN_CAP_USD, PaymentGuardRefusedError, RunBudget, assertPinned, formatUsd, parseAmount, plannedSignatures, shown, usdAsset, usdFromBaseUnits, usdFromDollars, } from "../guard/budget.js";
|
|
16
29
|
import { paymentChainFor } from "./chains/index.js";
|
|
30
|
+
const STELLAR_PUBNET = "stellar:pubnet";
|
|
17
31
|
import { REJECTED_REQUEST_MAX_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_LIFETIME_SECONDS } from "./rejected-request.js";
|
|
18
32
|
import { readPaymentChallenge } from "./simulator.js";
|
|
19
33
|
function message(error) {
|
|
@@ -28,7 +42,44 @@ const nothing = (name, status, reason, option) => ({
|
|
|
28
42
|
worstCase: 0n,
|
|
29
43
|
worstCaseUsd: 0n,
|
|
30
44
|
});
|
|
31
|
-
|
|
45
|
+
/**
|
|
46
|
+
* The URL rule of a mainnet endpoint, before it is asked anything: https, or
|
|
47
|
+
* on this machine (a local service, as the validation runs one), and no user
|
|
48
|
+
* name or password in it (they can hide which host it is). Returns where it
|
|
49
|
+
* pays, origin and path.
|
|
50
|
+
*/
|
|
51
|
+
function mainnetEndpointUrl(target) {
|
|
52
|
+
let url;
|
|
53
|
+
try {
|
|
54
|
+
url = new URL(target);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
throw new MainnetPlanRefusedError("endpoint", "Its URL does not parse.");
|
|
58
|
+
}
|
|
59
|
+
if (url.username !== "" || url.password !== "") {
|
|
60
|
+
throw new MainnetPlanRefusedError("endpoint", "Its URL carries a user name or password: a mainnet run pays a URL whose host is plain to read.");
|
|
61
|
+
}
|
|
62
|
+
if (url.protocol !== "https:" && !isLoopbackUrl(target)) {
|
|
63
|
+
throw new MainnetPlanRefusedError("endpoint", `A mainnet run pays an https endpoint only, or one on this machine, and this one is ${url.protocol.replace(/:$/, "")} on ${url.host}.`);
|
|
64
|
+
}
|
|
65
|
+
return paidUrlOf(target);
|
|
66
|
+
}
|
|
67
|
+
async function planEndpoint(network, pin, endpoint, mainnet) {
|
|
68
|
+
if (!mainnet)
|
|
69
|
+
return planEndpointTerms(network, pin, endpoint, undefined);
|
|
70
|
+
let url;
|
|
71
|
+
try {
|
|
72
|
+
url = mainnetEndpointUrl(endpoint.target);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error instanceof MainnetPlanRefusedError)
|
|
76
|
+
return nothing(endpoint.name, "refused", message(error));
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
return { ...(await planEndpointTerms(network, pin, endpoint, url)), url };
|
|
80
|
+
}
|
|
81
|
+
async function planEndpointTerms(network, pin, endpoint, url) {
|
|
82
|
+
const mainnet = url !== undefined;
|
|
32
83
|
let read;
|
|
33
84
|
try {
|
|
34
85
|
read = await readPaymentChallenge({ ...endpoint, network });
|
|
@@ -39,6 +90,10 @@ async function planEndpoint(network, pin, endpoint) {
|
|
|
39
90
|
}
|
|
40
91
|
const { paymentRequired, selected } = read;
|
|
41
92
|
try {
|
|
93
|
+
// A mainnet endpoint pays the URL in the config, not one a redirect leads to.
|
|
94
|
+
if (url !== undefined && paidUrlOf(read.payUrl) !== url) {
|
|
95
|
+
throw new MainnetPlanRefusedError("endpoint", `It answers through a redirect to ${shown(paidUrlOf(read.payUrl))}: a mainnet run pays the URL in the config only.`);
|
|
96
|
+
}
|
|
42
97
|
assertPinned(network, paymentRequired.accepts, pin);
|
|
43
98
|
const amount = parseAmount(selected.amount);
|
|
44
99
|
const option = {
|
|
@@ -49,6 +104,9 @@ async function planEndpoint(network, pin, endpoint) {
|
|
|
49
104
|
amount,
|
|
50
105
|
maxTimeoutSeconds: selected.maxTimeoutSeconds,
|
|
51
106
|
};
|
|
107
|
+
// Exact, on stellar:pubnet, in USDC, valid for at most 300 s (B3).
|
|
108
|
+
if (mainnet)
|
|
109
|
+
assertMainnetOption(selected);
|
|
52
110
|
const asset = usdAsset(network, selected.asset);
|
|
53
111
|
const price = RunBudget.valueOf(network, selected.asset, amount);
|
|
54
112
|
if (asset === undefined || price === undefined) {
|
|
@@ -79,8 +137,9 @@ async function planEndpoint(network, pin, endpoint) {
|
|
|
79
137
|
};
|
|
80
138
|
}
|
|
81
139
|
catch (error) {
|
|
82
|
-
if (error instanceof PaymentGuardRefusedError)
|
|
140
|
+
if (error instanceof PaymentGuardRefusedError || error instanceof MainnetPlanRefusedError) {
|
|
83
141
|
return nothing(endpoint.name, "refused", message(error));
|
|
142
|
+
}
|
|
84
143
|
throw error;
|
|
85
144
|
}
|
|
86
145
|
}
|
|
@@ -91,12 +150,14 @@ async function planEndpoint(network, pin, endpoint) {
|
|
|
91
150
|
* authorization lifetime) is part of the opt-in, not of this version.
|
|
92
151
|
*/
|
|
93
152
|
export async function planX402Run(options) {
|
|
153
|
+
if (options.mainnet !== undefined)
|
|
154
|
+
return planMainnetRun(options, options.mainnet);
|
|
94
155
|
assertPaymentNetworkAllowed("x402", options.network);
|
|
95
156
|
const budget = new RunBudget(options.maxRunUsd === undefined ? {} : { maxRunUsd: options.maxRunUsd });
|
|
96
157
|
const capLowered = budget.capUsd < usdFromDollars(PER_RUN_CAP_USD);
|
|
97
158
|
const endpoints = [];
|
|
98
159
|
for (const endpoint of options.endpoints) {
|
|
99
|
-
endpoints.push(await planEndpoint(options.network, options.pin, endpoint));
|
|
160
|
+
endpoints.push(await planEndpoint(options.network, options.pin, endpoint, false));
|
|
100
161
|
}
|
|
101
162
|
const planned = endpoints.filter((endpoint) => endpoint.status === "planned");
|
|
102
163
|
const worstCaseUsd = planned.reduce((sum, endpoint) => sum + endpoint.worstCaseUsd, 0n);
|
|
@@ -119,6 +180,302 @@ export async function planX402Run(options) {
|
|
|
119
180
|
`Select fewer endpoints with --endpoint, or test a cheaper route.`,
|
|
120
181
|
};
|
|
121
182
|
}
|
|
183
|
+
/** Public Horizon, as a mainnet plan reads it; tests point it at a stand-in. */
|
|
184
|
+
let pubnetHorizon = PUBNET_HORIZON_URL;
|
|
185
|
+
/** Tests only: where a mainnet plan reads Horizon; undefined puts back the public one. Not exported from the package. */
|
|
186
|
+
export function setPubnetHorizonForTesting(base) {
|
|
187
|
+
pubnetHorizon = base ?? PUBNET_HORIZON_URL;
|
|
188
|
+
}
|
|
189
|
+
function originOf(url) {
|
|
190
|
+
try {
|
|
191
|
+
return new URL(url).origin;
|
|
192
|
+
}
|
|
193
|
+
catch {
|
|
194
|
+
return "the RPC";
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* The reads of a mainnet plan, in this order, each refusing on its own: the
|
|
199
|
+
* token's decimals (7); the payer's USDC through the RPC ($10 at most); the
|
|
200
|
+
* payer's balances on public Horizon (USDC equal to the RPC's); the RPC's
|
|
201
|
+
* latest ledger beside Horizon's (12 apart at most), which becomes the run's
|
|
202
|
+
* anchor. Nothing is sent to the target, and nothing is signed.
|
|
203
|
+
*/
|
|
204
|
+
async function readMainnet(optIn, chain) {
|
|
205
|
+
const { network, rpcUrl, payer } = optIn;
|
|
206
|
+
const signedTerms = chain.signedTerms;
|
|
207
|
+
const assetDecimals = chain.assetDecimals;
|
|
208
|
+
if (signedTerms === undefined || assetDecimals === undefined) {
|
|
209
|
+
throw new MainnetRunRefusedError("run", `The ${chain.name} adapter cannot read what a mainnet plan reads before it pays.`);
|
|
210
|
+
}
|
|
211
|
+
let decimals;
|
|
212
|
+
try {
|
|
213
|
+
decimals = await assetDecimals.call(chain, network, rpcUrl, MAINNET_USDC.asset);
|
|
214
|
+
}
|
|
215
|
+
catch {
|
|
216
|
+
decimals = undefined;
|
|
217
|
+
}
|
|
218
|
+
assertMainnetDecimals(decimals);
|
|
219
|
+
const usdc = await assertMainnetPayerBalance({
|
|
220
|
+
network,
|
|
221
|
+
payer,
|
|
222
|
+
readBalance: () => chain.payerBalance(network, rpcUrl, payer, MAINNET_USDC.asset),
|
|
223
|
+
});
|
|
224
|
+
const horizon = await readHorizonAccount(pubnetHorizon, payer);
|
|
225
|
+
assertBalancesAgree(usdc, horizon.usdc);
|
|
226
|
+
let rpcLatest;
|
|
227
|
+
try {
|
|
228
|
+
rpcLatest = await signedTerms.latestUnit(network, rpcUrl);
|
|
229
|
+
}
|
|
230
|
+
catch {
|
|
231
|
+
rpcLatest = undefined;
|
|
232
|
+
}
|
|
233
|
+
const horizonLatest = await readHorizonLatestLedger(pubnetHorizon);
|
|
234
|
+
assertAnchorNearHorizon(rpcLatest, horizonLatest);
|
|
235
|
+
anchorOfOptIn(optIn).set(rpcLatest);
|
|
236
|
+
return {
|
|
237
|
+
payer,
|
|
238
|
+
decimals: decimals,
|
|
239
|
+
usdc: usdc,
|
|
240
|
+
native: horizon.native,
|
|
241
|
+
rpcLatest: rpcLatest,
|
|
242
|
+
horizonLatest,
|
|
243
|
+
rpc: originOf(rpcUrl),
|
|
244
|
+
horizon: originOf(pubnetHorizon),
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Why a mainnet run may not start on these endpoints, or undefined: one
|
|
249
|
+
* endpoint that could not be planned keeps the whole run from starting (B4),
|
|
250
|
+
* and so does a worst case above what is left of the budget.
|
|
251
|
+
*/
|
|
252
|
+
function mainnetRefusal(endpoints, worstCaseUsd, budget, capLowered) {
|
|
253
|
+
const unplanned = endpoints.filter((endpoint) => endpoint.status !== "planned");
|
|
254
|
+
if (unplanned.length > 0) {
|
|
255
|
+
const reasons = unplanned.map((endpoint) => `Endpoint ${sanitizeText(endpoint.name)} could not be planned: ` +
|
|
256
|
+
`${(endpoint.reason ?? endpoint.status).replace(/\s*Nothing was signed\.?/g, "").trim().replace(/\.?$/, ".")}`);
|
|
257
|
+
return `This mainnet run does not start: it pays only endpoints it could plan. ${reasons.join(" ")} Nothing was signed.`;
|
|
258
|
+
}
|
|
259
|
+
const remainingUsd = budget.capUsd - budget.spentUsd;
|
|
260
|
+
if (worstCaseUsd <= remainingUsd)
|
|
261
|
+
return undefined;
|
|
262
|
+
const parts = endpoints.map((endpoint) => `${sanitizeText(endpoint.name)} ${formatUsd(endpoint.worstCaseUsd)}`);
|
|
263
|
+
const left = budget.spentUsd === 0n
|
|
264
|
+
? `the ${formatUsd(budget.capUsd)} per run`
|
|
265
|
+
: `the ${formatUsd(remainingUsd)} left of the ${formatUsd(budget.capUsd)} per run`;
|
|
266
|
+
return (`This run could spend up to ${formatUsd(worstCaseUsd)} (${parts.join(", ")}), above ${left}` +
|
|
267
|
+
`${capLowered ? " set by maxRunUsd" : ""}. Nothing was signed. Select fewer endpoints, or test a cheaper route.`);
|
|
268
|
+
}
|
|
269
|
+
/** USDC base units as dollars, exactly ("$1.2733706"). */
|
|
270
|
+
function usdc(units, decimals) {
|
|
271
|
+
return formatUsd(usdFromBaseUnits(units, decimals));
|
|
272
|
+
}
|
|
273
|
+
/**
|
|
274
|
+
* What the planned endpoints need the payer to hold; undefined when no
|
|
275
|
+
* endpoint is planned. With `balance` (a paying run) it carries the balance;
|
|
276
|
+
* the warning is added only once the plan has passed ({@link warnedFunding}).
|
|
277
|
+
*/
|
|
278
|
+
function mainnetFunding(endpoints, decimals, balance) {
|
|
279
|
+
const prices = endpoints.flatMap((endpoint) => (endpoint.status === "planned" && endpoint.option !== undefined ? [endpoint.option.amount] : []));
|
|
280
|
+
if (prices.length === 0)
|
|
281
|
+
return undefined;
|
|
282
|
+
const sum = prices.reduce((total, price) => total + price, 0n);
|
|
283
|
+
const highestPrice = prices.reduce((highest, price) => (price > highest ? price : highest), 0n);
|
|
284
|
+
const minimum = sum + highestPrice;
|
|
285
|
+
const worstCase = endpoints.reduce((total, endpoint) => total + (endpoint.status === "planned" ? endpoint.worstCase : 0n), 0n);
|
|
286
|
+
return { prices: sum, highestPrice, minimum, worstCase, decimals, ...(balance === undefined ? {} : { balance }) };
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* The funds of a paying plan that passed every refusal, with the warning when
|
|
290
|
+
* the balance is at or above the minimum but below the worst case.
|
|
291
|
+
*/
|
|
292
|
+
function warnedFunding(funding) {
|
|
293
|
+
const { balance, decimals, minimum, worstCase } = funding;
|
|
294
|
+
if (balance === undefined || balance < minimum || balance >= worstCase)
|
|
295
|
+
return funding;
|
|
296
|
+
return {
|
|
297
|
+
...funding,
|
|
298
|
+
warning: `Warning: the payer holds ${usdc(balance, decimals)}, less than this run's worst case of ${usdc(worstCase, decimals)}. ` +
|
|
299
|
+
`A service that settles payments it should refuse can take more than the ${usdc(minimum, decimals)} this run needs: ` +
|
|
300
|
+
`funds can be lost that way, and the later checks may then have too little left to run.`,
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
/** The prices clause shared by the refusal, the funds line and the dry run's line. */
|
|
304
|
+
function fundingTerms(funding) {
|
|
305
|
+
const { decimals } = funding;
|
|
306
|
+
return (`at least ${usdc(funding.minimum, decimals)} to finish its checks (the prices, ${usdc(funding.prices, decimals)}, ` +
|
|
307
|
+
`plus the highest price again, ${usdc(funding.highestPrice, decimals)})`);
|
|
308
|
+
}
|
|
309
|
+
/** Why a paying mainnet run may not start for lack of funds, or undefined. */
|
|
310
|
+
function fundingRefusal(funding) {
|
|
311
|
+
if (funding?.balance === undefined || funding.balance >= funding.minimum)
|
|
312
|
+
return undefined;
|
|
313
|
+
const { decimals, balance } = funding;
|
|
314
|
+
return (`This mainnet run does not start: the payer holds ${usdc(balance, decimals)} in USDC, and this run needs ` +
|
|
315
|
+
`${fundingTerms(funding)}: ${usdc(funding.minimum - balance, decimals)} short. Nothing was signed. Add USDC to the ` +
|
|
316
|
+
`payer (it may hold at most $10.00), or select fewer or cheaper endpoints.`);
|
|
317
|
+
}
|
|
318
|
+
/**
|
|
319
|
+
* The dry run of a mainnet run on `stellar:pubnet` (spec B5): each endpoint's
|
|
320
|
+
* unpaid challenge, by the mainnet rules (the URL, exact on pubnet, USDC, a
|
|
321
|
+
* lifetime of at most 300 s, $1 a payment), against the caps. It needs no
|
|
322
|
+
* opt-in because it signs nothing, and it reads no key, so nothing of the
|
|
323
|
+
* payer is read: no balance, and no read of the chain, the RPC or Horizon. A
|
|
324
|
+
* paying run makes those reads first, and refuses on any of them.
|
|
325
|
+
*/
|
|
326
|
+
export async function planMainnetDryRun(options) {
|
|
327
|
+
const budget = new RunBudget(options.maxRunUsd === undefined ? {} : { maxRunUsd: options.maxRunUsd });
|
|
328
|
+
const capLowered = budget.capUsd < usdFromDollars(PER_RUN_CAP_USD);
|
|
329
|
+
const base = {
|
|
330
|
+
network: STELLAR_PUBNET,
|
|
331
|
+
...(options.pin === undefined ? {} : { pin: options.pin }),
|
|
332
|
+
perPaymentCapUsd: usdFromDollars(PER_PAYMENT_CAP_USD),
|
|
333
|
+
capUsd: budget.capUsd,
|
|
334
|
+
capLowered,
|
|
335
|
+
mainnetDryRun: true,
|
|
336
|
+
};
|
|
337
|
+
try {
|
|
338
|
+
// No key is read, so the payee is held to the payer's address only by the paying run.
|
|
339
|
+
assertMainnetPin(options.pin, undefined);
|
|
340
|
+
}
|
|
341
|
+
catch (error) {
|
|
342
|
+
if (error instanceof MainnetPlanRefusedError) {
|
|
343
|
+
return { ...base, endpoints: [], worstCaseUsd: 0n, refusal: `This mainnet run does not start: ${message(error)}` };
|
|
344
|
+
}
|
|
345
|
+
throw error;
|
|
346
|
+
}
|
|
347
|
+
const endpoints = [];
|
|
348
|
+
for (const endpoint of options.endpoints) {
|
|
349
|
+
endpoints.push(await planEndpoint(STELLAR_PUBNET, options.pin, endpoint, true));
|
|
350
|
+
}
|
|
351
|
+
const worstCaseUsd = endpoints
|
|
352
|
+
.filter((endpoint) => endpoint.status === "planned")
|
|
353
|
+
.reduce((sum, endpoint) => sum + endpoint.worstCaseUsd, 0n);
|
|
354
|
+
// No key, so no balance: the plan says what a paying run will hold the payer to.
|
|
355
|
+
const funding = mainnetFunding(endpoints, MAINNET_USDC.decimals);
|
|
356
|
+
const plan = { ...base, endpoints, worstCaseUsd, ...(funding === undefined ? {} : { funding }) };
|
|
357
|
+
const refusal = mainnetRefusal(endpoints, worstCaseUsd, budget, capLowered);
|
|
358
|
+
return refusal === undefined ? plan : { ...plan, refusal };
|
|
359
|
+
}
|
|
360
|
+
/**
|
|
361
|
+
* L1 of a mainnet run: the reads, then each endpoint by the mainnet rules.
|
|
362
|
+
* Every endpoint must plan, and the worst case must fit what is left of the
|
|
363
|
+
* run's budget; otherwise the run is refused and the opt-in stopped. A plan
|
|
364
|
+
* that passes is recorded on the opt-in, once.
|
|
365
|
+
*/
|
|
366
|
+
async function planMainnetRun(options, optIn) {
|
|
367
|
+
if (options.network !== optIn.network) {
|
|
368
|
+
throw new MainnetRunRefusedError("run", `A mainnet opt-in was handed to the plan of a run on another network than ${optIn.network}.`);
|
|
369
|
+
}
|
|
370
|
+
assertPaymentNetworkAllowed("x402", options.network, optIn);
|
|
371
|
+
try {
|
|
372
|
+
return await planLiveMainnetRun(options, optIn);
|
|
373
|
+
}
|
|
374
|
+
catch (error) {
|
|
375
|
+
// Fail closed: whatever stops the plan stops the run, so it is never planned twice.
|
|
376
|
+
optIn.stop(error.message);
|
|
377
|
+
throw error;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
async function planLiveMainnetRun(options, optIn) {
|
|
381
|
+
if (optIn.plan !== undefined)
|
|
382
|
+
throw new MainnetRunRefusedError("run", "The mainnet run already has a plan: it is planned once.");
|
|
383
|
+
if (options.pin !== undefined && (options.pin.payTo !== optIn.pin.payTo || options.pin.asset !== optIn.pin.asset)) {
|
|
384
|
+
throw new MainnetRunRefusedError("run", "The plan was handed another pin than the mainnet run's.");
|
|
385
|
+
}
|
|
386
|
+
if (options.maxRunUsd !== undefined) {
|
|
387
|
+
throw new MainnetRunRefusedError("run", "A mainnet run's cap is set when it is opened; the plan takes no maxRunUsd.");
|
|
388
|
+
}
|
|
389
|
+
const chain = paymentChainFor(options.network);
|
|
390
|
+
if (chain === undefined)
|
|
391
|
+
throw new ConfigurationError(`No payment adapter pays on ${options.network}.`);
|
|
392
|
+
const readings = await readMainnet(optIn, chain);
|
|
393
|
+
const endpoints = [];
|
|
394
|
+
for (const endpoint of options.endpoints) {
|
|
395
|
+
endpoints.push(await planEndpoint(options.network, optIn.pin, endpoint, true));
|
|
396
|
+
}
|
|
397
|
+
const planned = endpoints.filter((endpoint) => endpoint.status === "planned");
|
|
398
|
+
const worstCaseUsd = planned.reduce((sum, endpoint) => sum + endpoint.worstCaseUsd, 0n);
|
|
399
|
+
const budget = optIn.budget;
|
|
400
|
+
const remainingUsd = budget.capUsd - budget.spentUsd;
|
|
401
|
+
const capLowered = budget.capUsd < usdFromDollars(PER_RUN_CAP_USD);
|
|
402
|
+
// The payer's funds: the balance the plan read, held to what the run needs to finish its checks.
|
|
403
|
+
const funding = mainnetFunding(endpoints, readings.decimals, readings.usdc);
|
|
404
|
+
const plan = {
|
|
405
|
+
network: options.network,
|
|
406
|
+
pin: optIn.pin,
|
|
407
|
+
perPaymentCapUsd: usdFromDollars(PER_PAYMENT_CAP_USD),
|
|
408
|
+
capUsd: budget.capUsd,
|
|
409
|
+
capLowered,
|
|
410
|
+
endpoints,
|
|
411
|
+
worstCaseUsd,
|
|
412
|
+
mainnet: { ...readings, remainingUsd },
|
|
413
|
+
...(funding === undefined ? {} : { funding }),
|
|
414
|
+
};
|
|
415
|
+
// B4: on mainnet one endpoint that cannot be planned keeps the whole run from starting; then the cap; then the
|
|
416
|
+
// payer's funds: a run that could not finish its checks does not start.
|
|
417
|
+
const refusal = mainnetRefusal(endpoints, worstCaseUsd, budget, capLowered) ?? fundingRefusal(funding);
|
|
418
|
+
if (refusal !== undefined) {
|
|
419
|
+
// A refused run signs nothing, so it carries no warning that funds can be lost.
|
|
420
|
+
optIn.stop(refusal);
|
|
421
|
+
return { ...plan, refusal };
|
|
422
|
+
}
|
|
423
|
+
const passed = funding === undefined ? plan : { ...plan, funding: warnedFunding(funding) };
|
|
424
|
+
recordMainnetPlan(optIn, passed);
|
|
425
|
+
return passed;
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* The opening line of a mainnet run (spec B5: a mainnet run says so in its
|
|
429
|
+
* first line): printed when the opt-in opens, before a service is started or
|
|
430
|
+
* the target is asked anything. The network, real funds, the payer, the one
|
|
431
|
+
* payee and the caps; the worst case comes with the plan
|
|
432
|
+
* ({@link mainnetFirstLine}).
|
|
433
|
+
*/
|
|
434
|
+
export function mainnetOpeningLine(optIn) {
|
|
435
|
+
if (!isLiveOptIn(optIn, STELLAR_PUBNET))
|
|
436
|
+
throw new ConfigurationError("Not a mainnet opt-in that is still open.");
|
|
437
|
+
const { budget } = optIn;
|
|
438
|
+
const remaining = budget.capUsd - budget.spentUsd;
|
|
439
|
+
const cap = budget.spentUsd === 0n
|
|
440
|
+
? `at most ${formatUsd(budget.capUsd)} this run`
|
|
441
|
+
: `at most ${formatUsd(remaining)} this run, what is left of the ${formatUsd(budget.capUsd)} cap`;
|
|
442
|
+
return sanitizeText(`MAINNET RUN on ${optIn.network}: real funds. Payer ${optIn.payer}; pays only ${optIn.pin.payTo} in USDC; ` +
|
|
443
|
+
`at most ${formatUsd(usdFromDollars(PER_PAYMENT_CAP_USD))} per payment; ${cap}. ` +
|
|
444
|
+
`The plan is read next; nothing is signed before it passes.`);
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* The first line of every mainnet run (spec B5): the network, real funds, the
|
|
448
|
+
* payer, the one payee, the caps and the run's worst case.
|
|
449
|
+
*/
|
|
450
|
+
export function mainnetFirstLine(plan) {
|
|
451
|
+
const mainnet = plan.mainnet;
|
|
452
|
+
if (mainnet === undefined || plan.pin === undefined)
|
|
453
|
+
throw new ConfigurationError("Not the plan of a mainnet run.");
|
|
454
|
+
const left = mainnet.remainingUsd === plan.capUsd ? `the ${formatUsd(plan.capUsd)} cap` : `the ${formatUsd(mainnet.remainingUsd)} left of the ${formatUsd(plan.capUsd)} cap`;
|
|
455
|
+
return sanitizeText(`MAINNET RUN on ${plan.network}: real funds. Payer ${mainnet.payer}; pays only ${plan.pin.payTo} in USDC; ` +
|
|
456
|
+
`at most ${formatUsd(plan.perPaymentCapUsd)} per payment; this run could spend up to ${formatUsd(plan.worstCaseUsd)} of ${left}.`);
|
|
457
|
+
}
|
|
458
|
+
/** The funds lines of a mainnet plan: the balance against the minimum and the worst case, and the warning. */
|
|
459
|
+
function fundingLines(plan) {
|
|
460
|
+
const funding = plan.funding;
|
|
461
|
+
if (funding === undefined)
|
|
462
|
+
return [];
|
|
463
|
+
const { decimals, balance } = funding;
|
|
464
|
+
const worst = usdc(funding.worstCase, decimals);
|
|
465
|
+
if (balance === undefined) {
|
|
466
|
+
return [
|
|
467
|
+
`Mainnet dry run: a paying run also refuses when the payer holds less than ${usdc(funding.minimum, decimals)} in USDC ` +
|
|
468
|
+
`(the prices, ${usdc(funding.prices, decimals)}, plus the highest price again, ${usdc(funding.highestPrice, decimals)}: ` +
|
|
469
|
+
`what it needs to finish its checks), and warns below the worst case of ${worst}.`,
|
|
470
|
+
];
|
|
471
|
+
}
|
|
472
|
+
const margin = balance >= funding.minimum ? `${usdc(balance - funding.minimum, decimals)} above it` : `${usdc(funding.minimum - balance, decimals)} short`;
|
|
473
|
+
return [
|
|
474
|
+
`Mainnet: funds: the payer holds ${usdc(balance, decimals)} in USDC; this run needs ${fundingTerms(funding)}: ${margin}; ` +
|
|
475
|
+
`worst case ${worst}.`,
|
|
476
|
+
...(funding.warning === undefined ? [] : [funding.warning]),
|
|
477
|
+
];
|
|
478
|
+
}
|
|
122
479
|
/**
|
|
123
480
|
* The plan for a terminal or a log: the network, the caps, and per endpoint
|
|
124
481
|
* the destination, the asset, the amount of each signature and the worst case.
|
|
@@ -130,14 +487,31 @@ export function describePlan(plan) {
|
|
|
130
487
|
`Caps: ${formatUsd(plan.perPaymentCapUsd)} a payment, ${formatUsd(plan.capUsd)} this run` +
|
|
131
488
|
`${plan.capLowered ? " (maxRunUsd)" : ""}.`,
|
|
132
489
|
...(plan.pin === undefined ? [] : [`Pinned: payTo ${plan.pin.payTo}, asset ${plan.pin.asset}.`]),
|
|
490
|
+
...(plan.mainnet === undefined
|
|
491
|
+
? []
|
|
492
|
+
: [
|
|
493
|
+
`Mainnet: payer ${plan.mainnet.payer} holds ${formatUsd(usdFromBaseUnits(plan.mainnet.usdc, plan.mainnet.decimals))} in USDC ` +
|
|
494
|
+
`(${plan.mainnet.usdc} base units, the RPC and public Horizon agree) and ${plan.mainnet.native} stroops of XLM.`,
|
|
495
|
+
`Mainnet: hosts contacted beside the service: the RPC ${plan.mainnet.rpc} and public Horizon ${plan.mainnet.horizon}; ` +
|
|
496
|
+
`latest ledger ${plan.mainnet.rpcLatest} (RPC) and ${plan.mainnet.horizonLatest} (Horizon).`,
|
|
497
|
+
]),
|
|
498
|
+
...(plan.mainnetDryRun === true
|
|
499
|
+
? [
|
|
500
|
+
"Mainnet dry run: no key is read, so nothing of the payer was read. A paying mainnet run first reads, and refuses " +
|
|
501
|
+
"on any of them: the payer's USDC through the RPC and on public Horizon (the two equal, $10.00 at most), the " +
|
|
502
|
+
"token's decimals (7), and the RPC's latest ledger beside public Horizon's (12 apart at most).",
|
|
503
|
+
]
|
|
504
|
+
: []),
|
|
505
|
+
...fundingLines(plan),
|
|
133
506
|
];
|
|
134
507
|
for (const endpoint of plan.endpoints) {
|
|
508
|
+
const at = endpoint.url === undefined ? "" : ` at ${endpoint.url}`;
|
|
135
509
|
if (endpoint.status !== "planned" || endpoint.option === undefined) {
|
|
136
|
-
lines.push(` ${endpoint.name}: ${endpoint.status === "refused" ? "refused" : "not paid"}: ${endpoint.reason ?? ""}`);
|
|
510
|
+
lines.push(` ${endpoint.name}${at}: ${endpoint.status === "refused" ? "refused" : "not paid"}: ${endpoint.reason ?? ""}`);
|
|
137
511
|
continue;
|
|
138
512
|
}
|
|
139
513
|
const { option } = endpoint;
|
|
140
|
-
lines.push(` ${endpoint.name}: pays ${shown(option.payTo)} in ${shown(option.asset)}, up to ${formatUsd(endpoint.worstCaseUsd)}`, ` ${endpoint.signatures.map((entry) => `${entry.check} ${entry.amount}`).join(", ")} (base units)`);
|
|
514
|
+
lines.push(` ${endpoint.name}${at}: pays ${shown(option.payTo)} in ${shown(option.asset)}, up to ${formatUsd(endpoint.worstCaseUsd)}`, ` ${endpoint.signatures.map((entry) => `${entry.check} ${entry.amount}`).join(", ")} (base units)`);
|
|
141
515
|
}
|
|
142
516
|
lines.push(`Worst case: ${formatUsd(plan.worstCaseUsd)} of ${formatUsd(plan.capUsd)}.`);
|
|
143
517
|
if (plan.refusal !== undefined)
|
|
@@ -133,6 +133,16 @@ export interface RejectedRequestEvidence {
|
|
|
133
133
|
readonly ledger: number;
|
|
134
134
|
}[];
|
|
135
135
|
}
|
|
136
|
+
/**
|
|
137
|
+
* The settlement the chain shows for X402-11's payment, for the run ledger:
|
|
138
|
+
* the chain records its authorization as used, and the second readings agree
|
|
139
|
+
* (a transfer of the price from the payer to payTo, and the payer's balance
|
|
140
|
+
* down by at least it). The nonce read is a reading of this payment's own
|
|
141
|
+
* authorization, so the settlement counts as verified. The reference is the
|
|
142
|
+
* one transfer in the ledger the nonce was used in, or the only one the watch
|
|
143
|
+
* saw; when neither names one, undefined, and the ledger leaves it unverified.
|
|
144
|
+
*/
|
|
145
|
+
export declare function rejectedRequestSettlement(evidence: RejectedRequestEvidence): string | undefined;
|
|
136
146
|
/**
|
|
137
147
|
* X402-11's verdict from what the service answered and what the chain shows.
|
|
138
148
|
*
|
|
@@ -171,6 +171,24 @@ function notUntaken(evidence) {
|
|
|
171
171
|
return `the payer's balance fell by ${fell} base units, at least the ${amount} paid`;
|
|
172
172
|
return undefined;
|
|
173
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* The settlement the chain shows for X402-11's payment, for the run ledger:
|
|
176
|
+
* the chain records its authorization as used, and the second readings agree
|
|
177
|
+
* (a transfer of the price from the payer to payTo, and the payer's balance
|
|
178
|
+
* down by at least it). The nonce read is a reading of this payment's own
|
|
179
|
+
* authorization, so the settlement counts as verified. The reference is the
|
|
180
|
+
* one transfer in the ledger the nonce was used in, or the only one the watch
|
|
181
|
+
* saw; when neither names one, undefined, and the ledger leaves it unverified.
|
|
182
|
+
*/
|
|
183
|
+
export function rejectedRequestSettlement(evidence) {
|
|
184
|
+
const { watch, transfers } = evidence;
|
|
185
|
+
if (watch.kind !== "used" || transfers === undefined || notTaken(evidence) !== undefined)
|
|
186
|
+
return undefined;
|
|
187
|
+
const there = transfers.filter((transfer) => transfer.ledger === watch.ledger);
|
|
188
|
+
if (there.length === 1)
|
|
189
|
+
return there[0].reference;
|
|
190
|
+
return transfers.length === 1 ? transfers[0].reference : undefined;
|
|
191
|
+
}
|
|
174
192
|
const SERVED_HINT = "Refuse an invalid request before its payment is settled. The official x402 Express middleware does not settle " +
|
|
175
193
|
"when the handler answers 400 or above; a route that serves every request it is paid for sells what it should refuse.";
|
|
176
194
|
const TAKEN_HINT = "A refused request must not cost the payer: settle a payment only after the request has been accepted. The " +
|
package/dist/x402/simulator.d.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { type CheckResult } from "../check.js";
|
|
2
2
|
import { ConfigurationError } from "../errors.js";
|
|
3
3
|
import { RunBudget, type PinTerms } from "../guard/budget.js";
|
|
4
|
+
import { type MainnetOptIn } from "../guard/optin.js";
|
|
5
|
+
import { type PaymentLedger } from "../guard/run-ledger.js";
|
|
4
6
|
import type { EndpointPlan } from "./plan.js";
|
|
5
7
|
import { type RejectCase } from "./rejected-request.js";
|
|
6
8
|
export type { CheckResult };
|
|
@@ -31,6 +33,15 @@ export interface X402SimulatorOptions extends RequestShape {
|
|
|
31
33
|
*/
|
|
32
34
|
readonly onResult?: (result: CheckResult) => void;
|
|
33
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* Validates a request shape and turns it into fetch init.
|
|
38
|
+
*
|
|
39
|
+
* A bad method, or a body on a verb that cannot carry one, is a configuration
|
|
40
|
+
* error rather than a finding: nothing has been learned about the target.
|
|
41
|
+
* Exported for `wasit init`'s unpaid request (route-reader.ts), which sends
|
|
42
|
+
* the route what the read checks send it.
|
|
43
|
+
*/
|
|
44
|
+
export declare function buildInit(shape: RequestShape): RequestInit;
|
|
34
45
|
/**
|
|
35
46
|
* Reads an x402 v1 challenge from a 402 response body, if that is what it is.
|
|
36
47
|
*
|
|
@@ -69,6 +80,21 @@ export interface X402PaymentCheckOptions extends RequestShape {
|
|
|
69
80
|
readonly plan?: EndpointPlan;
|
|
70
81
|
/** The request the service must refuse (`endpoints[].reject`), for X402-11. Absent: X402-11 is skipped. */
|
|
71
82
|
readonly reject?: RejectCase;
|
|
83
|
+
/**
|
|
84
|
+
* The run ledger of this endpoint (spec B5): each signature's intent is
|
|
85
|
+
* written before the key is asked to sign, then what became of it. A ledger
|
|
86
|
+
* that cannot take an intent stops that payment, with nothing signed.
|
|
87
|
+
* Optional on a test network. On mainnet the opt-in's own ledger is used,
|
|
88
|
+
* and one handed in here is refused.
|
|
89
|
+
*/
|
|
90
|
+
readonly ledger?: PaymentLedger;
|
|
91
|
+
/**
|
|
92
|
+
* The mainnet opt-in of the run (spec B5), made by `openMainnetOptIn`, its
|
|
93
|
+
* plan passed and its ledger open. On `stellar:pubnet` nothing is paid
|
|
94
|
+
* without it, and the checks pay by its budget, pin, plan, ledger and RPC
|
|
95
|
+
* only: a different one handed in beside it is refused.
|
|
96
|
+
*/
|
|
97
|
+
readonly mainnet?: MainnetOptIn;
|
|
72
98
|
/**
|
|
73
99
|
* Called with one line when a check starts a long wait on the chain (X402-11
|
|
74
100
|
* waits up to six minutes), so a log does not look stuck. The line holds no
|
|
@@ -105,6 +131,14 @@ export declare function readPaymentChallenge(options: RequestShape & {
|
|
|
105
131
|
selected: PaymentRequirements;
|
|
106
132
|
idempotent: boolean;
|
|
107
133
|
}>;
|
|
134
|
+
/**
|
|
135
|
+
* Refuses an RPC an x402 payment on `network` cannot be built through, then
|
|
136
|
+
* checks that it serves `network` (D-023). On Stellar the client accepts only
|
|
137
|
+
* an https RPC. Throws `RpcIdentityError` (a configuration error) before the
|
|
138
|
+
* target is sent anything; the RPC's address is never echoed (it may carry a
|
|
139
|
+
* key). The CLI calls it before it starts a service.
|
|
140
|
+
*/
|
|
141
|
+
export declare function assertX402PaymentRpc(network: string, rpcUrl: string): Promise<void>;
|
|
108
142
|
/**
|
|
109
143
|
* Reads the settlement a paid response reports, before anything is looked up.
|
|
110
144
|
*
|