uvd-x402-sdk 2.75.0 → 2.77.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +145 -1
- package/dist/backend/index.d.mts +348 -52
- package/dist/backend/index.d.ts +348 -52
- package/dist/backend/index.js +470 -235
- package/dist/backend/index.js.map +1 -1
- package/dist/backend/index.mjs +459 -236
- package/dist/backend/index.mjs.map +1 -1
- package/dist/index.d.mts +44 -6
- package/dist/index.d.ts +44 -6
- package/dist/index.js +244 -39
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +234 -40
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/backend/facilitator-error.ts +355 -0
- package/src/backend/index.ts +536 -263
- package/src/dx402.ts +130 -10
- package/src/index.ts +17 -0
package/src/backend/index.ts
CHANGED
|
@@ -73,6 +73,39 @@ import type {
|
|
|
73
73
|
import { decodeX402Header, chainToCAIP2, parseNetworkIdentifier } from '../utils';
|
|
74
74
|
import { REVIEW_WINDOW_SEC, REFUND_WINDOW_SEC } from '../escrow-preauth';
|
|
75
75
|
import { getChainByName } from '../chains';
|
|
76
|
+
import {
|
|
77
|
+
DEFAULT_RETRY_AFTER_SECONDS,
|
|
78
|
+
carryFailureFields,
|
|
79
|
+
isReplayableLeaseReason,
|
|
80
|
+
facilitatorFetch,
|
|
81
|
+
failureFields,
|
|
82
|
+
readFacilitatorError,
|
|
83
|
+
} from './facilitator-error';
|
|
84
|
+
import type { FacilitatorErrorInfo, FacilitatorFailureFields } from './facilitator-error';
|
|
85
|
+
|
|
86
|
+
// A facilitator refusal is DATA, not prose. `402` and `503` say opposite things
|
|
87
|
+
// and this file used to answer both with `success: false` plus a sentence --
|
|
88
|
+
// see ./facilitator-error.ts for why that costs the buyer a second payment.
|
|
89
|
+
export {
|
|
90
|
+
AMBIGUOUS_LEASE_REASONS,
|
|
91
|
+
DEFAULT_FACILITATOR_RETRIES,
|
|
92
|
+
DEFAULT_RETRY_AFTER_SECONDS,
|
|
93
|
+
MAX_RETRY_AFTER_SECONDS,
|
|
94
|
+
REPLAYABLE_LEASE_REASONS,
|
|
95
|
+
WRITER_LEASE_REASONS,
|
|
96
|
+
carryFailureFields,
|
|
97
|
+
facilitatorFetch,
|
|
98
|
+
isAmbiguousLeaseReason,
|
|
99
|
+
isReplayableLeaseReason,
|
|
100
|
+
parseRetryAfterSeconds,
|
|
101
|
+
readFacilitatorError,
|
|
102
|
+
} from './facilitator-error';
|
|
103
|
+
export type {
|
|
104
|
+
FacilitatorErrorInfo,
|
|
105
|
+
FacilitatorFailureFields,
|
|
106
|
+
FacilitatorFetchOptions,
|
|
107
|
+
WriterLeaseReason,
|
|
108
|
+
} from './facilitator-error';
|
|
76
109
|
|
|
77
110
|
// ============================================================================
|
|
78
111
|
// TYPES
|
|
@@ -127,8 +160,16 @@ export interface SettleRequest {
|
|
|
127
160
|
/**
|
|
128
161
|
* Verify response from the facilitator
|
|
129
162
|
*/
|
|
130
|
-
export interface VerifyResponse {
|
|
163
|
+
export interface VerifyResponse extends FacilitatorFailureFields {
|
|
131
164
|
isValid: boolean;
|
|
165
|
+
/**
|
|
166
|
+
* Why the payment is not valid.
|
|
167
|
+
*
|
|
168
|
+
* Read `retryable` before showing this to anyone. When `retryable` is true the
|
|
169
|
+
* facilitator reached NO VERDICT -- it did not reject the payment, so this
|
|
170
|
+
* string is a transport diagnosis, not a rejection, and re-signing on it makes
|
|
171
|
+
* the buyer pay twice.
|
|
172
|
+
*/
|
|
132
173
|
invalidReason?: string;
|
|
133
174
|
payer?: string;
|
|
134
175
|
network?: string;
|
|
@@ -137,11 +178,17 @@ export interface VerifyResponse {
|
|
|
137
178
|
/**
|
|
138
179
|
* Settle response from the facilitator
|
|
139
180
|
*/
|
|
140
|
-
export interface SettleResponse {
|
|
181
|
+
export interface SettleResponse extends FacilitatorFailureFields {
|
|
141
182
|
success: boolean;
|
|
142
183
|
transactionHash?: string;
|
|
143
184
|
network?: string;
|
|
144
|
-
/**
|
|
185
|
+
/**
|
|
186
|
+
* Transport-level failure (unreachable facilitator, non-2xx, timeout).
|
|
187
|
+
*
|
|
188
|
+
* `success: false` with `retryable: true` is NOT a rejected payment. The
|
|
189
|
+
* authorization is untouched and the same one must be resent; treating it as
|
|
190
|
+
* a refusal and asking for a new signature charges the buyer twice.
|
|
191
|
+
*/
|
|
145
192
|
error?: string;
|
|
146
193
|
/**
|
|
147
194
|
* The facilitator's own reason when it settled nothing — e.g. a transfer that
|
|
@@ -605,6 +652,15 @@ export interface FacilitatorClientOptions {
|
|
|
605
652
|
* Set explicitly to override per-network auto-detection.
|
|
606
653
|
*/
|
|
607
654
|
timeout?: number;
|
|
655
|
+
/**
|
|
656
|
+
* Extra attempts after the first when the facilitator answers a refusal it
|
|
657
|
+
* proved it did not execute (`safeToReplay`). Default 2; `0` disables.
|
|
658
|
+
*
|
|
659
|
+
* Only ever spent on `429` and on a `503` naming a pre-execution writer-lease
|
|
660
|
+
* reason. An ambiguous `forward_failed` -- whose write may already have landed
|
|
661
|
+
* -- is never replayed here, at any setting.
|
|
662
|
+
*/
|
|
663
|
+
retries?: number;
|
|
608
664
|
}
|
|
609
665
|
|
|
610
666
|
/**
|
|
@@ -631,11 +687,13 @@ export class FacilitatorClient {
|
|
|
631
687
|
private readonly baseUrl: string;
|
|
632
688
|
private readonly timeout: number;
|
|
633
689
|
private readonly explicitTimeout: boolean;
|
|
690
|
+
private readonly retries: number | undefined;
|
|
634
691
|
|
|
635
692
|
constructor(options: FacilitatorClientOptions = {}) {
|
|
636
693
|
this.baseUrl = options.baseUrl || 'https://facilitator.ultravioletadao.xyz';
|
|
637
694
|
this.explicitTimeout = options.timeout !== undefined;
|
|
638
695
|
this.timeout = options.timeout || 30000;
|
|
696
|
+
this.retries = options.retries;
|
|
639
697
|
}
|
|
640
698
|
|
|
641
699
|
/**
|
|
@@ -670,33 +728,41 @@ export class FacilitatorClient {
|
|
|
670
728
|
): Promise<VerifyResponse> {
|
|
671
729
|
const body = buildVerifyRequest(paymentHeader, requirements);
|
|
672
730
|
|
|
673
|
-
const controller = new AbortController();
|
|
674
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
675
|
-
|
|
676
731
|
try {
|
|
677
|
-
const response = await
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
732
|
+
const { response, error } = await facilitatorFetch(
|
|
733
|
+
`${this.baseUrl}/verify`,
|
|
734
|
+
{
|
|
735
|
+
method: 'POST',
|
|
736
|
+
headers: { 'Content-Type': 'application/json' },
|
|
737
|
+
body: JSON.stringify(body),
|
|
738
|
+
},
|
|
739
|
+
{ timeoutMs: this.timeout, retries: this.retries },
|
|
740
|
+
);
|
|
685
741
|
|
|
686
|
-
if (
|
|
687
|
-
|
|
742
|
+
if (error) {
|
|
743
|
+
// `isValid: false` is unavoidable -- nothing was validated -- but it is
|
|
744
|
+
// no longer the whole story. A caller that answers 402 on this without
|
|
745
|
+
// reading `retryable` tells the buyer their payment was REFUSED and
|
|
746
|
+
// asks them to sign another one, for a payment the facilitator never
|
|
747
|
+
// looked at. That is the double-charge this field exists to prevent.
|
|
688
748
|
return {
|
|
689
749
|
isValid: false,
|
|
690
|
-
invalidReason:
|
|
750
|
+
invalidReason: error.error,
|
|
751
|
+
...failureFields(error),
|
|
691
752
|
};
|
|
692
753
|
}
|
|
693
754
|
|
|
694
755
|
return await response.json();
|
|
695
756
|
} catch (error) {
|
|
696
|
-
|
|
757
|
+
// A thrown error is a transport failure (timeout, DNS, connection reset).
|
|
758
|
+
// No verdict was reached either, so it is retryable for exactly the same
|
|
759
|
+
// reason a 503 is -- and it used to be reported as an invalid payment.
|
|
697
760
|
return {
|
|
698
761
|
isValid: false,
|
|
699
762
|
invalidReason: error instanceof Error ? error.message : 'Unknown error',
|
|
763
|
+
retryable: true,
|
|
764
|
+
safeToReplay: false,
|
|
765
|
+
retryAfterSeconds: DEFAULT_RETRY_AFTER_SECONDS,
|
|
700
766
|
};
|
|
701
767
|
}
|
|
702
768
|
}
|
|
@@ -717,24 +783,29 @@ export class FacilitatorClient {
|
|
|
717
783
|
const body = buildSettleRequest(paymentHeader, requirements);
|
|
718
784
|
const settleTimeout = this.getTimeout(requirements.network);
|
|
719
785
|
|
|
720
|
-
const controller = new AbortController();
|
|
721
|
-
const timeoutId = setTimeout(() => controller.abort(), settleTimeout);
|
|
722
|
-
|
|
723
786
|
try {
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
787
|
+
// A `/settle` refusal that the facilitator proved it did not execute is
|
|
788
|
+
// replayed here with the SAME authorization. That is safe twice over: the
|
|
789
|
+
// facilitator refused in its router before signing anything, and the
|
|
790
|
+
// authorization carries a single-use nonce the chain rejects on a real
|
|
791
|
+
// duplicate. What is NOT replayed is `forward_failed` -- the hop to the
|
|
792
|
+
// lease holder died after handing the write over, so the transfer may
|
|
793
|
+
// already be mining.
|
|
794
|
+
const { response, error } = await facilitatorFetch(
|
|
795
|
+
`${this.baseUrl}/settle`,
|
|
796
|
+
{
|
|
797
|
+
method: 'POST',
|
|
798
|
+
headers: { 'Content-Type': 'application/json' },
|
|
799
|
+
body: JSON.stringify(body),
|
|
800
|
+
},
|
|
801
|
+
{ timeoutMs: settleTimeout, retries: this.retries },
|
|
802
|
+
);
|
|
732
803
|
|
|
733
|
-
if (
|
|
734
|
-
const errorText = await response.text();
|
|
804
|
+
if (error) {
|
|
735
805
|
return {
|
|
736
806
|
success: false,
|
|
737
|
-
error:
|
|
807
|
+
error: error.error,
|
|
808
|
+
...failureFields(error),
|
|
738
809
|
};
|
|
739
810
|
}
|
|
740
811
|
|
|
@@ -791,10 +862,16 @@ export class FacilitatorClient {
|
|
|
791
862
|
payer: result.payer,
|
|
792
863
|
};
|
|
793
864
|
} catch (error) {
|
|
794
|
-
|
|
865
|
+
// Timeout or connection failure. The write may have landed -- this is the
|
|
866
|
+
// same ambiguity as `forward_failed`, so it is retryable but never
|
|
867
|
+
// replayed automatically. Reconcile on-chain, or by transaction hash,
|
|
868
|
+
// before sending anything again.
|
|
795
869
|
return {
|
|
796
870
|
success: false,
|
|
797
871
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
872
|
+
retryable: true,
|
|
873
|
+
safeToReplay: false,
|
|
874
|
+
retryAfterSeconds: DEFAULT_RETRY_AFTER_SECONDS,
|
|
798
875
|
};
|
|
799
876
|
}
|
|
800
877
|
}
|
|
@@ -812,19 +889,25 @@ export class FacilitatorClient {
|
|
|
812
889
|
async verifyAndSettle(
|
|
813
890
|
paymentHeader: X402Header,
|
|
814
891
|
requirements: PaymentRequirements
|
|
815
|
-
): Promise<
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
892
|
+
): Promise<
|
|
893
|
+
{
|
|
894
|
+
verified: boolean;
|
|
895
|
+
settled: boolean;
|
|
896
|
+
transactionHash?: string;
|
|
897
|
+
error?: string;
|
|
898
|
+
} & FacilitatorFailureFields
|
|
899
|
+
> {
|
|
821
900
|
// Verify first
|
|
822
901
|
const verifyResult = await this.verify(paymentHeader, requirements);
|
|
823
902
|
if (!verifyResult.isValid) {
|
|
903
|
+
// Carry the refusal's shape up. Flattening it to `verified: false` here
|
|
904
|
+
// would undo the whole point one level below: the caller could not tell a
|
|
905
|
+
// rejected authorization from a facilitator that never answered.
|
|
824
906
|
return {
|
|
825
907
|
verified: false,
|
|
826
908
|
settled: false,
|
|
827
909
|
error: verifyResult.invalidReason,
|
|
910
|
+
...carryFailureFields(verifyResult),
|
|
828
911
|
};
|
|
829
912
|
}
|
|
830
913
|
|
|
@@ -835,6 +918,7 @@ export class FacilitatorClient {
|
|
|
835
918
|
settled: settleResult.success,
|
|
836
919
|
transactionHash: settleResult.transactionHash,
|
|
837
920
|
error: settleResult.error,
|
|
921
|
+
...carryFailureFields(settleResult),
|
|
838
922
|
};
|
|
839
923
|
}
|
|
840
924
|
|
|
@@ -1397,6 +1481,41 @@ function createVerifiedPaymentState(
|
|
|
1397
1481
|
};
|
|
1398
1482
|
}
|
|
1399
1483
|
|
|
1484
|
+
/**
|
|
1485
|
+
* Answer a no-verdict facilitator refusal as 503 + `Retry-After`.
|
|
1486
|
+
*
|
|
1487
|
+
* The body repeats the facilitator's own `reason` and a `retryable` flag so a
|
|
1488
|
+
* client that only reads JSON still learns the payment was not rejected. The
|
|
1489
|
+
* header is a whole-second integer, as RFC 9110 requires.
|
|
1490
|
+
*/
|
|
1491
|
+
function respondUnavailable(
|
|
1492
|
+
res: {
|
|
1493
|
+
status: (code: number) => {
|
|
1494
|
+
json: (body: unknown) => void;
|
|
1495
|
+
set: (headers: Record<string, string>) => { json: (body: unknown) => void };
|
|
1496
|
+
};
|
|
1497
|
+
},
|
|
1498
|
+
message: string,
|
|
1499
|
+
failure: FacilitatorFailureFields & { error?: string; invalidReason?: string },
|
|
1500
|
+
): void {
|
|
1501
|
+
const seconds = Math.max(1, Math.ceil(failure.retryAfterSeconds ?? DEFAULT_RETRY_AFTER_SECONDS));
|
|
1502
|
+
const body = {
|
|
1503
|
+
error: message,
|
|
1504
|
+
reason: failure.reason ?? failure.invalidReason ?? failure.error,
|
|
1505
|
+
retryable: true,
|
|
1506
|
+
retryAfterSeconds: seconds,
|
|
1507
|
+
// False for `forward_failed` and for a bare timeout: the write may already
|
|
1508
|
+
// have landed, so the caller must reconcile before resending.
|
|
1509
|
+
safeToReplay: failure.safeToReplay === true,
|
|
1510
|
+
};
|
|
1511
|
+
const staged = res.status(503);
|
|
1512
|
+
if (typeof staged.set === 'function') {
|
|
1513
|
+
staged.set({ 'Retry-After': String(seconds) }).json(body);
|
|
1514
|
+
return;
|
|
1515
|
+
}
|
|
1516
|
+
staged.json(body);
|
|
1517
|
+
}
|
|
1518
|
+
|
|
1400
1519
|
/**
|
|
1401
1520
|
* Create an Express-compatible middleware for x402 payments
|
|
1402
1521
|
*
|
|
@@ -1436,6 +1555,7 @@ export function createPaymentMiddleware(
|
|
|
1436
1555
|
const client = new FacilitatorClient({
|
|
1437
1556
|
baseUrl: options.facilitatorUrl || options.baseUrl,
|
|
1438
1557
|
timeout: options.timeout,
|
|
1558
|
+
retries: options.retries,
|
|
1439
1559
|
});
|
|
1440
1560
|
const settlementStrategy = options.settlementStrategy || 'before-handler';
|
|
1441
1561
|
|
|
@@ -1457,6 +1577,15 @@ export function createPaymentMiddleware(
|
|
|
1457
1577
|
const verifyResult = await client.verify(payment, requirements);
|
|
1458
1578
|
|
|
1459
1579
|
if (!verifyResult.isValid) {
|
|
1580
|
+
// 402 says "your payment was REJECTED, sign a new authorization". Sending
|
|
1581
|
+
// it for a facilitator that never reached a verdict is what makes the
|
|
1582
|
+
// buyer pay twice: their first authorization was never refused and is
|
|
1583
|
+
// still perfectly good. A no-verdict answer must keep the credential
|
|
1584
|
+
// alive, so it goes out as 503 + Retry-After instead.
|
|
1585
|
+
if (verifyResult.retryable) {
|
|
1586
|
+
respondUnavailable(res, 'Payment verification unavailable', verifyResult);
|
|
1587
|
+
return;
|
|
1588
|
+
}
|
|
1460
1589
|
res.status(402).json({
|
|
1461
1590
|
error: 'Payment verification failed',
|
|
1462
1591
|
reason: verifyResult.invalidReason,
|
|
@@ -1469,6 +1598,13 @@ export function createPaymentMiddleware(
|
|
|
1469
1598
|
if (settlementStrategy === 'before-handler') {
|
|
1470
1599
|
const settleResult = await req.x402.settle();
|
|
1471
1600
|
if (!settleResult.success) {
|
|
1601
|
+
// Same distinction on the settle side. A 500 tells a client its request
|
|
1602
|
+
// is broken and to stop; a settle that reached no verdict is the one
|
|
1603
|
+
// case where retrying the identical request is correct.
|
|
1604
|
+
if (settleResult.retryable) {
|
|
1605
|
+
respondUnavailable(res, 'Payment settlement unavailable', settleResult);
|
|
1606
|
+
return;
|
|
1607
|
+
}
|
|
1472
1608
|
res.status(500).json({
|
|
1473
1609
|
error: 'Payment settlement failed',
|
|
1474
1610
|
reason: settleResult.error || 'Unknown settlement error',
|
|
@@ -1528,10 +1664,34 @@ export interface HonoMiddlewareOptions extends PaymentMiddlewareOptions {
|
|
|
1528
1664
|
* });
|
|
1529
1665
|
* ```
|
|
1530
1666
|
*/
|
|
1667
|
+
/** {@link respondUnavailable} for a Hono context. */
|
|
1668
|
+
function honoUnavailable(
|
|
1669
|
+
c: {
|
|
1670
|
+
json: (body: unknown, status?: number) => unknown;
|
|
1671
|
+
header?: (name: string, value: string) => void;
|
|
1672
|
+
},
|
|
1673
|
+
message: string,
|
|
1674
|
+
failure: FacilitatorFailureFields & { error?: string; invalidReason?: string },
|
|
1675
|
+
): unknown {
|
|
1676
|
+
const seconds = Math.max(1, Math.ceil(failure.retryAfterSeconds ?? DEFAULT_RETRY_AFTER_SECONDS));
|
|
1677
|
+
c.header?.('Retry-After', String(seconds));
|
|
1678
|
+
return c.json(
|
|
1679
|
+
{
|
|
1680
|
+
error: message,
|
|
1681
|
+
reason: failure.reason ?? failure.invalidReason ?? failure.error,
|
|
1682
|
+
retryable: true,
|
|
1683
|
+
retryAfterSeconds: seconds,
|
|
1684
|
+
safeToReplay: failure.safeToReplay === true,
|
|
1685
|
+
},
|
|
1686
|
+
503,
|
|
1687
|
+
);
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1531
1690
|
export function createHonoMiddleware(options: HonoMiddlewareOptions) {
|
|
1532
1691
|
const client = new FacilitatorClient({
|
|
1533
1692
|
baseUrl: options.facilitatorUrl || options.baseUrl,
|
|
1534
1693
|
timeout: options.timeout,
|
|
1694
|
+
retries: options.retries,
|
|
1535
1695
|
});
|
|
1536
1696
|
const settlementStrategy = options.settlementStrategy || 'before-handler';
|
|
1537
1697
|
|
|
@@ -1544,6 +1704,8 @@ export function createHonoMiddleware(options: HonoMiddlewareOptions) {
|
|
|
1544
1704
|
req: { header: (name: string) => string | undefined; url: string };
|
|
1545
1705
|
json: (body: unknown, status?: number) => unknown;
|
|
1546
1706
|
set?: (key: string, value: unknown) => void;
|
|
1707
|
+
/** Hono's response-header setter. Optional so older context doubles still fit. */
|
|
1708
|
+
header?: (name: string, value: string) => void;
|
|
1547
1709
|
},
|
|
1548
1710
|
next: () => Promise<void>
|
|
1549
1711
|
) => {
|
|
@@ -1585,6 +1747,11 @@ export function createHonoMiddleware(options: HonoMiddlewareOptions) {
|
|
|
1585
1747
|
|
|
1586
1748
|
const verifyResult = await client.verify(parsed, requirement);
|
|
1587
1749
|
if (!verifyResult.isValid) {
|
|
1750
|
+
// See respondUnavailable: 402 here would tell the buyer to sign again for
|
|
1751
|
+
// an authorization the facilitator never rejected.
|
|
1752
|
+
if (verifyResult.retryable) {
|
|
1753
|
+
return honoUnavailable(c, 'Payment verification unavailable', verifyResult);
|
|
1754
|
+
}
|
|
1588
1755
|
return c.json({
|
|
1589
1756
|
error: 'Payment verification failed',
|
|
1590
1757
|
reason: verifyResult.invalidReason,
|
|
@@ -1597,6 +1764,9 @@ export function createHonoMiddleware(options: HonoMiddlewareOptions) {
|
|
|
1597
1764
|
if (settlementStrategy === 'before-handler') {
|
|
1598
1765
|
const settleResult = await verifiedPayment.settle();
|
|
1599
1766
|
if (!settleResult.success) {
|
|
1767
|
+
if (settleResult.retryable) {
|
|
1768
|
+
return honoUnavailable(c, 'Payment settlement unavailable', settleResult);
|
|
1769
|
+
}
|
|
1600
1770
|
return c.json({
|
|
1601
1771
|
error: 'Payment settlement failed',
|
|
1602
1772
|
reason: settleResult.error || 'Unknown error',
|
|
@@ -3456,7 +3626,7 @@ export interface FeedbackRequest {
|
|
|
3456
3626
|
/**
|
|
3457
3627
|
* Feedback response from POST /feedback
|
|
3458
3628
|
*/
|
|
3459
|
-
export interface FeedbackResponse {
|
|
3629
|
+
export interface FeedbackResponse extends FacilitatorFailureFields {
|
|
3460
3630
|
/** Whether the feedback was successfully submitted */
|
|
3461
3631
|
success: boolean;
|
|
3462
3632
|
/** Transaction hash of the feedback submission */
|
|
@@ -3487,12 +3657,21 @@ export class Erc8004LookupError extends Error {
|
|
|
3487
3657
|
readonly status: number;
|
|
3488
3658
|
/** Raw response body, for debugging */
|
|
3489
3659
|
readonly body: string;
|
|
3660
|
+
/**
|
|
3661
|
+
* `Retry-After`, already clamped, when the facilitator sent one.
|
|
3662
|
+
*
|
|
3663
|
+
* Optional so every existing three-argument construction keeps compiling; it
|
|
3664
|
+
* falls back to the default wait rather than to zero, because a caller that
|
|
3665
|
+
* retries instantly on a 503 is the load that caused it.
|
|
3666
|
+
*/
|
|
3667
|
+
private readonly retryAfterHint: number | undefined;
|
|
3490
3668
|
|
|
3491
|
-
constructor(message: string, status: number, body: string) {
|
|
3669
|
+
constructor(message: string, status: number, body: string, retryAfterSeconds?: number) {
|
|
3492
3670
|
super(message);
|
|
3493
3671
|
this.name = 'Erc8004LookupError';
|
|
3494
3672
|
this.status = status;
|
|
3495
3673
|
this.body = body;
|
|
3674
|
+
this.retryAfterHint = retryAfterSeconds;
|
|
3496
3675
|
}
|
|
3497
3676
|
|
|
3498
3677
|
/** The address genuinely owns no agent on this network. */
|
|
@@ -3500,9 +3679,55 @@ export class Erc8004LookupError extends Error {
|
|
|
3500
3679
|
return this.status === 404;
|
|
3501
3680
|
}
|
|
3502
3681
|
|
|
3503
|
-
/**
|
|
3682
|
+
/**
|
|
3683
|
+
* The lookup reached no verdict. Retry; never read as "owns nothing".
|
|
3684
|
+
*
|
|
3685
|
+
* `502` and `504` join `503` and `429` here: a gateway that answered on the
|
|
3686
|
+
* facilitator's behalf is exactly as silent about the agent's existence, and
|
|
3687
|
+
* reading either as absence has the same consequence -- a duplicate mint.
|
|
3688
|
+
*/
|
|
3504
3689
|
get retryable(): boolean {
|
|
3505
|
-
return
|
|
3690
|
+
return (
|
|
3691
|
+
this.status === 429 ||
|
|
3692
|
+
this.status === 502 ||
|
|
3693
|
+
this.status === 503 ||
|
|
3694
|
+
this.status === 504
|
|
3695
|
+
);
|
|
3696
|
+
}
|
|
3697
|
+
|
|
3698
|
+
/**
|
|
3699
|
+
* The facilitator's own `reason`, when the body carried one.
|
|
3700
|
+
*
|
|
3701
|
+
* On a WRITE route this is the writer-lease reason and it decides whether the
|
|
3702
|
+
* request may be re-sent; see {@link isReplayableLeaseReason}.
|
|
3703
|
+
*/
|
|
3704
|
+
get reason(): string | undefined {
|
|
3705
|
+
try {
|
|
3706
|
+
const parsed = JSON.parse(this.body) as { reason?: unknown };
|
|
3707
|
+
if (parsed && typeof parsed === 'object' && typeof parsed.reason === 'string') {
|
|
3708
|
+
return parsed.reason;
|
|
3709
|
+
}
|
|
3710
|
+
} catch {
|
|
3711
|
+
/* a non-JSON body is still a status */
|
|
3712
|
+
}
|
|
3713
|
+
return undefined;
|
|
3714
|
+
}
|
|
3715
|
+
|
|
3716
|
+
/**
|
|
3717
|
+
* The facilitator NAMED a reason proving it executed nothing.
|
|
3718
|
+
*
|
|
3719
|
+
* False for `forward_failed` and for every unattributed 5xx: "something
|
|
3720
|
+
* answered" is not evidence that nothing ran. On `/register`, replaying when
|
|
3721
|
+
* this is false is the sequence that minted five duplicate agents.
|
|
3722
|
+
*/
|
|
3723
|
+
get safeToReplay(): boolean {
|
|
3724
|
+
return this.status === 429 || (this.status === 503 && isReplayableLeaseReason(this.reason));
|
|
3725
|
+
}
|
|
3726
|
+
|
|
3727
|
+
/** Seconds to wait before retrying, clamped. Absent when not retryable. */
|
|
3728
|
+
get retryAfterSeconds(): number | undefined {
|
|
3729
|
+
if (!this.retryable) return undefined;
|
|
3730
|
+
return this.retryAfterHint ?? DEFAULT_RETRY_AFTER_SECONDS;
|
|
3506
3731
|
}
|
|
3507
3732
|
}
|
|
3508
3733
|
|
|
@@ -3581,7 +3806,7 @@ export interface RegisterAgentRequest {
|
|
|
3581
3806
|
/**
|
|
3582
3807
|
* Response from POST /register
|
|
3583
3808
|
*/
|
|
3584
|
-
export interface RegisterAgentResponse {
|
|
3809
|
+
export interface RegisterAgentResponse extends FacilitatorFailureFields {
|
|
3585
3810
|
/** Whether registration succeeded */
|
|
3586
3811
|
success: boolean;
|
|
3587
3812
|
/** The newly assigned agent ID (EVM: tokenId number, Solana: base58 pubkey string) */
|
|
@@ -3744,6 +3969,12 @@ export interface Erc8004ClientOptions {
|
|
|
3744
3969
|
baseUrl?: string;
|
|
3745
3970
|
/** Request timeout in milliseconds (default: 30000) */
|
|
3746
3971
|
timeout?: number;
|
|
3972
|
+
/**
|
|
3973
|
+
* Extra attempts after the first, spent only on a refusal the facilitator
|
|
3974
|
+
* proved it did not execute. Default 2; `0` disables. An ambiguous
|
|
3975
|
+
* `forward_failed` is never replayed at any setting.
|
|
3976
|
+
*/
|
|
3977
|
+
retries?: number;
|
|
3747
3978
|
}
|
|
3748
3979
|
|
|
3749
3980
|
/**
|
|
@@ -3786,10 +4017,44 @@ export interface Erc8004ClientOptions {
|
|
|
3786
4017
|
export class Erc8004Client {
|
|
3787
4018
|
private readonly baseUrl: string;
|
|
3788
4019
|
private readonly timeout: number;
|
|
4020
|
+
private readonly retries: number | undefined;
|
|
3789
4021
|
|
|
3790
4022
|
constructor(options: Erc8004ClientOptions = {}) {
|
|
3791
4023
|
this.baseUrl = options.baseUrl || 'https://facilitator.ultravioletadao.xyz';
|
|
3792
4024
|
this.timeout = options.timeout || 30000;
|
|
4025
|
+
this.retries = options.retries;
|
|
4026
|
+
}
|
|
4027
|
+
|
|
4028
|
+
/**
|
|
4029
|
+
* POST a write route, keeping a refusal readable.
|
|
4030
|
+
*
|
|
4031
|
+
* Every ERC-8004 write goes through the facilitator's EVM writer lease, so
|
|
4032
|
+
* every one of them can answer `503` + `reason`. Flattened to a string, those
|
|
4033
|
+
* are indistinguishable from "the registry rejected your feedback" — and on
|
|
4034
|
+
* `/register` the wrong reading re-POSTs a mint that may already have landed,
|
|
4035
|
+
* which is precisely how five duplicate agents were once created.
|
|
4036
|
+
*
|
|
4037
|
+
* A refusal the facilitator proved it did not execute is replayed
|
|
4038
|
+
* automatically (`safeToReplay`); `forward_failed` never is.
|
|
4039
|
+
*/
|
|
4040
|
+
private async writeJson(
|
|
4041
|
+
url: string,
|
|
4042
|
+
body: unknown,
|
|
4043
|
+
extraHeaders: Record<string, string> = {},
|
|
4044
|
+
): Promise<{ response: Response; error?: FacilitatorErrorInfo }> {
|
|
4045
|
+
return facilitatorFetch(
|
|
4046
|
+
url,
|
|
4047
|
+
{
|
|
4048
|
+
method: 'POST',
|
|
4049
|
+
headers: {
|
|
4050
|
+
'Content-Type': 'application/json',
|
|
4051
|
+
Accept: 'application/json',
|
|
4052
|
+
...extraHeaders,
|
|
4053
|
+
},
|
|
4054
|
+
body: JSON.stringify(body),
|
|
4055
|
+
},
|
|
4056
|
+
{ timeoutMs: this.timeout, retries: this.retries },
|
|
4057
|
+
);
|
|
3793
4058
|
}
|
|
3794
4059
|
|
|
3795
4060
|
/**
|
|
@@ -3847,33 +4112,28 @@ export class Erc8004Client {
|
|
|
3847
4112
|
const controller = new AbortController();
|
|
3848
4113
|
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
3849
4114
|
|
|
3850
|
-
|
|
3851
|
-
|
|
3852
|
-
|
|
3853
|
-
|
|
3854
|
-
|
|
3855
|
-
});
|
|
3856
|
-
|
|
3857
|
-
clearTimeout(timeoutId);
|
|
3858
|
-
|
|
3859
|
-
if (!response.ok) {
|
|
3860
|
-
const errorText = await response.text();
|
|
3861
|
-
// 404 and 503 are different answers: "owns nothing" versus "could not
|
|
3862
|
-
// find out". Reading the status out of a message string is how they get
|
|
3863
|
-
// collapsed, and collapsing them mints a duplicate agent for an owner
|
|
3864
|
-
// who already has one. Carry the status as a field.
|
|
3865
|
-
throw new Erc8004LookupError(
|
|
3866
|
-
`ERC-8004 API error: ${response.status} - ${errorText}`,
|
|
3867
|
-
response.status,
|
|
3868
|
-
errorText,
|
|
3869
|
-
);
|
|
3870
|
-
}
|
|
4115
|
+
const response = await fetch(url, {
|
|
4116
|
+
method: 'GET',
|
|
4117
|
+
headers: { Accept: 'application/json' },
|
|
4118
|
+
signal: controller.signal,
|
|
4119
|
+
}).finally(() => clearTimeout(timeoutId));
|
|
3871
4120
|
|
|
3872
|
-
|
|
3873
|
-
|
|
3874
|
-
|
|
3875
|
-
|
|
4121
|
+
if (!response.ok) {
|
|
4122
|
+
// 404 and 503 are different answers: "owns nothing" versus "could not
|
|
4123
|
+
// find out". Reading the status out of a message string is how they get
|
|
4124
|
+
// collapsed, and collapsing them mints a duplicate agent for an owner
|
|
4125
|
+
// who already has one. Carry the status, the reason and the wait as
|
|
4126
|
+
// fields.
|
|
4127
|
+
const info = await readFacilitatorError(response);
|
|
4128
|
+
throw new Erc8004LookupError(
|
|
4129
|
+
`ERC-8004 API error: ${info.status} - ${info.body}`,
|
|
4130
|
+
info.status,
|
|
4131
|
+
info.body,
|
|
4132
|
+
info.retryAfterSeconds,
|
|
4133
|
+
);
|
|
3876
4134
|
}
|
|
4135
|
+
|
|
4136
|
+
return await response.json();
|
|
3877
4137
|
}
|
|
3878
4138
|
|
|
3879
4139
|
/**
|
|
@@ -4007,38 +4267,32 @@ export class Erc8004Client {
|
|
|
4007
4267
|
async submitFeedback(request: FeedbackRequest): Promise<FeedbackResponse> {
|
|
4008
4268
|
const url = `${this.baseUrl}/feedback`;
|
|
4009
4269
|
|
|
4010
|
-
const controller = new AbortController();
|
|
4011
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
4012
|
-
|
|
4013
4270
|
try {
|
|
4014
|
-
const response = await
|
|
4015
|
-
|
|
4016
|
-
|
|
4017
|
-
'Content-Type': 'application/json',
|
|
4018
|
-
'Accept': 'application/json',
|
|
4019
|
-
},
|
|
4020
|
-
body: JSON.stringify({ ...request, network: wireNetwork(request.network) }),
|
|
4021
|
-
signal: controller.signal,
|
|
4271
|
+
const { response, error } = await this.writeJson(url, {
|
|
4272
|
+
...request,
|
|
4273
|
+
network: wireNetwork(request.network),
|
|
4022
4274
|
});
|
|
4023
4275
|
|
|
4024
|
-
|
|
4025
|
-
|
|
4026
|
-
if (!response.ok) {
|
|
4027
|
-
const errorText = await response.text();
|
|
4276
|
+
if (error) {
|
|
4028
4277
|
return {
|
|
4029
4278
|
success: false,
|
|
4030
|
-
error:
|
|
4279
|
+
error: error.error,
|
|
4031
4280
|
network: request.network,
|
|
4281
|
+
...failureFields(error),
|
|
4032
4282
|
};
|
|
4033
4283
|
}
|
|
4034
4284
|
|
|
4035
4285
|
return await response.json();
|
|
4036
4286
|
} catch (error) {
|
|
4037
|
-
|
|
4287
|
+
// Timeout or connection failure: the write may already be on-chain.
|
|
4288
|
+
// Retryable, never replayable -- reconcile before resending.
|
|
4038
4289
|
return {
|
|
4039
4290
|
success: false,
|
|
4040
4291
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
4041
4292
|
network: request.network,
|
|
4293
|
+
retryable: true,
|
|
4294
|
+
safeToReplay: false,
|
|
4295
|
+
retryAfterSeconds: DEFAULT_RETRY_AFTER_SECONDS,
|
|
4042
4296
|
};
|
|
4043
4297
|
}
|
|
4044
4298
|
}
|
|
@@ -4159,38 +4413,32 @@ export class Erc8004Client {
|
|
|
4159
4413
|
): Promise<FeedbackResponse> {
|
|
4160
4414
|
const url = `${this.baseUrl}/feedback/evm/submit`;
|
|
4161
4415
|
|
|
4162
|
-
const controller = new AbortController();
|
|
4163
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
4164
|
-
|
|
4165
4416
|
try {
|
|
4166
|
-
const response = await
|
|
4167
|
-
|
|
4168
|
-
|
|
4169
|
-
'Content-Type': 'application/json',
|
|
4170
|
-
'Accept': 'application/json',
|
|
4171
|
-
},
|
|
4172
|
-
body: JSON.stringify({ ...request, network: wireNetwork(request.network) }),
|
|
4173
|
-
signal: controller.signal,
|
|
4417
|
+
const { response, error } = await this.writeJson(url, {
|
|
4418
|
+
...request,
|
|
4419
|
+
network: wireNetwork(request.network),
|
|
4174
4420
|
});
|
|
4175
4421
|
|
|
4176
|
-
|
|
4177
|
-
|
|
4178
|
-
if (!response.ok) {
|
|
4179
|
-
const errorText = await response.text();
|
|
4422
|
+
if (error) {
|
|
4180
4423
|
return {
|
|
4181
4424
|
success: false,
|
|
4182
|
-
error:
|
|
4425
|
+
error: error.error,
|
|
4183
4426
|
network: request.network,
|
|
4427
|
+
...failureFields(error),
|
|
4184
4428
|
};
|
|
4185
4429
|
}
|
|
4186
4430
|
|
|
4187
4431
|
return await response.json();
|
|
4188
4432
|
} catch (error) {
|
|
4189
|
-
|
|
4433
|
+
// Timeout or connection failure: the write may already be on-chain.
|
|
4434
|
+
// Retryable, never replayable -- reconcile before resending.
|
|
4190
4435
|
return {
|
|
4191
4436
|
success: false,
|
|
4192
4437
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
4193
4438
|
network: request.network,
|
|
4439
|
+
retryable: true,
|
|
4440
|
+
safeToReplay: false,
|
|
4441
|
+
retryAfterSeconds: DEFAULT_RETRY_AFTER_SECONDS,
|
|
4194
4442
|
};
|
|
4195
4443
|
}
|
|
4196
4444
|
}
|
|
@@ -4213,9 +4461,6 @@ export class Erc8004Client {
|
|
|
4213
4461
|
): Promise<FeedbackResponse> {
|
|
4214
4462
|
const url = `${this.baseUrl}/feedback/revoke`;
|
|
4215
4463
|
|
|
4216
|
-
const controller = new AbortController();
|
|
4217
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
4218
|
-
|
|
4219
4464
|
const payload: Record<string, unknown> = {
|
|
4220
4465
|
x402Version: 1,
|
|
4221
4466
|
network: wireNetwork(network),
|
|
@@ -4232,34 +4477,26 @@ export class Erc8004Client {
|
|
|
4232
4477
|
}
|
|
4233
4478
|
|
|
4234
4479
|
try {
|
|
4235
|
-
const response = await
|
|
4236
|
-
method: 'POST',
|
|
4237
|
-
headers: {
|
|
4238
|
-
'Content-Type': 'application/json',
|
|
4239
|
-
'Accept': 'application/json',
|
|
4240
|
-
},
|
|
4241
|
-
body: JSON.stringify(payload),
|
|
4242
|
-
signal: controller.signal,
|
|
4243
|
-
});
|
|
4244
|
-
|
|
4245
|
-
clearTimeout(timeoutId);
|
|
4480
|
+
const { response, error } = await this.writeJson(url, payload);
|
|
4246
4481
|
|
|
4247
|
-
if (
|
|
4248
|
-
const errorText = await response.text();
|
|
4482
|
+
if (error) {
|
|
4249
4483
|
return {
|
|
4250
4484
|
success: false,
|
|
4251
|
-
error:
|
|
4485
|
+
error: error.error,
|
|
4252
4486
|
network,
|
|
4487
|
+
...failureFields(error),
|
|
4253
4488
|
};
|
|
4254
4489
|
}
|
|
4255
4490
|
|
|
4256
4491
|
return await response.json();
|
|
4257
4492
|
} catch (error) {
|
|
4258
|
-
clearTimeout(timeoutId);
|
|
4259
4493
|
return {
|
|
4260
4494
|
success: false,
|
|
4261
4495
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
4262
4496
|
network,
|
|
4497
|
+
retryable: true,
|
|
4498
|
+
safeToReplay: false,
|
|
4499
|
+
retryAfterSeconds: DEFAULT_RETRY_AFTER_SECONDS,
|
|
4263
4500
|
};
|
|
4264
4501
|
}
|
|
4265
4502
|
}
|
|
@@ -4368,24 +4605,23 @@ export class Erc8004Client {
|
|
|
4368
4605
|
|
|
4369
4606
|
/** Shared POST for the relay routes: a refusal is data, never a throw. */
|
|
4370
4607
|
private async postRelay<T>(path: string, request: { network: Erc8004Network }, onError: T): Promise<T> {
|
|
4371
|
-
const controller = new AbortController();
|
|
4372
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
4373
4608
|
try {
|
|
4374
|
-
const response = await
|
|
4375
|
-
|
|
4376
|
-
|
|
4377
|
-
body: JSON.stringify({ ...request, network: wireNetwork(request.network) }),
|
|
4378
|
-
signal: controller.signal,
|
|
4609
|
+
const { response, error } = await this.writeJson(`${this.baseUrl}${path}`, {
|
|
4610
|
+
...request,
|
|
4611
|
+
network: wireNetwork(request.network),
|
|
4379
4612
|
});
|
|
4380
|
-
|
|
4381
|
-
|
|
4382
|
-
const errorText = await response.text();
|
|
4383
|
-
return { ...onError, error: `Facilitator error: ${response.status} - ${errorText}` };
|
|
4613
|
+
if (error) {
|
|
4614
|
+
return { ...onError, error: error.error, ...failureFields(error) };
|
|
4384
4615
|
}
|
|
4385
4616
|
return await response.json();
|
|
4386
4617
|
} catch (error) {
|
|
4387
|
-
|
|
4388
|
-
|
|
4618
|
+
return {
|
|
4619
|
+
...onError,
|
|
4620
|
+
error: error instanceof Error ? error.message : 'Unknown error',
|
|
4621
|
+
retryable: true,
|
|
4622
|
+
safeToReplay: false,
|
|
4623
|
+
retryAfterSeconds: DEFAULT_RETRY_AFTER_SECONDS,
|
|
4624
|
+
};
|
|
4389
4625
|
}
|
|
4390
4626
|
}
|
|
4391
4627
|
|
|
@@ -4430,9 +4666,6 @@ export class Erc8004Client {
|
|
|
4430
4666
|
): Promise<FeedbackResponse> {
|
|
4431
4667
|
const url = `${this.baseUrl}/feedback/response`;
|
|
4432
4668
|
|
|
4433
|
-
const controller = new AbortController();
|
|
4434
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
4435
|
-
|
|
4436
4669
|
const payload: Record<string, unknown> = {
|
|
4437
4670
|
x402Version: 1,
|
|
4438
4671
|
network: wireNetwork(network),
|
|
@@ -4448,34 +4681,26 @@ export class Erc8004Client {
|
|
|
4448
4681
|
}
|
|
4449
4682
|
|
|
4450
4683
|
try {
|
|
4451
|
-
const fetchResponse = await
|
|
4452
|
-
method: 'POST',
|
|
4453
|
-
headers: {
|
|
4454
|
-
'Content-Type': 'application/json',
|
|
4455
|
-
'Accept': 'application/json',
|
|
4456
|
-
},
|
|
4457
|
-
body: JSON.stringify(payload),
|
|
4458
|
-
signal: controller.signal,
|
|
4459
|
-
});
|
|
4684
|
+
const { response: fetchResponse, error } = await this.writeJson(url, payload);
|
|
4460
4685
|
|
|
4461
|
-
|
|
4462
|
-
|
|
4463
|
-
if (!fetchResponse.ok) {
|
|
4464
|
-
const errorText = await fetchResponse.text();
|
|
4686
|
+
if (error) {
|
|
4465
4687
|
return {
|
|
4466
4688
|
success: false,
|
|
4467
|
-
error:
|
|
4689
|
+
error: error.error,
|
|
4468
4690
|
network,
|
|
4691
|
+
...failureFields(error),
|
|
4469
4692
|
};
|
|
4470
4693
|
}
|
|
4471
4694
|
|
|
4472
4695
|
return await fetchResponse.json();
|
|
4473
4696
|
} catch (error) {
|
|
4474
|
-
clearTimeout(timeoutId);
|
|
4475
4697
|
return {
|
|
4476
4698
|
success: false,
|
|
4477
4699
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
4478
4700
|
network,
|
|
4701
|
+
retryable: true,
|
|
4702
|
+
safeToReplay: false,
|
|
4703
|
+
retryAfterSeconds: DEFAULT_RETRY_AFTER_SECONDS,
|
|
4479
4704
|
};
|
|
4480
4705
|
}
|
|
4481
4706
|
}
|
|
@@ -4529,24 +4754,13 @@ export class Erc8004Client {
|
|
|
4529
4754
|
|
|
4530
4755
|
const url = `${this.baseUrl}/register`;
|
|
4531
4756
|
|
|
4532
|
-
const controller = new AbortController();
|
|
4533
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
4534
|
-
|
|
4535
4757
|
try {
|
|
4536
|
-
const response = await
|
|
4537
|
-
|
|
4538
|
-
|
|
4539
|
-
'Content-Type': 'application/json',
|
|
4540
|
-
'Accept': 'application/json',
|
|
4541
|
-
},
|
|
4542
|
-
body: JSON.stringify({ ...request, network: wireNetwork(request.network) }),
|
|
4543
|
-
signal: controller.signal,
|
|
4758
|
+
const { response, error } = await this.writeJson(url, {
|
|
4759
|
+
...request,
|
|
4760
|
+
network: wireNetwork(request.network),
|
|
4544
4761
|
});
|
|
4545
4762
|
|
|
4546
|
-
|
|
4547
|
-
|
|
4548
|
-
if (!response.ok) {
|
|
4549
|
-
const errorText = await response.text();
|
|
4763
|
+
if (error) {
|
|
4550
4764
|
// The facilitator answers 4xx with a structured RegisterAgentResponse,
|
|
4551
4765
|
// and on 409 - a registration for this agent is ALREADY IN FLIGHT -
|
|
4552
4766
|
// that body carries the agent id and tx of the run already underway,
|
|
@@ -4556,14 +4770,15 @@ export class Erc8004Client {
|
|
|
4556
4770
|
// a caller resolve instead of re-POSTing, and re-POSTing a mint is
|
|
4557
4771
|
// exactly how duplicate agents get created. Keep the body.
|
|
4558
4772
|
try {
|
|
4559
|
-
const parsed = JSON.parse(
|
|
4773
|
+
const parsed = JSON.parse(error.body) as RegisterAgentResponse;
|
|
4560
4774
|
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
4561
4775
|
return {
|
|
4562
4776
|
...parsed,
|
|
4563
|
-
// Never let a
|
|
4777
|
+
// Never let a non-2xx body claim success, whatever it says.
|
|
4564
4778
|
success: false,
|
|
4565
|
-
error: parsed.error ?? `Facilitator error: ${
|
|
4779
|
+
error: parsed.error ?? `Facilitator error: ${error.status}`,
|
|
4566
4780
|
network: parsed.network ?? request.network,
|
|
4781
|
+
...failureFields(error),
|
|
4567
4782
|
};
|
|
4568
4783
|
}
|
|
4569
4784
|
} catch {
|
|
@@ -4571,18 +4786,26 @@ export class Erc8004Client {
|
|
|
4571
4786
|
}
|
|
4572
4787
|
return {
|
|
4573
4788
|
success: false,
|
|
4574
|
-
error:
|
|
4789
|
+
error: error.error,
|
|
4575
4790
|
network: request.network,
|
|
4791
|
+
...failureFields(error),
|
|
4576
4792
|
};
|
|
4577
4793
|
}
|
|
4578
4794
|
|
|
4579
4795
|
return await response.json();
|
|
4580
4796
|
} catch (error) {
|
|
4581
|
-
|
|
4797
|
+
// A MINT that timed out is the single most dangerous ambiguity in this
|
|
4798
|
+
// SDK: the transaction may be mining right now. `safeToReplay: false`
|
|
4799
|
+
// says so out loud. Resolve with
|
|
4800
|
+
// `GET /identity/{network}/owner/{recipient}` -- honouring its 404-vs-503
|
|
4801
|
+
// distinction -- or with `getRegisterStatus`, never by re-POSTing.
|
|
4582
4802
|
return {
|
|
4583
4803
|
success: false,
|
|
4584
4804
|
error: error instanceof Error ? error.message : 'Unknown error',
|
|
4585
4805
|
network: request.network,
|
|
4806
|
+
retryable: true,
|
|
4807
|
+
safeToReplay: false,
|
|
4808
|
+
retryAfterSeconds: DEFAULT_RETRY_AFTER_SECONDS,
|
|
4586
4809
|
};
|
|
4587
4810
|
}
|
|
4588
4811
|
}
|
|
@@ -4602,37 +4825,26 @@ export class Erc8004Client {
|
|
|
4602
4825
|
async registerAgentAsync(request: RegisterAgentRequest): Promise<RegisterJobResponse> {
|
|
4603
4826
|
const url = `${this.baseUrl}/register`;
|
|
4604
4827
|
|
|
4605
|
-
|
|
4606
|
-
|
|
4607
|
-
|
|
4608
|
-
|
|
4609
|
-
|
|
4610
|
-
|
|
4611
|
-
|
|
4612
|
-
|
|
4613
|
-
|
|
4614
|
-
'Prefer': 'respond-async',
|
|
4615
|
-
},
|
|
4616
|
-
body: JSON.stringify({ ...request, network: wireNetwork(request.network) }),
|
|
4617
|
-
signal: controller.signal,
|
|
4618
|
-
});
|
|
4619
|
-
|
|
4620
|
-
clearTimeout(timeoutId);
|
|
4621
|
-
|
|
4622
|
-
if (!response.ok) {
|
|
4623
|
-
const errorText = await response.text();
|
|
4624
|
-
throw new Erc8004LookupError(
|
|
4625
|
-
`ERC-8004 API error: ${response.status} - ${errorText}`,
|
|
4626
|
-
response.status,
|
|
4627
|
-
errorText,
|
|
4628
|
-
);
|
|
4629
|
-
}
|
|
4828
|
+
// A 503 here is the SAFE half of the register story: the job was never
|
|
4829
|
+
// created, so a replay creates one job, not two. `writeJson` replays only
|
|
4830
|
+
// what the facilitator proved it did not execute, and never
|
|
4831
|
+
// `forward_failed`.
|
|
4832
|
+
const { response, error } = await this.writeJson(
|
|
4833
|
+
url,
|
|
4834
|
+
{ ...request, network: wireNetwork(request.network) },
|
|
4835
|
+
{ Prefer: 'respond-async' },
|
|
4836
|
+
);
|
|
4630
4837
|
|
|
4631
|
-
|
|
4632
|
-
|
|
4633
|
-
|
|
4634
|
-
|
|
4838
|
+
if (error) {
|
|
4839
|
+
throw new Erc8004LookupError(
|
|
4840
|
+
`ERC-8004 API error: ${error.status} - ${error.body}`,
|
|
4841
|
+
error.status,
|
|
4842
|
+
error.body,
|
|
4843
|
+
error.retryAfterSeconds,
|
|
4844
|
+
);
|
|
4635
4845
|
}
|
|
4846
|
+
|
|
4847
|
+
return await response.json();
|
|
4636
4848
|
}
|
|
4637
4849
|
|
|
4638
4850
|
/**
|
|
@@ -4647,29 +4859,23 @@ export class Erc8004Client {
|
|
|
4647
4859
|
const controller = new AbortController();
|
|
4648
4860
|
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
4649
4861
|
|
|
4650
|
-
|
|
4651
|
-
|
|
4652
|
-
|
|
4653
|
-
|
|
4654
|
-
|
|
4655
|
-
});
|
|
4656
|
-
|
|
4657
|
-
clearTimeout(timeoutId);
|
|
4658
|
-
|
|
4659
|
-
if (!response.ok) {
|
|
4660
|
-
const errorText = await response.text();
|
|
4661
|
-
throw new Erc8004LookupError(
|
|
4662
|
-
`ERC-8004 API error: ${response.status} - ${errorText}`,
|
|
4663
|
-
response.status,
|
|
4664
|
-
errorText,
|
|
4665
|
-
);
|
|
4666
|
-
}
|
|
4862
|
+
const response = await fetch(url, {
|
|
4863
|
+
method: 'GET',
|
|
4864
|
+
headers: { Accept: 'application/json' },
|
|
4865
|
+
signal: controller.signal,
|
|
4866
|
+
}).finally(() => clearTimeout(timeoutId));
|
|
4667
4867
|
|
|
4668
|
-
|
|
4669
|
-
|
|
4670
|
-
|
|
4671
|
-
|
|
4868
|
+
if (!response.ok) {
|
|
4869
|
+
const info = await readFacilitatorError(response);
|
|
4870
|
+
throw new Erc8004LookupError(
|
|
4871
|
+
`ERC-8004 API error: ${info.status} - ${info.body}`,
|
|
4872
|
+
info.status,
|
|
4873
|
+
info.body,
|
|
4874
|
+
info.retryAfterSeconds,
|
|
4875
|
+
);
|
|
4672
4876
|
}
|
|
4877
|
+
|
|
4878
|
+
return await response.json();
|
|
4673
4879
|
}
|
|
4674
4880
|
|
|
4675
4881
|
/**
|
|
@@ -5102,10 +5308,19 @@ export interface AdvancedAuthorizationResult {
|
|
|
5102
5308
|
/**
|
|
5103
5309
|
* Result of an on-chain transaction (release, refund, charge).
|
|
5104
5310
|
*/
|
|
5105
|
-
export interface AdvancedTransactionResult {
|
|
5311
|
+
export interface AdvancedTransactionResult extends FacilitatorFailureFields {
|
|
5106
5312
|
success: boolean;
|
|
5107
5313
|
transactionHash?: string;
|
|
5108
5314
|
gasUsed?: number;
|
|
5315
|
+
/**
|
|
5316
|
+
* Why it failed.
|
|
5317
|
+
*
|
|
5318
|
+
* On the gasless (`*ViaFacilitator`) paths, check `retryable` first: a
|
|
5319
|
+
* facilitator that could not hand the write to its lease holder rejected
|
|
5320
|
+
* nothing on-chain, and the escrow is exactly as it was. Reporting that as a
|
|
5321
|
+
* failed refund is how funds get written off while they are still sitting in
|
|
5322
|
+
* escrow, recoverable.
|
|
5323
|
+
*/
|
|
5109
5324
|
error?: string;
|
|
5110
5325
|
}
|
|
5111
5326
|
|
|
@@ -5199,6 +5414,11 @@ export interface AdvancedEscrowClientOptions {
|
|
|
5199
5414
|
* ```
|
|
5200
5415
|
*/
|
|
5201
5416
|
wallet?: import('../wallet').SigningWalletAdapter;
|
|
5417
|
+
/**
|
|
5418
|
+
* Extra attempts on the gasless facilitator paths when the facilitator proved
|
|
5419
|
+
* it executed nothing. Default 2; `0` disables.
|
|
5420
|
+
*/
|
|
5421
|
+
retries?: number;
|
|
5202
5422
|
}
|
|
5203
5423
|
|
|
5204
5424
|
/**
|
|
@@ -5276,6 +5496,7 @@ export class AdvancedEscrowClient {
|
|
|
5276
5496
|
private chainId: number;
|
|
5277
5497
|
private gasLimit: number;
|
|
5278
5498
|
private readonly timeout: number;
|
|
5499
|
+
private readonly retries: number | undefined;
|
|
5279
5500
|
private contracts: AdvancedEscrowContracts;
|
|
5280
5501
|
private signer: any; // ethers.Signer (legacy mode)
|
|
5281
5502
|
private walletAdapter: import('../wallet').SigningWalletAdapter | null; // OWS mode (v2.36.0+)
|
|
@@ -5311,6 +5532,7 @@ export class AdvancedEscrowClient {
|
|
|
5311
5532
|
this.chainId = options.chainId || 8453;
|
|
5312
5533
|
this.gasLimit = options.gasLimit || 300000;
|
|
5313
5534
|
this.timeout = options.timeout || ESCROW_TIMEOUT_MS[this.chainId] || DEFAULT_ESCROW_TIMEOUT_MS;
|
|
5535
|
+
this.retries = options.retries;
|
|
5314
5536
|
|
|
5315
5537
|
if (this.walletAdapter && !this.rpcUrl) {
|
|
5316
5538
|
throw new Error(
|
|
@@ -5366,10 +5588,17 @@ export class AdvancedEscrowClient {
|
|
|
5366
5588
|
const t = TIER_TIMINGS[tier];
|
|
5367
5589
|
// The release window must outlast the REVIEW, not just the tier. `micro`
|
|
5368
5590
|
// alone gives two hours; a buyer approving later gets
|
|
5369
|
-
// `AfterAuthorizationExpiry` on-chain — the release reverts
|
|
5370
|
-
// not paid
|
|
5371
|
-
//
|
|
5372
|
-
//
|
|
5591
|
+
// `AfterAuthorizationExpiry` on-chain — the release reverts and the worker
|
|
5592
|
+
// is not paid. Measured in production 2026-08-19: a release attempted 26.2
|
|
5593
|
+
// HOURS past expiry, 8 escrows stuck on one network in 24h.
|
|
5594
|
+
//
|
|
5595
|
+
// This comment used to add "and only the payer's `reclaim()` can move the
|
|
5596
|
+
// funds". That is FALSE and it is why those escrows were treated as lost:
|
|
5597
|
+
// `AuthCaptureEscrow.partialVoid` is `onlySender(operator)` — the operator
|
|
5598
|
+
// is the facilitator — pays the PAYER, and does not look at
|
|
5599
|
+
// `authorizationExpiry`. `refundViaFacilitator` reaches it with no gas and
|
|
5600
|
+
// no payer. Widening the window still matters: it is what pays the WORKER,
|
|
5601
|
+
// and a refund does not.
|
|
5373
5602
|
//
|
|
5374
5603
|
// buildEscrowPreAuth — the other escrow path in this same SDK — already
|
|
5375
5604
|
// floors both windows this way and says why. This path never got the memo,
|
|
@@ -5758,17 +5987,23 @@ export class AdvancedEscrowClient {
|
|
|
5758
5987
|
},
|
|
5759
5988
|
};
|
|
5760
5989
|
|
|
5761
|
-
const controller = new AbortController();
|
|
5762
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
5763
|
-
|
|
5764
5990
|
try {
|
|
5765
|
-
|
|
5766
|
-
|
|
5767
|
-
|
|
5768
|
-
|
|
5769
|
-
|
|
5770
|
-
|
|
5771
|
-
|
|
5991
|
+
// A 503 from the writer lease is NOT a refused release. The facilitator
|
|
5992
|
+
// never reached the chain, so the escrow still holds every token and
|
|
5993
|
+
// the same request is the right thing to send again. Reading it as a
|
|
5994
|
+
// refusal is how a recoverable escrow gets written off.
|
|
5995
|
+
const { response, error } = await facilitatorFetch(
|
|
5996
|
+
`${this.facilitatorUrl}/settle`,
|
|
5997
|
+
{
|
|
5998
|
+
method: 'POST',
|
|
5999
|
+
headers: { 'Content-Type': 'application/json' },
|
|
6000
|
+
body: JSON.stringify(payload),
|
|
6001
|
+
},
|
|
6002
|
+
{ timeoutMs: this.timeout, retries: this.retries },
|
|
6003
|
+
);
|
|
6004
|
+
if (error) {
|
|
6005
|
+
return { success: false, error: error.error, ...failureFields(error) };
|
|
6006
|
+
}
|
|
5772
6007
|
const result = await response.json();
|
|
5773
6008
|
|
|
5774
6009
|
if (result.success) {
|
|
@@ -5790,8 +6025,6 @@ export class AdvancedEscrowClient {
|
|
|
5790
6025
|
`Release refused with no reason (HTTP ${response.status}, body keys: ${Object.keys(result ?? {}).sort().join(', ') || 'none'})`,
|
|
5791
6026
|
};
|
|
5792
6027
|
} catch (fetchErr: any) {
|
|
5793
|
-
clearTimeout(timeoutId);
|
|
5794
|
-
|
|
5795
6028
|
// On timeout, check on-chain state as fallback
|
|
5796
6029
|
if (fetchErr.name === 'AbortError') {
|
|
5797
6030
|
try {
|
|
@@ -5810,23 +6043,53 @@ export class AdvancedEscrowClient {
|
|
|
5810
6043
|
}
|
|
5811
6044
|
|
|
5812
6045
|
/**
|
|
5813
|
-
* GASLESS REFUND:
|
|
6046
|
+
* GASLESS REFUND: return escrowed funds to the payer via the facilitator.
|
|
5814
6047
|
*
|
|
5815
|
-
*
|
|
5816
|
-
*
|
|
5817
|
-
*
|
|
6048
|
+
* Sends `action: "refundInEscrow"` to `POST /settle`; the facilitator's
|
|
6049
|
+
* PaymentOperator calls `AuthCaptureEscrow.partialVoid`.
|
|
6050
|
+
*
|
|
6051
|
+
* # This is how an EXPIRED escrow is recovered
|
|
6052
|
+
*
|
|
6053
|
+
* A widely repeated claim — including in this SDK's own comments until now —
|
|
6054
|
+
* says that once `authorizationExpiry` passes, only the payer's `reclaim()`
|
|
6055
|
+
* can move the funds. **That is false, and believing it has left real money
|
|
6056
|
+
* stranded.**
|
|
6057
|
+
*
|
|
6058
|
+
* Read the contract (`AuthCaptureEscrow.sol`):
|
|
6059
|
+
*
|
|
6060
|
+
* - `partialVoid` is `onlySender(paymentInfo.operator)` — the operator is the
|
|
6061
|
+
* FACILITATOR, not the payer — it sends the tokens **to the payer**, and it
|
|
6062
|
+
* **does not check `authorizationExpiry` at all**. It works before expiry
|
|
6063
|
+
* and after it, and the payer never has to appear.
|
|
6064
|
+
* - `reclaim` is `onlySender(paymentInfo.payer)` and only after expiry. It is
|
|
6065
|
+
* a payer's self-service escape hatch, which is why this facilitator does
|
|
6066
|
+
* not expose it — **not** the only way out.
|
|
6067
|
+
*
|
|
6068
|
+
* So a release that reverted with `AfterAuthorizationExpiry` is recoverable
|
|
6069
|
+
* from here, with no gas and no cooperation from the payer. Get the amount
|
|
6070
|
+
* from {@link queryEscrowState}'s `capturableAmount`.
|
|
6071
|
+
*
|
|
6072
|
+
* # A refusal that is not a refusal
|
|
6073
|
+
*
|
|
6074
|
+
* Check `retryable` before writing an escrow off. A `503` means the
|
|
6075
|
+
* facilitator never reached the chain — the escrow is untouched and the same
|
|
6076
|
+
* request should be sent again.
|
|
5818
6077
|
*
|
|
5819
6078
|
* @param paymentInfo - PaymentInfo from the authorize step
|
|
5820
|
-
* @param amount - Amount to refund in atomic units (defaults to maxAmount)
|
|
6079
|
+
* @param amount - Amount to refund in atomic units (defaults to maxAmount).
|
|
6080
|
+
* For a stuck escrow pass `capturableAmount` from {@link queryEscrowState}.
|
|
5821
6081
|
* @returns Transaction result from the facilitator
|
|
5822
6082
|
*
|
|
5823
|
-
* @example
|
|
6083
|
+
* @example Recovering an escrow whose release window already closed
|
|
5824
6084
|
* ```typescript
|
|
5825
|
-
* const
|
|
5826
|
-
*
|
|
5827
|
-
*
|
|
5828
|
-
*
|
|
5829
|
-
*
|
|
6085
|
+
* const state = await client.queryEscrowState(pi);
|
|
6086
|
+
* if (state.capturableAmount !== '0') {
|
|
6087
|
+
* // No payer needed, no gas, and expiry is irrelevant to partialVoid.
|
|
6088
|
+
* const result = await client.refundViaFacilitator(pi, state.capturableAmount);
|
|
6089
|
+
* if (!result.success && result.retryable) {
|
|
6090
|
+
* // No verdict was reached. The funds are still there; send it again.
|
|
6091
|
+
* }
|
|
6092
|
+
* }
|
|
5830
6093
|
* ```
|
|
5831
6094
|
*/
|
|
5832
6095
|
async refundViaFacilitator(
|
|
@@ -5868,17 +6131,23 @@ export class AdvancedEscrowClient {
|
|
|
5868
6131
|
},
|
|
5869
6132
|
};
|
|
5870
6133
|
|
|
5871
|
-
const controller = new AbortController();
|
|
5872
|
-
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
5873
|
-
|
|
5874
6134
|
try {
|
|
5875
|
-
|
|
5876
|
-
|
|
5877
|
-
|
|
5878
|
-
|
|
5879
|
-
|
|
5880
|
-
|
|
5881
|
-
|
|
6135
|
+
// The non-2xx branch used to be missing entirely: `response.json()` on
|
|
6136
|
+
// a 503 body yields `{error, reason}`, `result.success` is undefined,
|
|
6137
|
+
// and the refund was reported as failed. That is a recoverable escrow
|
|
6138
|
+
// declared lost on a facilitator hiccup.
|
|
6139
|
+
const { response, error } = await facilitatorFetch(
|
|
6140
|
+
`${this.facilitatorUrl}/settle`,
|
|
6141
|
+
{
|
|
6142
|
+
method: 'POST',
|
|
6143
|
+
headers: { 'Content-Type': 'application/json' },
|
|
6144
|
+
body: JSON.stringify(payload),
|
|
6145
|
+
},
|
|
6146
|
+
{ timeoutMs: this.timeout, retries: this.retries },
|
|
6147
|
+
);
|
|
6148
|
+
if (error) {
|
|
6149
|
+
return { success: false, error: error.error, ...failureFields(error) };
|
|
6150
|
+
}
|
|
5882
6151
|
const result = await response.json();
|
|
5883
6152
|
|
|
5884
6153
|
if (result.success) {
|
|
@@ -5887,10 +6156,14 @@ export class AdvancedEscrowClient {
|
|
|
5887
6156
|
transactionHash: result.transaction || result.transactionHash || result.transaction_hash,
|
|
5888
6157
|
};
|
|
5889
6158
|
}
|
|
5890
|
-
return {
|
|
6159
|
+
return {
|
|
6160
|
+
success: false,
|
|
6161
|
+
error:
|
|
6162
|
+
result.errorReason ||
|
|
6163
|
+
result.error ||
|
|
6164
|
+
`Refund refused with no reason (HTTP ${response.status}, body keys: ${Object.keys(result ?? {}).sort().join(', ') || 'none'})`,
|
|
6165
|
+
};
|
|
5891
6166
|
} catch (fetchErr: any) {
|
|
5892
|
-
clearTimeout(timeoutId);
|
|
5893
|
-
|
|
5894
6167
|
// On timeout, check on-chain state as fallback
|
|
5895
6168
|
if (fetchErr.name === 'AbortError') {
|
|
5896
6169
|
try {
|