@wasit-dev/core 0.8.0-beta.1 → 0.8.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -2
- package/dist/baseline.js +3 -1
- package/dist/check.d.ts +1 -1
- package/dist/ci-report.js +15 -7
- package/dist/config-writer.d.ts +96 -0
- package/dist/config-writer.js +281 -0
- package/dist/guard/budget.d.ts +6 -3
- package/dist/guard/budget.js +10 -3
- 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-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 +96 -0
- package/dist/guard/signed-terms.js +207 -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.js +134 -3
- package/dist/x402/chains/types.d.ts +36 -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 +452 -46
- package/package.json +1 -1
- package/dist/guard/mainnet-optin.d.ts +0 -58
- package/dist/guard/mainnet-optin.js +0 -95
package/dist/x402/simulator.js
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
import { errored, quoteValue, skipped } from "../check.js";
|
|
2
2
|
import { CheckSetupError, ConfigurationError, MalformedResponseError, assertHttpUrl, fetchPaymentChallenge, fetchTarget, } from "../errors.js";
|
|
3
|
-
import { PER_PAYMENT_CAP_USD, PaymentGuardRefusedError, RunBudget, assertPinned, sameAddress, } from "../guard/budget.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
3
|
+
import { PER_PAYMENT_CAP_USD, PaymentGuardRefusedError, RunBudget, assertPinned, sameAddress, shown, } from "../guard/budget.js";
|
|
4
|
+
import { MainnetPlanRefusedError, assertMainnetOption, paidUrlOf } from "../guard/mainnet-plan.js";
|
|
5
|
+
import { PaymentNetworkRefusedError, assertPaymentNetworkAllowed } from "../guard/networks.js";
|
|
6
|
+
import { MainnetRunRefusedError, anchorOfOptIn, isLiveOptIn } from "../guard/optin.js";
|
|
7
|
+
import { SigningAnchor, SigningGate, expirationOfSigned } from "../guard/signed-terms.js";
|
|
8
|
+
import { RunLedgerError } from "../guard/run-ledger.js";
|
|
9
|
+
import { RpcIdentityError, assertRpcServesNetwork } from "../guard/rpc-identity.js";
|
|
10
|
+
import { REJECTED_REQUEST_ID, REJECTED_REQUEST_MAX_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_LIFETIME_SECONDS, REJECTED_REQUEST_MIN_UNITS_LEFT, REJECTED_REQUEST_NAME, rejectRequestShape, rejectedRequestHardStopMs, rejectedRequestSettlement, rejectedRequestVerdict, watchAuthorization, } from "./rejected-request.js";
|
|
7
11
|
import { sanitizeText } from "../sanitize.js";
|
|
8
12
|
import { checkNetworkIdentifier, checkRequiredFields } from "./requirements.js";
|
|
9
13
|
const BODYLESS_METHODS = new Set(["GET", "HEAD"]);
|
|
@@ -21,8 +25,10 @@ const KNOWN_METHODS = new Set([
|
|
|
21
25
|
*
|
|
22
26
|
* A bad method, or a body on a verb that cannot carry one, is a configuration
|
|
23
27
|
* error rather than a finding: nothing has been learned about the target.
|
|
28
|
+
* Exported for `wasit init`'s unpaid request (route-reader.ts), which sends
|
|
29
|
+
* the route what the read checks send it.
|
|
24
30
|
*/
|
|
25
|
-
function buildInit(shape) {
|
|
31
|
+
export function buildInit(shape) {
|
|
26
32
|
const method = (shape.method ?? "GET").toUpperCase();
|
|
27
33
|
if (!KNOWN_METHODS.has(method)) {
|
|
28
34
|
throw new ConfigurationError(`"${shape.method}" is not an HTTP method. Expected one of ` +
|
|
@@ -303,6 +309,28 @@ class PaymentNotAttemptedError extends Error {
|
|
|
303
309
|
this.name = "PaymentNotAttemptedError";
|
|
304
310
|
}
|
|
305
311
|
}
|
|
312
|
+
/**
|
|
313
|
+
* The route answered 409 where a 402 challenge was asked for: a single-use
|
|
314
|
+
* resource that a payment has used up (spec B8). Nothing is paid for it.
|
|
315
|
+
* Before any payment of the run it is one more reason no payment was attempted
|
|
316
|
+
* (X402-06 and the plan read it so); after X402-06's payment was accepted the
|
|
317
|
+
* negative checks that need a new challenge are skipped as "resource consumed".
|
|
318
|
+
*/
|
|
319
|
+
class ResourceConsumedError extends PaymentNotAttemptedError {
|
|
320
|
+
constructor() {
|
|
321
|
+
super("the target answered 409 instead of a 402 challenge: a single-use resource that is already used up, so no " +
|
|
322
|
+
"payment was attempted (see X402-01).");
|
|
323
|
+
this.name = "ResourceConsumedError";
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
/** The status a single-use resource answers once it is used up (spec B8). */
|
|
327
|
+
const RESOURCE_CONSUMED_STATUS = 409;
|
|
328
|
+
/** The one negative check that needs no new challenge: it sends X402-06's payment again. */
|
|
329
|
+
const REPLAY_CHECK = "X402-08";
|
|
330
|
+
/** Why a negative check is skipped once a new challenge drew a 409 after X402-06's payment was accepted. */
|
|
331
|
+
const RESOURCE_CONSUMED_REASON = "resource consumed: the route answered 409 to a new request after X402-06's payment was accepted, a single-use resource that the " +
|
|
332
|
+
"payment used up, so this check has no new challenge to pay, and nothing was signed for it. X402-08, the replay, " +
|
|
333
|
+
"needs no new challenge and still runs.";
|
|
306
334
|
/**
|
|
307
335
|
* No payment adapter pays on this network, so the payment checks cannot be
|
|
308
336
|
* graded here. A `ConfigurationError`, so a caller that does not know the class
|
|
@@ -331,13 +359,13 @@ function chainFor(network) {
|
|
|
331
359
|
throw new UnsupportedPaymentNetworkError(network);
|
|
332
360
|
return chain;
|
|
333
361
|
}
|
|
334
|
-
async function buildX402Client(chain, network, payerSecretKey, rpcUrl, pin) {
|
|
362
|
+
async function buildX402Client(chain, network, payerSecretKey, rpcUrl, pin, gate, mainnet) {
|
|
335
363
|
const client = new x402Client();
|
|
336
364
|
// L3 (spec B3): the SDK's own spend controls, set here rather than left to
|
|
337
365
|
// its default, as a second implementation of the $1 cap. An adapter that
|
|
338
366
|
// allows more assets replaces them and states the cap again (`evm.ts`).
|
|
339
367
|
client.setSpendControls({ maxAmountPerPayment: `$${PER_PAYMENT_CAP_USD}` });
|
|
340
|
-
await chain.registerPayer(client, network, payerSecretKey, rpcUrl);
|
|
368
|
+
await chain.registerPayer(client, network, payerSecretKey, rpcUrl, gate, mainnet);
|
|
341
369
|
client
|
|
342
370
|
// A challenge may offer several networks, including both Stellar ones.
|
|
343
371
|
// The client's default pick is the first it supports, which would sign
|
|
@@ -406,6 +434,11 @@ export async function readPaymentChallenge(options) {
|
|
|
406
434
|
/** The terms of a challenge already fetched, by the rules of {@link readPaymentChallenge}. */
|
|
407
435
|
async function paymentTerms(challenge, network) {
|
|
408
436
|
const options = { network };
|
|
437
|
+
// B8: a single-use resource answers 409 once it is used up. Said as that, before its headers are read as a challenge.
|
|
438
|
+
if (challenge.status === RESOURCE_CONSUMED_STATUS) {
|
|
439
|
+
await challenge.body?.cancel().catch(() => undefined);
|
|
440
|
+
throw new ResourceConsumedError();
|
|
441
|
+
}
|
|
409
442
|
let paymentRequired;
|
|
410
443
|
try {
|
|
411
444
|
paymentRequired = new x402HTTPClient(new x402Client()).getPaymentRequiredResponse((name) => challenge.headers.get(name));
|
|
@@ -480,6 +513,72 @@ function plannedAmount(plan, check, selected) {
|
|
|
480
513
|
}
|
|
481
514
|
return entry.amount;
|
|
482
515
|
}
|
|
516
|
+
/**
|
|
517
|
+
* Refuses an RPC an x402 payment on `network` cannot be built through, then
|
|
518
|
+
* checks that it serves `network` (D-023). On Stellar the client accepts only
|
|
519
|
+
* an https RPC. Throws `RpcIdentityError` (a configuration error) before the
|
|
520
|
+
* target is sent anything; the RPC's address is never echoed (it may carry a
|
|
521
|
+
* key). The CLI calls it before it starts a service.
|
|
522
|
+
*/
|
|
523
|
+
export async function assertX402PaymentRpc(network, rpcUrl) {
|
|
524
|
+
const chain = paymentChainFor(network);
|
|
525
|
+
if (chain?.httpsRpcOnly === true) {
|
|
526
|
+
let protocol = "";
|
|
527
|
+
try {
|
|
528
|
+
protocol = new URL(rpcUrl).protocol;
|
|
529
|
+
}
|
|
530
|
+
catch {
|
|
531
|
+
protocol = "";
|
|
532
|
+
}
|
|
533
|
+
if (protocol !== "https:") {
|
|
534
|
+
throw new RpcIdentityError(`The x402 ${chain.name} client builds the payment through the run's RPC and accepts only an https RPC, ` +
|
|
535
|
+
`and this run's RPC is not https. No payment was sent and nothing was signed.`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
await assertRpcServesNetwork(network, rpcUrl);
|
|
539
|
+
}
|
|
540
|
+
/** The run's anchor for expiration bounds, one per run budget (a run shares one budget across endpoints). */
|
|
541
|
+
const anchors = new WeakMap();
|
|
542
|
+
function anchorOf(budget) {
|
|
543
|
+
let anchor = anchors.get(budget);
|
|
544
|
+
if (anchor === undefined) {
|
|
545
|
+
anchor = new SigningAnchor();
|
|
546
|
+
anchors.set(budget, anchor);
|
|
547
|
+
}
|
|
548
|
+
return anchor;
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* The terms the gate is armed with: those L2 checked and charged, and the
|
|
552
|
+
* latest ledger the signature may expire at. The run's first signature reads
|
|
553
|
+
* the chain's latest ledger as the anchor; nothing is signed when it cannot.
|
|
554
|
+
*/
|
|
555
|
+
async function signingTerms(binding, network, rpcUrl, anchor, payer, signing, readIfMissing) {
|
|
556
|
+
if (anchor.reading === undefined) {
|
|
557
|
+
// A mainnet run's anchor is read in its plan, beside public Horizon's latest ledger (B17.2), never here.
|
|
558
|
+
if (!readIfMissing) {
|
|
559
|
+
throw new PaymentGuardRefusedError("plan", "The mainnet run's latest ledger was not read in its plan, so no expiration can be bounded.");
|
|
560
|
+
}
|
|
561
|
+
let latest;
|
|
562
|
+
try {
|
|
563
|
+
latest = await binding.latestUnit(network, rpcUrl);
|
|
564
|
+
}
|
|
565
|
+
catch (error) {
|
|
566
|
+
throw new CheckSetupError(`The chain's latest ledger could not be read before signing (${error.message}). Nothing was signed.`);
|
|
567
|
+
}
|
|
568
|
+
if (!Number.isSafeInteger(latest) || latest <= 0) {
|
|
569
|
+
throw new CheckSetupError("The chain's latest ledger could not be read before signing. Nothing was signed.");
|
|
570
|
+
}
|
|
571
|
+
anchor.set(latest);
|
|
572
|
+
}
|
|
573
|
+
return {
|
|
574
|
+
network,
|
|
575
|
+
payer,
|
|
576
|
+
asset: signing.asset,
|
|
577
|
+
payTo: signing.payTo,
|
|
578
|
+
amount: signing.amount,
|
|
579
|
+
maxExpiration: anchor.maxExpiration(binding.unitSeconds, signing.maxTimeoutSeconds),
|
|
580
|
+
};
|
|
581
|
+
}
|
|
483
582
|
/**
|
|
484
583
|
* Reads the challenge and produces a signed payment payload for it.
|
|
485
584
|
*
|
|
@@ -494,17 +593,56 @@ function plannedAmount(plan, check, selected) {
|
|
|
494
593
|
* L2 (spec B3) is here, between the fresh challenge and the SDK: the pin over
|
|
495
594
|
* every `exact` option, the plan, the $1 cap and the run's cap, the run charged
|
|
496
595
|
* before the signature. The SDK is then handed exactly the one option checked,
|
|
497
|
-
* and a payload whose `accepted` is not that option is discarded unsent.
|
|
596
|
+
* and a payload whose `accepted` is not that option is discarded unsent. On a
|
|
597
|
+
* chain with a signed-terms gate (Stellar), the key signs only an
|
|
598
|
+
* authorization for those same terms, and a payload that carries anything
|
|
599
|
+
* else is discarded unsent.
|
|
600
|
+
*
|
|
601
|
+
* On mainnet (a live opt-in, spec B5) the fresh terms are also held to the
|
|
602
|
+
* mainnet rules (exact, USDC, a lifetime of at most 300 s), the ledger is the
|
|
603
|
+
* opt-in's, the anchor is the one its plan read, and a refusal here stops the
|
|
604
|
+
* whole run (B3): nothing more is signed in it.
|
|
498
605
|
*/
|
|
499
606
|
async function preparePayment(options, check, alter, beforeSigning) {
|
|
500
607
|
// L0 again at the one function every x402 signature goes through, whoever
|
|
501
608
|
// reaches it: nothing is fetched or signed on a network that is not a test
|
|
502
|
-
// network.
|
|
503
|
-
assertPaymentNetworkAllowed("x402", options.network);
|
|
609
|
+
// network, but stellar:pubnet with a live mainnet opt-in.
|
|
610
|
+
assertPaymentNetworkAllowed("x402", options.network, options.mainnet);
|
|
611
|
+
const mainnet = isLiveOptIn(options.mainnet, options.network) ? options.mainnet : undefined;
|
|
612
|
+
if (mainnet === undefined)
|
|
613
|
+
return signPayment(options, check, undefined, alter, beforeSigning);
|
|
614
|
+
try {
|
|
615
|
+
return await signPayment(options, check, mainnet, alter, beforeSigning);
|
|
616
|
+
}
|
|
617
|
+
catch (error) {
|
|
618
|
+
if (isGuardRefusal(error))
|
|
619
|
+
mainnet.stop(error.message);
|
|
620
|
+
throw error;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
/** A refusal of Wasit's own guard, the ledger's included: on mainnet it stops the whole run (B3). */
|
|
624
|
+
function isGuardRefusal(error) {
|
|
625
|
+
return (error instanceof PaymentGuardRefusedError ||
|
|
626
|
+
error instanceof PaymentNetworkRefusedError ||
|
|
627
|
+
error instanceof MainnetPlanRefusedError ||
|
|
628
|
+
error instanceof MainnetRunRefusedError ||
|
|
629
|
+
error instanceof RunLedgerError);
|
|
630
|
+
}
|
|
631
|
+
async function signPayment(options, check, mainnet, alter, beforeSigning) {
|
|
504
632
|
const chain = chainFor(options.network);
|
|
505
633
|
const budget = options.budget ?? new RunBudget();
|
|
506
|
-
|
|
634
|
+
if (mainnet !== undefined && (budget !== mainnet.budget || options.ledger === undefined || chain.signedTerms === undefined)) {
|
|
635
|
+
throw new MainnetRunRefusedError("run", `${check} on mainnet pays only through the run's own budget and ledger, with a signer that signs only the checked terms.`, { during: true });
|
|
636
|
+
}
|
|
637
|
+
const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
|
|
638
|
+
const gate = new SigningGate();
|
|
639
|
+
const { client, httpClient } = await buildX402Client(chain, options.network, options.payerSecretKey, rpcUrl, options.pin, gate, mainnet);
|
|
507
640
|
const { paymentRequired, selected, idempotent, payUrl } = await readPaymentChallenge(options);
|
|
641
|
+
// On mainnet a payment goes to the one URL the plan recorded, never to one the service sends it to later.
|
|
642
|
+
if (mainnet !== undefined && (options.plan?.url === undefined || paidUrlOf(payUrl) !== options.plan.url)) {
|
|
643
|
+
throw new PaymentGuardRefusedError("plan", `${check} would pay ${shown(paidUrlOf(payUrl))}, not the URL the plan recorded for this endpoint: the service ` +
|
|
644
|
+
`sent the request elsewhere after the plan.`);
|
|
645
|
+
}
|
|
508
646
|
// L2, before anything is built: the service may change its challenge between
|
|
509
647
|
// requests, so the plan alone is not enough.
|
|
510
648
|
assertPinned(options.network, paymentRequired.accepts, options.pin);
|
|
@@ -515,6 +653,10 @@ async function preparePayment(options, check, alter, beforeSigning) {
|
|
|
515
653
|
throw new PaymentGuardRefusedError("accepted", `${check} would sign different ${field} terms than the target's.`);
|
|
516
654
|
}
|
|
517
655
|
}
|
|
656
|
+
// The mainnet rules on the terms about to be signed, not only on the plan's:
|
|
657
|
+
// a lifetime raised after the plan is refused here (B3, L2).
|
|
658
|
+
if (mainnet !== undefined)
|
|
659
|
+
assertMainnetOption(signing);
|
|
518
660
|
budget.charge({
|
|
519
661
|
check,
|
|
520
662
|
network: options.network,
|
|
@@ -522,16 +664,106 @@ async function preparePayment(options, check, alter, beforeSigning) {
|
|
|
522
664
|
amount: signing.amount,
|
|
523
665
|
...(planned === undefined ? {} : { planned }),
|
|
524
666
|
});
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
667
|
+
// The run ledger (spec B5): the intent is on disk before the key can be asked
|
|
668
|
+
// to sign. A ledger that cannot take it throws here, and nothing is signed.
|
|
669
|
+
const entry = options.ledger?.intent({
|
|
670
|
+
check,
|
|
671
|
+
network: options.network,
|
|
672
|
+
asset: signing.asset,
|
|
673
|
+
payTo: signing.payTo,
|
|
674
|
+
amount: signing.amount,
|
|
675
|
+
});
|
|
676
|
+
let asked = false;
|
|
677
|
+
let signed;
|
|
678
|
+
try {
|
|
679
|
+
await beforeSigning?.(selected);
|
|
680
|
+
// The signed-terms gate (spec B17.2): the key signs only what was checked and
|
|
681
|
+
// charged above, once, within this payment's lifetime.
|
|
682
|
+
if (chain.signedTerms !== undefined) {
|
|
683
|
+
gate.arm(await signingTerms(chain.signedTerms, options.network, rpcUrl, mainnet === undefined ? anchorOf(budget) : anchorOfOptIn(mainnet), chain.payerAddress(options.payerSecretKey), signing, mainnet === undefined));
|
|
684
|
+
}
|
|
685
|
+
asked = true;
|
|
686
|
+
signed = await withinSpendControls(options.network, selected, () => client.createPaymentPayload({ ...paymentRequired, accepts: [signing] }));
|
|
687
|
+
}
|
|
688
|
+
catch (error) {
|
|
689
|
+
recordUnsigned(entry, chain, gate, asked, error);
|
|
690
|
+
throw error;
|
|
691
|
+
}
|
|
692
|
+
// Recorded before the payload can be used: a signature the ledger cannot
|
|
693
|
+
// take is never sent.
|
|
694
|
+
entry?.signed(gate.signed === undefined ? undefined : expirationOfSigned(gate.signed));
|
|
695
|
+
try {
|
|
696
|
+
// What the SDK says it signed must be the option checked, field by field;
|
|
697
|
+
// otherwise the payload is discarded here, unsent. It stays charged.
|
|
698
|
+
if (canonical(signed.accepted) !== canonical(signing)) {
|
|
699
|
+
throw new PaymentGuardRefusedError("accepted", `The payment the x402 client built for ${check} names other terms in its accepted field than the ` +
|
|
700
|
+
`option Wasit checked.`, { signed: true });
|
|
701
|
+
}
|
|
702
|
+
// And what it carries must be the one authorization the gate let the key sign.
|
|
703
|
+
chain.signedTerms?.bind(signed.payload, gate);
|
|
704
|
+
}
|
|
705
|
+
catch (error) {
|
|
706
|
+
recordDiscarded(entry, error);
|
|
707
|
+
throw error;
|
|
532
708
|
}
|
|
533
709
|
const paymentPayload = alter === undefined ? signed : { ...signed, accepted: selected };
|
|
534
|
-
return { httpClient, paymentPayload, selected, idempotent, payUrl };
|
|
710
|
+
return { httpClient, paymentPayload, selected, idempotent, payUrl, entry };
|
|
711
|
+
}
|
|
712
|
+
function reasonOf(error) {
|
|
713
|
+
return error instanceof Error ? error.message : String(error);
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* What became of a payment that failed before its payload was built. With
|
|
717
|
+
* the gate armed, only a signature the gate recorded was made: the gate is the
|
|
718
|
+
* only way to the key. Without a gate (EVM and Solana, test networks only),
|
|
719
|
+
* a client that failed once it was asked may have signed. A ledger that cannot
|
|
720
|
+
* take the outcome leaves the intent, which reads as signed.
|
|
721
|
+
*/
|
|
722
|
+
function recordUnsigned(entry, chain, gate, asked, error) {
|
|
723
|
+
if (entry === undefined)
|
|
724
|
+
return;
|
|
725
|
+
try {
|
|
726
|
+
if (gate.signed !== undefined)
|
|
727
|
+
entry.signed(expirationOfSigned(gate.signed));
|
|
728
|
+
else if (!asked || chain.signedTerms !== undefined)
|
|
729
|
+
entry.notSigned(reasonOf(error));
|
|
730
|
+
else
|
|
731
|
+
entry.unknown(reasonOf(error));
|
|
732
|
+
}
|
|
733
|
+
catch {
|
|
734
|
+
// The payment's own error is what the check reports; the intent stays.
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
/** A signed payload discarded unsent. A ledger that cannot take it leaves "signed", which reads as sent. */
|
|
738
|
+
function recordDiscarded(entry, error) {
|
|
739
|
+
try {
|
|
740
|
+
entry?.discarded(reasonOf(error));
|
|
741
|
+
}
|
|
742
|
+
catch {
|
|
743
|
+
// The payment's own error is what the check reports.
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Sends a signed payment and records it in the run ledger: the answer's
|
|
748
|
+
* status, or that no answer came (the payment may still have reached the
|
|
749
|
+
* service). The ledger's own text, never the service's.
|
|
750
|
+
*/
|
|
751
|
+
async function sendPayment(entry, url, init) {
|
|
752
|
+
let response;
|
|
753
|
+
try {
|
|
754
|
+
response = await fetchTarget(url, init);
|
|
755
|
+
}
|
|
756
|
+
catch (error) {
|
|
757
|
+
try {
|
|
758
|
+
entry?.sent({ error: "no answer: the payment may have reached the service" });
|
|
759
|
+
}
|
|
760
|
+
catch {
|
|
761
|
+
// The send's own error is what the check reports.
|
|
762
|
+
}
|
|
763
|
+
throw error;
|
|
764
|
+
}
|
|
765
|
+
entry?.sent({ status: response.status });
|
|
766
|
+
return response;
|
|
535
767
|
}
|
|
536
768
|
/**
|
|
537
769
|
* Reads the settlement a paid response reports, before anything is looked up.
|
|
@@ -609,9 +841,9 @@ async function checkSignatureAccepted(options) {
|
|
|
609
841
|
const id = "X402-06";
|
|
610
842
|
const name = "Signature Resubmit Accepted";
|
|
611
843
|
const fail = (detail, hint) => ({ id, name, pass: false, detail, hint });
|
|
612
|
-
const { httpClient, paymentPayload, idempotent, payUrl } = await preparePayment(options, "X402-06", undefined, (selected) => assertPayerCanPay(options, selected));
|
|
844
|
+
const { httpClient, paymentPayload, idempotent, payUrl, entry } = await preparePayment(options, "X402-06", undefined, (selected) => assertPayerCanPay(options, selected));
|
|
613
845
|
const paymentHeaders = httpClient.encodePaymentSignatureHeader(paymentPayload);
|
|
614
|
-
const paid = await
|
|
846
|
+
const paid = await sendPayment(entry, payUrl, withPaymentHeaders(options, paymentHeaders));
|
|
615
847
|
const honest = (result, accepted) => ({
|
|
616
848
|
result,
|
|
617
849
|
accepted,
|
|
@@ -660,6 +892,7 @@ async function checkSignatureAccepted(options) {
|
|
|
660
892
|
recipient: accepted.payTo,
|
|
661
893
|
payer: chain.payerAddress(options.payerSecretKey),
|
|
662
894
|
});
|
|
895
|
+
entry?.settled(reference, verdict.pass);
|
|
663
896
|
return honest(verdict.pass
|
|
664
897
|
? {
|
|
665
898
|
id,
|
|
@@ -687,13 +920,13 @@ async function checkSignatureAccepted(options) {
|
|
|
687
920
|
* answer: anything that prevents one produces no verdict.
|
|
688
921
|
*/
|
|
689
922
|
async function checkInvalidSignatureRejected(options) {
|
|
690
|
-
const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-07");
|
|
923
|
+
const { httpClient, paymentPayload, payUrl, entry } = await preparePayment(options, "X402-07");
|
|
691
924
|
const corrupted = {
|
|
692
925
|
...paymentPayload,
|
|
693
926
|
payload: chainFor(options.network).corruptPayload(paymentPayload.payload),
|
|
694
927
|
};
|
|
695
928
|
const paymentHeaders = httpClient.encodePaymentSignatureHeader(corrupted);
|
|
696
|
-
const response = await
|
|
929
|
+
const response = await sendPayment(entry, payUrl, withPaymentHeaders(options, paymentHeaders));
|
|
697
930
|
return signatureRejectionVerdict(response.status, await refusalReason(response));
|
|
698
931
|
}
|
|
699
932
|
/**
|
|
@@ -854,9 +1087,57 @@ async function checkUnderpaymentRejected(options) {
|
|
|
854
1087
|
}
|
|
855
1088
|
throw error;
|
|
856
1089
|
}
|
|
857
|
-
const { httpClient, paymentPayload, payUrl } = prepared;
|
|
858
|
-
const response = await
|
|
859
|
-
|
|
1090
|
+
const { httpClient, paymentPayload, selected, payUrl, entry } = prepared;
|
|
1091
|
+
const response = await sendPayment(entry, payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
|
|
1092
|
+
const reason = await refusalReason(response);
|
|
1093
|
+
const verdict = underpaymentVerdict(response.status, offered, advertised, reason);
|
|
1094
|
+
if (verdict.pass)
|
|
1095
|
+
return verdict;
|
|
1096
|
+
// Accepted: the lower amount may have settled. What the chain shows is
|
|
1097
|
+
// added to the FAIL, and recorded in the run ledger, as X402-06 records its own.
|
|
1098
|
+
const settlement = await underpaymentSettlement(options, httpClient, response, entry, offered, selected);
|
|
1099
|
+
return settlement === "" ? verdict : { ...verdict, detail: `${verdict.detail}${settlement}` };
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Whether the underpaid payment a target accepted settled, as X402-06 reads
|
|
1103
|
+
* its own: the `PAYMENT-RESPONSE` names a transaction, which is looked up and
|
|
1104
|
+
* held to the payment signed (the offered amount, the asset, payTo, the
|
|
1105
|
+
* payer). Recorded in the run ledger, verified or not. Returns the sentence
|
|
1106
|
+
* the FAIL adds; empty when the response names no settlement. A chain that
|
|
1107
|
+
* gives no answer changes nothing in the FAIL: the target served for less.
|
|
1108
|
+
*/
|
|
1109
|
+
async function underpaymentSettlement(options, httpClient, response, entry, offered, selected) {
|
|
1110
|
+
const chain = chainFor(options.network);
|
|
1111
|
+
const read = readSettlementReference(response.status, () => httpClient.getPaymentSettleResponse((header) => response.headers.get(header)), chain);
|
|
1112
|
+
if ("failure" in read)
|
|
1113
|
+
return "";
|
|
1114
|
+
const reference = read.reference;
|
|
1115
|
+
let verdict;
|
|
1116
|
+
try {
|
|
1117
|
+
verdict = await chain.verifySettlement(options.network, chain.resolveRpcUrl(options.network, options.rpcUrl), reference, {
|
|
1118
|
+
amount: offered,
|
|
1119
|
+
token: selected.asset,
|
|
1120
|
+
recipient: selected.payTo,
|
|
1121
|
+
payer: chain.payerAddress(options.payerSecretKey),
|
|
1122
|
+
});
|
|
1123
|
+
}
|
|
1124
|
+
catch (error) {
|
|
1125
|
+
recordSettlement(entry, reference, false);
|
|
1126
|
+
return ` Its PAYMENT-RESPONSE names ${reference}, which could not be read on chain (${sanitizeText(error.message).slice(0, 200)}).`;
|
|
1127
|
+
}
|
|
1128
|
+
recordSettlement(entry, reference, verdict.pass);
|
|
1129
|
+
return verdict.pass
|
|
1130
|
+
? ` It settled on chain: ${offered} base units moved from the payer to payTo in ${reference}, read back from the transfer event.`
|
|
1131
|
+
: ` Its PAYMENT-RESPONSE names ${reference}, which the chain does not show as this payment: ${verdict.detail}`;
|
|
1132
|
+
}
|
|
1133
|
+
/** A settlement for the run ledger. A ledger that cannot take it leaves it unverified, which explains nothing. */
|
|
1134
|
+
function recordSettlement(entry, reference, verified) {
|
|
1135
|
+
try {
|
|
1136
|
+
entry?.settled(reference, verified);
|
|
1137
|
+
}
|
|
1138
|
+
catch {
|
|
1139
|
+
// The check's own verdict stands; the next intent finds the ledger broken and stops the run.
|
|
1140
|
+
}
|
|
860
1141
|
}
|
|
861
1142
|
/** X402-09's verdict from the status the underpaid payment drew. */
|
|
862
1143
|
export function underpaymentVerdict(status, offered, advertised, reason) {
|
|
@@ -895,13 +1176,13 @@ async function checkExpiredRejected(options) {
|
|
|
895
1176
|
const chain = chainFor(options.network);
|
|
896
1177
|
const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
|
|
897
1178
|
let holdMs = 0;
|
|
898
|
-
const { httpClient, paymentPayload, payUrl } = await preparePayment(options, "X402-10", async (selected) => {
|
|
1179
|
+
const { httpClient, paymentPayload, payUrl, entry } = await preparePayment(options, "X402-10", async (selected) => {
|
|
899
1180
|
const expired = await chain.expiredSigning(selected, rpcUrl);
|
|
900
1181
|
holdMs = expired.holdMs;
|
|
901
1182
|
return expired.terms;
|
|
902
1183
|
});
|
|
903
1184
|
await new Promise((done) => setTimeout(done, holdMs));
|
|
904
|
-
const response = await
|
|
1185
|
+
const response = await sendPayment(entry, payUrl, withPaymentHeaders(options, httpClient.encodePaymentSignatureHeader(paymentPayload)));
|
|
905
1186
|
return expiredVerdict(response.status, await refusalReason(response));
|
|
906
1187
|
}
|
|
907
1188
|
/** X402-10's verdict from the status the expired payment drew. */
|
|
@@ -1056,38 +1337,43 @@ async function checkRejectedRequestNotSettled(options, honest) {
|
|
|
1056
1337
|
return outside(error.lifetime, true);
|
|
1057
1338
|
throw error;
|
|
1058
1339
|
}
|
|
1059
|
-
const { httpClient, paymentPayload, selected, payUrl } = prepared;
|
|
1340
|
+
const { httpClient, paymentPayload, selected, payUrl, entry } = prepared;
|
|
1341
|
+
// A signed payment this check does not send: recorded as discarded, then the check stops.
|
|
1342
|
+
const discard = (message) => {
|
|
1343
|
+
recordDiscarded(entry, new Error(message));
|
|
1344
|
+
throw new CheckSetupError(message);
|
|
1345
|
+
};
|
|
1060
1346
|
const amount = BigInt(selected.amount);
|
|
1061
1347
|
const ours = authorizationOf(chain, paymentPayload.payload, payer, "this payment");
|
|
1062
1348
|
if (ours.nonce === control.nonce) {
|
|
1063
|
-
|
|
1349
|
+
discard("This payment's authorization carries X402-06's nonce, so it could not be told apart. It was not sent.");
|
|
1064
1350
|
}
|
|
1065
1351
|
// Right before sending: ours unused, the control found. This read's ledger
|
|
1066
1352
|
// starts the range the transfers are read over.
|
|
1067
1353
|
const before = await watch.read(network, rpcUrl, [ours, control]);
|
|
1068
1354
|
if (before.used[1] === undefined) {
|
|
1069
|
-
|
|
1355
|
+
discard("The chain's answer leaves out X402-06's authorization, so this payment was not sent.");
|
|
1070
1356
|
}
|
|
1071
1357
|
if (before.used[0] !== undefined) {
|
|
1072
|
-
|
|
1358
|
+
discard("The chain records this payment's authorization as used before it was sent, so it was not sent.");
|
|
1073
1359
|
}
|
|
1074
1360
|
// What the client signed, not what it was asked: an authorization that stays
|
|
1075
1361
|
// valid longer than the 300 s this check waits is not sent (2 units of slack
|
|
1076
1362
|
// for the ledgers that close while it is built).
|
|
1077
1363
|
const longest = Math.ceil(REJECTED_REQUEST_MAX_LIFETIME_SECONDS / watch.unitSeconds) + 2;
|
|
1078
1364
|
if (ours.expiresAt - before.latest > longest) {
|
|
1079
|
-
|
|
1365
|
+
discard(`This payment's authorization stays valid until ${watch.unit} ${ours.expiresAt}, ` +
|
|
1080
1366
|
`${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}), longer than the ` +
|
|
1081
1367
|
`${REJECTED_REQUEST_MAX_LIFETIME_SECONDS} seconds this check waits. It was signed and discarded; it was not sent.`);
|
|
1082
1368
|
}
|
|
1083
1369
|
// And long enough that a service which settles it could still get it on chain.
|
|
1084
1370
|
if (ours.expiresAt - before.latest < REJECTED_REQUEST_MIN_UNITS_LEFT) {
|
|
1085
|
-
|
|
1371
|
+
discard(`This payment's authorization expires at ${watch.unit} ${ours.expiresAt}, ` +
|
|
1086
1372
|
`${ours.expiresAt - before.latest} ${watch.unit}s after the latest (${before.latest}): too soon for an unused ` +
|
|
1087
1373
|
`authorization to show anything. It was signed and discarded; it was not sent.`);
|
|
1088
1374
|
}
|
|
1089
1375
|
const sentAt = Date.now();
|
|
1090
|
-
const response = await
|
|
1376
|
+
const response = await sendPayment(entry, payUrl, withPaymentHeaders(shape, httpClient.encodePaymentSignatureHeader(paymentPayload)));
|
|
1091
1377
|
const status = response.status;
|
|
1092
1378
|
const reason = await refusalReason(response);
|
|
1093
1379
|
options.onProgress?.(`X402-11: the payment was sent with the request the service must refuse (HTTP ${status}); reading the chain ` +
|
|
@@ -1121,7 +1407,7 @@ async function checkRejectedRequestNotSettled(options, honest) {
|
|
|
1121
1407
|
transfers = undefined;
|
|
1122
1408
|
}
|
|
1123
1409
|
}
|
|
1124
|
-
|
|
1410
|
+
const evidence = {
|
|
1125
1411
|
status,
|
|
1126
1412
|
...(reason === undefined ? {} : { reason }),
|
|
1127
1413
|
amount,
|
|
@@ -1130,7 +1416,13 @@ async function checkRejectedRequestNotSettled(options, honest) {
|
|
|
1130
1416
|
watch: outcome,
|
|
1131
1417
|
...(balance === undefined ? {} : { balance }),
|
|
1132
1418
|
...(transfers === undefined ? {} : { transfers }),
|
|
1133
|
-
}
|
|
1419
|
+
};
|
|
1420
|
+
// What the chain shows of this payment goes into the run ledger: a payment
|
|
1421
|
+
// the service took for a request it must refuse is a settlement the chain verified.
|
|
1422
|
+
const settlement = rejectedRequestSettlement(evidence);
|
|
1423
|
+
if (settlement !== undefined)
|
|
1424
|
+
recordSettlement(entry, settlement, true);
|
|
1425
|
+
return rejectedRequestVerdict(evidence);
|
|
1134
1426
|
}
|
|
1135
1427
|
/** The negative checks, in catalogue order, each with how it runs. */
|
|
1136
1428
|
const NEGATIVE_CHECKS = [
|
|
@@ -1156,10 +1448,25 @@ export const X402_PAYMENT_CHECK_IDS = [
|
|
|
1156
1448
|
* See docs/CHECKS.md.
|
|
1157
1449
|
*/
|
|
1158
1450
|
export async function runX402PaymentChecks(input) {
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1451
|
+
const allChecks = [
|
|
1452
|
+
["X402-06", "Signature Resubmit Accepted"],
|
|
1453
|
+
...NEGATIVE_CHECKS.map(([id, name]) => [id, name]),
|
|
1454
|
+
];
|
|
1455
|
+
// A mainnet run stopped by an earlier refusal (B3): every check of this
|
|
1456
|
+
// endpoint is skipped with the reason, and nothing is fetched or signed.
|
|
1457
|
+
const stoppedBefore = stopReason(input.mainnet);
|
|
1458
|
+
if (stoppedBefore !== undefined) {
|
|
1459
|
+
const results = allChecks.map(([id, name]) => skipped(id, name, stoppedBefore));
|
|
1460
|
+
for (const result of results)
|
|
1461
|
+
input.onResult?.(result);
|
|
1462
|
+
return results;
|
|
1463
|
+
}
|
|
1464
|
+
let options = input;
|
|
1162
1465
|
try {
|
|
1466
|
+
// One budget for every signature these checks make: the run's, when the
|
|
1467
|
+
// caller shares one across endpoints, or this call's own $5. On mainnet,
|
|
1468
|
+
// the opt-in's budget, pin, plan, ledger and RPC, and nothing else.
|
|
1469
|
+
options = input.mainnet === undefined ? { ...input, budget: input.budget ?? new RunBudget() } : mainnetOptions(input);
|
|
1163
1470
|
assertHttpUrl(options.target);
|
|
1164
1471
|
buildInit(options);
|
|
1165
1472
|
// The payment checks pay only where Wasit has an adapter, and X402-06 can
|
|
@@ -1168,15 +1475,15 @@ export async function runX402PaymentChecks(input) {
|
|
|
1168
1475
|
// after paying.
|
|
1169
1476
|
const chain = chainFor(options.network);
|
|
1170
1477
|
// L0: an adapter for the network is not permission to pay on it. Only a
|
|
1171
|
-
// test network passes
|
|
1172
|
-
|
|
1173
|
-
assertPaymentNetworkAllowed("x402", options.network);
|
|
1478
|
+
// test network passes, and stellar:pubnet with a live mainnet opt-in.
|
|
1479
|
+
assertPaymentNetworkAllowed("x402", options.network, options.mainnet);
|
|
1174
1480
|
const rpcUrl = chain.resolveRpcUrl(options.network, options.rpcUrl);
|
|
1175
1481
|
// A key for another chain, or a malformed one, would otherwise surface
|
|
1176
1482
|
// mid-payment as a harness error. Checked here, it is what it is: the
|
|
1177
1483
|
// run's configuration. The message never echoes the key.
|
|
1484
|
+
let payer;
|
|
1178
1485
|
try {
|
|
1179
|
-
chain.payerAddress(options.payerSecretKey);
|
|
1486
|
+
payer = chain.payerAddress(options.payerSecretKey);
|
|
1180
1487
|
}
|
|
1181
1488
|
catch (error) {
|
|
1182
1489
|
if (error instanceof ConfigurationError)
|
|
@@ -1184,9 +1491,13 @@ export async function runX402PaymentChecks(input) {
|
|
|
1184
1491
|
throw new ConfigurationError(`The payer key is not a valid ${chain.name} key (read from ${chain.payerKeyEnv} ` +
|
|
1185
1492
|
`or --payer-key).`);
|
|
1186
1493
|
}
|
|
1494
|
+
if (options.mainnet !== undefined && payer !== options.mainnet.payer) {
|
|
1495
|
+
throw stopMainnet(options.mainnet, "These checks were handed the key of another account than the mainnet run's payer.");
|
|
1496
|
+
}
|
|
1187
1497
|
// The RPC signs and settles nothing itself, but the payment is built and
|
|
1188
|
-
//
|
|
1189
|
-
|
|
1498
|
+
// the settlement read through it: it must be one the client accepts and
|
|
1499
|
+
// serve the run's network (D-023).
|
|
1500
|
+
await assertX402PaymentRpc(options.network, rpcUrl);
|
|
1190
1501
|
}
|
|
1191
1502
|
catch (error) {
|
|
1192
1503
|
// A network no adapter pays on is not a failure of the run: Wasit does not
|
|
@@ -1207,6 +1518,7 @@ export async function runX402PaymentChecks(input) {
|
|
|
1207
1518
|
const results = [];
|
|
1208
1519
|
const emit = (result) => {
|
|
1209
1520
|
results.push(result);
|
|
1521
|
+
recordVerdict(options.ledger, result);
|
|
1210
1522
|
options.onResult?.(result);
|
|
1211
1523
|
};
|
|
1212
1524
|
const skipNegatives = (reason) => {
|
|
@@ -1225,6 +1537,9 @@ export async function runX402PaymentChecks(input) {
|
|
|
1225
1537
|
}
|
|
1226
1538
|
const failed = errored("X402-06", "Signature Resubmit Accepted", error);
|
|
1227
1539
|
emit(failed);
|
|
1540
|
+
const stopped = stopReason(options.mainnet);
|
|
1541
|
+
if (stopped !== undefined)
|
|
1542
|
+
return skipNegatives(stopped);
|
|
1228
1543
|
// If the payment flow could not be exercised at all, no altered variant of
|
|
1229
1544
|
// it can be either, and none may be reported as a passing rejection.
|
|
1230
1545
|
return skipNegatives(`the payment flow could not be exercised (${failed.error?.kind ?? "harness"}), ` +
|
|
@@ -1238,13 +1553,104 @@ export async function runX402PaymentChecks(input) {
|
|
|
1238
1553
|
return skipNegatives("the target refused X402-06's valid payment, so refusing an altered one " +
|
|
1239
1554
|
"says nothing about what it checks.");
|
|
1240
1555
|
}
|
|
1556
|
+
// B8: once a new challenge drew a 409, the resource is used up: every later
|
|
1557
|
+
// check that needs one is skipped as "resource consumed" without asking again,
|
|
1558
|
+
// and the replay, which needs none, still runs.
|
|
1559
|
+
let consumed = false;
|
|
1241
1560
|
for (const [id, name, run] of NEGATIVE_CHECKS) {
|
|
1561
|
+
// B3: once a mainnet run is stopped, nothing more is signed in it.
|
|
1562
|
+
const stopped = stopReason(options.mainnet);
|
|
1563
|
+
if (stopped !== undefined) {
|
|
1564
|
+
emit(skipped(id, name, stopped));
|
|
1565
|
+
continue;
|
|
1566
|
+
}
|
|
1567
|
+
if (consumed && id !== REPLAY_CHECK) {
|
|
1568
|
+
emit(skipped(id, name, RESOURCE_CONSUMED_REASON, "resource-consumed"));
|
|
1569
|
+
continue;
|
|
1570
|
+
}
|
|
1242
1571
|
try {
|
|
1243
1572
|
emit(await run(options, honest));
|
|
1244
1573
|
}
|
|
1245
1574
|
catch (error) {
|
|
1575
|
+
if (error instanceof ResourceConsumedError) {
|
|
1576
|
+
consumed = true;
|
|
1577
|
+
emit(skipped(id, name, RESOURCE_CONSUMED_REASON, "resource-consumed"));
|
|
1578
|
+
continue;
|
|
1579
|
+
}
|
|
1246
1580
|
emit(errored(id, name, error));
|
|
1247
1581
|
}
|
|
1248
1582
|
}
|
|
1249
1583
|
return results;
|
|
1250
1584
|
}
|
|
1585
|
+
/** What a result says about the target, as the run ledger records it. */
|
|
1586
|
+
function verdictOf(result) {
|
|
1587
|
+
if (result.skipped === true)
|
|
1588
|
+
return "skipped";
|
|
1589
|
+
if (result.error !== undefined)
|
|
1590
|
+
return "no-verdict";
|
|
1591
|
+
return result.pass ? "pass" : "fail";
|
|
1592
|
+
}
|
|
1593
|
+
/**
|
|
1594
|
+
* Records a check's verdict on its entries in the run ledger. A ledger that
|
|
1595
|
+
* cannot take it keeps none, and a payment of that check then explains
|
|
1596
|
+
* nothing when the balances are compared: the safe side.
|
|
1597
|
+
*/
|
|
1598
|
+
function recordVerdict(ledger, result) {
|
|
1599
|
+
try {
|
|
1600
|
+
ledger?.verdict?.(result.id, verdictOf(result));
|
|
1601
|
+
}
|
|
1602
|
+
catch {
|
|
1603
|
+
// The result stands; see above.
|
|
1604
|
+
}
|
|
1605
|
+
}
|
|
1606
|
+
/** Why a check of a stopped mainnet run is skipped; undefined while the run goes on, or with no opt-in. */
|
|
1607
|
+
function stopReason(mainnet) {
|
|
1608
|
+
const reason = mainnet?.stopped;
|
|
1609
|
+
if (reason === undefined)
|
|
1610
|
+
return undefined;
|
|
1611
|
+
return `the mainnet run stopped, and nothing more is signed in it: ${sanitizeText(String(reason)).slice(0, 400)}`;
|
|
1612
|
+
}
|
|
1613
|
+
/** Stops `mainnet` with `message` and returns the error to throw. */
|
|
1614
|
+
function stopMainnet(mainnet, message) {
|
|
1615
|
+
const error = new MainnetRunRefusedError("run", message, { during: true });
|
|
1616
|
+
mainnet.stop(error.message);
|
|
1617
|
+
return error;
|
|
1618
|
+
}
|
|
1619
|
+
/**
|
|
1620
|
+
* The options a mainnet run's checks pay by (spec B5): the opt-in's own
|
|
1621
|
+
* budget, pin, plan entry, ledger and RPC. A value handed in beside it that is
|
|
1622
|
+
* not the opt-in's is refused and the run stopped: on mainnet nothing is paid
|
|
1623
|
+
* by terms core did not plan.
|
|
1624
|
+
*/
|
|
1625
|
+
function mainnetOptions(input) {
|
|
1626
|
+
const optIn = input.mainnet;
|
|
1627
|
+
if (input.network !== optIn.network) {
|
|
1628
|
+
throw stopMainnet(optIn, `A mainnet opt-in was handed to checks on another network than ${optIn.network}.`);
|
|
1629
|
+
}
|
|
1630
|
+
// L0 first: a stopped, closed or forged opt-in is refused here, and says why.
|
|
1631
|
+
assertPaymentNetworkAllowed("x402", input.network, optIn);
|
|
1632
|
+
const plan = optIn.plan;
|
|
1633
|
+
if (plan === undefined)
|
|
1634
|
+
throw stopMainnet(optIn, "The mainnet run has no plan that passed: its plan comes before any payment.");
|
|
1635
|
+
const entry = input.plan;
|
|
1636
|
+
if (entry === undefined || !plan.endpoints.includes(entry)) {
|
|
1637
|
+
throw stopMainnet(optIn, "These checks were not handed an entry of the mainnet run's own plan.");
|
|
1638
|
+
}
|
|
1639
|
+
if (input.budget !== undefined && input.budget !== optIn.budget) {
|
|
1640
|
+
throw stopMainnet(optIn, "These checks were handed another budget than the mainnet run's.");
|
|
1641
|
+
}
|
|
1642
|
+
if (input.pin !== undefined && (input.pin.payTo !== optIn.pin.payTo || input.pin.asset !== optIn.pin.asset)) {
|
|
1643
|
+
throw stopMainnet(optIn, "These checks were handed another pin than the mainnet run's.");
|
|
1644
|
+
}
|
|
1645
|
+
if (input.rpcUrl !== undefined && input.rpcUrl !== optIn.rpcUrl) {
|
|
1646
|
+
throw stopMainnet(optIn, "These checks were handed another RPC than the mainnet run's.");
|
|
1647
|
+
}
|
|
1648
|
+
if (input.ledger !== undefined) {
|
|
1649
|
+
throw stopMainnet(optIn, "These checks were handed a ledger of their own: a mainnet run writes every signature to its own.");
|
|
1650
|
+
}
|
|
1651
|
+
const ledger = optIn.ledger;
|
|
1652
|
+
if (ledger === undefined) {
|
|
1653
|
+
throw stopMainnet(optIn, "The mainnet run's ledger is not open: on mainnet every signature is written to it first.");
|
|
1654
|
+
}
|
|
1655
|
+
return { ...input, budget: optIn.budget, pin: optIn.pin, rpcUrl: optIn.rpcUrl, ledger: ledger.forEndpoint(entry.name) };
|
|
1656
|
+
}
|