@integraledger/terms 0.1.0 → 0.3.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 +135 -65
- package/dist/agreement.d.ts +21 -17
- package/dist/agreement.js +279 -85
- package/dist/channels.d.ts +35 -12
- package/dist/channels.js +152 -70
- package/dist/gate.d.ts +41 -18
- package/dist/gate.js +81 -47
- package/dist/index.d.ts +1 -1
- package/dist/pairings/batch.d.ts +2 -5
- package/dist/pairings/batch.js +3 -13
- package/dist/pairings/card.js +0 -2
- package/dist/pairings/common.d.ts +7 -1
- package/dist/pairings/common.js +17 -2
- package/dist/pairings/evm-x402.js +3 -3
- package/dist/pairings/lightning.js +1 -1
- package/dist/pairings/lnbtc-request.d.ts +1 -1
- package/dist/pairings/lnbtc-request.js +1 -1
- package/dist/pairings/mpp-charge-hedera.d.ts +7 -7
- package/dist/pairings/mpp-charge-hedera.js +1 -1
- package/dist/pairings/mpp-charge-stellar.js +1 -1
- package/dist/pairings/mpp-charge-tempo-memo.d.ts +1 -9
- package/dist/pairings/mpp-charge-tempo-memo.js +3 -7
- package/dist/pairings/mpp-charge-tempo-push.d.ts +0 -1
- package/dist/pairings/mpp-charge-tempo-push.js +2 -10
- package/dist/pairings/mpp-charge-xrpl.js +3 -3
- package/dist/pairings/mpp-rails.d.ts +1 -1
- package/dist/pairings/mpp-session-solana.js +2 -2
- package/dist/pairings/mpp-session-xrpl.js +3 -4
- package/dist/pairings/mpp-session.js +1 -1
- package/dist/pairings/mpp.d.ts +12 -16
- package/dist/pairings/mpp.js +32 -109
- package/dist/pairings/protocol-groups.d.ts +1 -1
- package/dist/pairings/x402-account-rails.d.ts +1 -1
- package/dist/pairings/x402-batch-settlement-eip155.js +1 -1
- package/dist/pairings/x402-batch-settlement-solana.d.ts +2 -0
- package/dist/pairings/x402-batch-settlement-solana.js +3 -2
- package/dist/pairings/x402-exact-casper.js +3 -3
- package/dist/pairings/x402-exact-ccd.js +3 -3
- package/dist/pairings/x402-exact-hedera.d.ts +4 -1
- package/dist/pairings/x402-exact-hedera.js +5 -2
- package/dist/pairings/x402-exact-solana.d.ts +4 -4
- package/dist/pairings/x402-exact-solana.js +3 -2
- package/dist/pairings/x402-exact-stellar.js +1 -1
- package/dist/pairings/x402-exact-sui.js +3 -1
- package/dist/pairings/x402-exact-tvm.js +10 -2
- package/dist/pairings/x402-exact-xrpl.js +2 -4
- package/dist/pairings/x402-rail.d.ts +1 -1
- package/dist/transact.d.ts +14 -9
- package/dist/transact.js +30 -24
- package/dist/types.d.ts +43 -18
- package/package.json +11 -12
package/dist/agreement.js
CHANGED
|
@@ -1,20 +1,26 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The agreement payment. `agree` asks the agreement URL for its
|
|
3
|
-
*
|
|
2
|
+
* The agreement payment, in two calls. Called without an approved payment, `agree` asks the agreement URL for its
|
|
3
|
+
* challenge and returns the agreement payment for the buyer's agent to approve, signing nothing: the challenge's first
|
|
4
|
+
* option, in document order, that the signer can pay with a pairing whose payment is itself a public proof of the ATR
|
|
5
|
+
* hash. Called with the payment the agent approved, it signs exactly that payment, sends it, and returns the resource's
|
|
4
6
|
* receipt once the payment is recorded. Nothing is signed when the challenge advertises another hash, and nothing is
|
|
5
|
-
* sent unless
|
|
6
|
-
* timeout, each paid request bounded by min(`maxTimeoutSeconds`, 120) + 60 + 10 seconds and the
|
|
7
|
-
*
|
|
8
|
-
* it was sent carries it as `moved`.
|
|
7
|
+
* sent unless the pairing reads the hash from the completed payment. Once sent, the same signed payment is sent again
|
|
8
|
+
* after each 202, 5xx or timeout, each paid request bounded by min(`maxTimeoutSeconds`, 120) + 60 + 10 seconds and the
|
|
9
|
+
* whole exchange by the paid option's `maxTimeoutSeconds` + 180 seconds; no second agreement payment is signed, and
|
|
10
|
+
* every decline after it was sent carries it as `moved`. A caller's `signal` ends the exchange at its next step.
|
|
9
11
|
*/
|
|
10
|
-
import { BINDINGS, hashEquals, isHttpsLink, isOtherSchemeLink,
|
|
11
|
-
import { pay, redirected } from "./gate.js";
|
|
12
|
+
import { BINDINGS, canonicalJson, fromBase64, hash, hashEquals, isHttpsLink, isOtherSchemeLink, parseJson, toBase64, } from "@integraledger/lcp";
|
|
13
|
+
import { hasAccount, IDENTITY, isIdentity, newRef, pay, pieceOf, redirected, trimHttpWhitespace } from "./gate.js";
|
|
14
|
+
import { isRefusal } from "./pairings/common.js";
|
|
12
15
|
const UNPAID_DEADLINE_MS = 10_000;
|
|
13
16
|
const EXCHANGE_CAP_S = 120;
|
|
14
17
|
const SETTLE_S = 60;
|
|
15
18
|
const VERIFY_S = 10;
|
|
16
19
|
const WINDOW_EXTRA_S = 180;
|
|
17
20
|
const MAX_ANSWER_BYTES = 65_536;
|
|
21
|
+
const MAX_OPTIONS = 32;
|
|
22
|
+
/** The answers whose content the exchange reads: a receipt, and a payment request. */
|
|
23
|
+
const READ_STATUSES = [200, 402];
|
|
18
24
|
const RETRY_DEFAULT_S = 2;
|
|
19
25
|
const RETRY_MIN_S = 1;
|
|
20
26
|
const DECIMAL = /^[0-9]{1,9}$/;
|
|
@@ -22,36 +28,47 @@ function declined(code, detail) {
|
|
|
22
28
|
return { decline: { code, detail } };
|
|
23
29
|
}
|
|
24
30
|
const failed = (detail) => declined("agreement-failed", detail);
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
31
|
+
/** Whether the caller's signal has ended the exchange. */
|
|
32
|
+
const isEnded = (signal) => signal?.aborted === true;
|
|
33
|
+
const ended = () => failed("The caller's signal ended the agreement exchange before the payment was sent.");
|
|
28
34
|
function isObject(v) {
|
|
29
35
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
30
36
|
}
|
|
31
|
-
/**
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
37
|
+
/**
|
|
38
|
+
* The JSON text `JSON.stringify` writes for the agreement payment, which the protocol package reads back: nested at
|
|
39
|
+
* most 64 levels. Undefined when it nests deeper, or `JSON.stringify` writes nothing for it or throws.
|
|
40
|
+
*/
|
|
41
|
+
function paymentText(signed) {
|
|
42
|
+
try {
|
|
43
|
+
const text = JSON.stringify(signed);
|
|
44
|
+
return text !== undefined && parseJson(text) !== undefined ? text : undefined;
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
38
49
|
}
|
|
39
|
-
/**
|
|
50
|
+
/**
|
|
51
|
+
* The JSON value a header of at most 64 KiB carries as padded standard base64 (RFC 4648 section 4) whose final
|
|
52
|
+
* character's unused bits are zero, of UTF-8 JSON text nested at most 64 levels deep whose leading byte order mark is
|
|
53
|
+
* kept as a character; undefined for anything else.
|
|
54
|
+
*/
|
|
40
55
|
function fromBase64Json(header) {
|
|
41
|
-
|
|
56
|
+
const bytes = header.length > MAX_ANSWER_BYTES ? null : fromBase64(header);
|
|
57
|
+
if (bytes === null)
|
|
42
58
|
return undefined;
|
|
43
59
|
try {
|
|
44
|
-
|
|
45
|
-
const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));
|
|
46
|
-
return parseJson(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
|
|
60
|
+
return parseJson(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes));
|
|
47
61
|
}
|
|
48
62
|
catch {
|
|
49
63
|
return undefined;
|
|
50
64
|
}
|
|
51
65
|
}
|
|
52
|
-
/**
|
|
66
|
+
/**
|
|
67
|
+
* `retry-after` as one to nine decimal digits of seconds, surrounding spaces, tabs, CRs and LFs aside, at least 1; 2
|
|
68
|
+
* for any other value or none.
|
|
69
|
+
*/
|
|
53
70
|
function retrySeconds(header) {
|
|
54
|
-
const v = header
|
|
71
|
+
const v = header === null ? undefined : trimHttpWhitespace(header);
|
|
55
72
|
if (v === undefined || !DECIMAL.test(v))
|
|
56
73
|
return RETRY_DEFAULT_S;
|
|
57
74
|
return Math.max(RETRY_MIN_S, Number(v));
|
|
@@ -60,17 +77,36 @@ function retrySeconds(header) {
|
|
|
60
77
|
function isServerError(status) {
|
|
61
78
|
return status >= 500 && status <= 599;
|
|
62
79
|
}
|
|
63
|
-
|
|
64
|
-
|
|
80
|
+
/** Waits `ms`, or less when the caller's signal ends the wait. */
|
|
81
|
+
function sleep(ms, signal) {
|
|
82
|
+
return new Promise((resolve) => {
|
|
83
|
+
const done = () => {
|
|
84
|
+
clearTimeout(timer);
|
|
85
|
+
signal?.removeEventListener("abort", done);
|
|
86
|
+
resolve();
|
|
87
|
+
};
|
|
88
|
+
const timer = setTimeout(done, ms);
|
|
89
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
90
|
+
if (signal?.aborted === true)
|
|
91
|
+
done();
|
|
92
|
+
});
|
|
65
93
|
}
|
|
66
94
|
/**
|
|
67
|
-
* One GET of the agreement URL, with no redirect followed and a deadline of `ms` over
|
|
68
|
-
*
|
|
95
|
+
* One GET of the agreement URL, asking for the identity coding, with no redirect followed and a deadline of `ms` over
|
|
96
|
+
* headers and body; the caller's signal ends it as the deadline does. A redirect is `agreement-failed`, and so is a 200
|
|
97
|
+
* or a 402, the answers the exchange reads, whose `Content-Encoding` names any coding. A 200 body is read as sent, up to
|
|
98
|
+
* 64 KiB; any other body is cancelled unread.
|
|
69
99
|
*/
|
|
70
|
-
async function get(fetch, url, signature, ms) {
|
|
100
|
+
async function get(fetch, url, signature, ms, signal) {
|
|
71
101
|
const controller = new AbortController();
|
|
72
102
|
const timer = setTimeout(() => controller.abort(new DOMException("The agreement request passed its deadline.", "TimeoutError")), ms);
|
|
103
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
104
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
105
|
+
if (signal?.aborted === true)
|
|
106
|
+
onAbort();
|
|
73
107
|
const deadline = new Promise((_, reject) => {
|
|
108
|
+
if (controller.signal.aborted)
|
|
109
|
+
reject(controller.signal.reason);
|
|
74
110
|
controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
|
|
75
111
|
});
|
|
76
112
|
deadline.catch(() => undefined);
|
|
@@ -78,9 +114,10 @@ async function get(fetch, url, signature, ms) {
|
|
|
78
114
|
let reader;
|
|
79
115
|
let whole = false;
|
|
80
116
|
try {
|
|
81
|
-
const
|
|
117
|
+
const headers = { ...IDENTITY };
|
|
82
118
|
if (signature !== undefined)
|
|
83
|
-
|
|
119
|
+
headers["PAYMENT-SIGNATURE"] = signature;
|
|
120
|
+
const init = { method: "GET", redirect: "manual", signal: controller.signal, headers };
|
|
84
121
|
const response = await Promise.race([fetch(url, init), deadline]);
|
|
85
122
|
body = response.body;
|
|
86
123
|
if (redirected(response))
|
|
@@ -91,9 +128,13 @@ async function get(fetch, url, signature, ms) {
|
|
|
91
128
|
retryAfter: response.headers.get("retry-after"),
|
|
92
129
|
body: null,
|
|
93
130
|
};
|
|
131
|
+
if (READ_STATUSES.includes(response.status) && !isIdentity(response.headers.get("content-encoding"))) {
|
|
132
|
+
return failed("The agreement URL served a content coding other than identity.");
|
|
133
|
+
}
|
|
94
134
|
if (response.status !== 200)
|
|
95
135
|
return answer;
|
|
96
|
-
const
|
|
136
|
+
const length = response.headers.get("content-length");
|
|
137
|
+
const declared = length === null ? undefined : trimHttpWhitespace(length);
|
|
97
138
|
if (declared !== undefined && /^[0-9]+$/.test(declared) && Number(declared) > MAX_ANSWER_BYTES) {
|
|
98
139
|
return failed("The agreement receipt is larger than 64 KiB.");
|
|
99
140
|
}
|
|
@@ -129,6 +170,7 @@ async function get(fetch, url, signature, ms) {
|
|
|
129
170
|
}
|
|
130
171
|
finally {
|
|
131
172
|
clearTimeout(timer);
|
|
173
|
+
signal?.removeEventListener("abort", onAbort);
|
|
132
174
|
if (!whole) {
|
|
133
175
|
cancel(reader ?? body);
|
|
134
176
|
controller.abort();
|
|
@@ -146,11 +188,14 @@ function cancel(s) {
|
|
|
146
188
|
// A body that cannot be cancelled is left to the fetch's own abort.
|
|
147
189
|
}
|
|
148
190
|
}
|
|
149
|
-
/**
|
|
191
|
+
/**
|
|
192
|
+
* The receipt a 200 carries, read as UTF-8 JSON text whose leading byte order mark is kept as a character, when it is
|
|
193
|
+
* the agreement receipt for `h`.
|
|
194
|
+
*/
|
|
150
195
|
function receiptOf(body, h) {
|
|
151
196
|
let parsed;
|
|
152
197
|
try {
|
|
153
|
-
parsed = parseJson(new TextDecoder("utf-8", { fatal: true }).decode(body ?? new Uint8Array(0)));
|
|
198
|
+
parsed = parseJson(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(body ?? new Uint8Array(0)));
|
|
154
199
|
}
|
|
155
200
|
catch {
|
|
156
201
|
return failed("The agreement URL answered 200 without a JSON receipt.");
|
|
@@ -170,23 +215,107 @@ function isPublicProof(binding) {
|
|
|
170
215
|
const pattern = binding.pattern;
|
|
171
216
|
return isObject(pattern) && pattern["publicProof"] === true;
|
|
172
217
|
}
|
|
173
|
-
/** The
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
218
|
+
/** The x402 pairings the gate pays, in the protocol package's order. */
|
|
219
|
+
const X402 = BINDINGS.filter((b) => String(b.id).startsWith("x402/") && pieceOf(b) !== undefined);
|
|
220
|
+
/**
|
|
221
|
+
* The option the agreement is paid with, by the main payment's rule: the options in document order, and the first one
|
|
222
|
+
* the signer can pay whose pairing's payment is itself a public proof. An option's pairing is the first x402 pairing,
|
|
223
|
+
* in the protocol package's order, whose read accepts the challenge holding only that option. An option whose
|
|
224
|
+
* `maxTimeoutSeconds` gives no deadline (`bounds`) is not payable, whichever pairing reads it. An `accepts` that is
|
|
225
|
+
* not a list, holds more than 32 entries or holds no object serves no option, and is declined `offer-unreadable` with
|
|
226
|
+
* the code the read gives the whole challenge (`unservedCode`). With `approved`, the challenge is checked whole in the
|
|
227
|
+
* same way and for a fault of its own (`challengeFault`), declined `offer-unreadable` with that code; then `approved`
|
|
228
|
+
* must be one of `accepts` (`isOffered`), else it is declined `offer-unreadable` with `x402/option-not-in-document`;
|
|
229
|
+
* and it is the one option read and chosen.
|
|
230
|
+
*/
|
|
231
|
+
async function select(required, account, inputs, approved) {
|
|
232
|
+
const accepts = required["accepts"];
|
|
233
|
+
if (!Array.isArray(accepts) || accepts.length > MAX_OPTIONS || !accepts.some((option) => isObject(option))) {
|
|
234
|
+
return declined("offer-unreadable", unservedCode(required));
|
|
235
|
+
}
|
|
236
|
+
if (approved !== undefined) {
|
|
237
|
+
const fault = challengeFault(required);
|
|
238
|
+
if (fault !== undefined)
|
|
239
|
+
return declined("offer-unreadable", fault);
|
|
240
|
+
if (!isOffered(accepts, approved))
|
|
241
|
+
return declined("offer-unreadable", "x402/option-not-in-document");
|
|
242
|
+
}
|
|
243
|
+
const now = Math.floor(Date.now() / 1000);
|
|
244
|
+
let unreadable;
|
|
245
|
+
let unpayable;
|
|
246
|
+
for (const option of approved === undefined ? accepts : [approved]) {
|
|
247
|
+
if (!isObject(option))
|
|
248
|
+
continue;
|
|
249
|
+
const only = { ...required, accepts: [option] };
|
|
250
|
+
let found;
|
|
251
|
+
for (const binding of X402) {
|
|
252
|
+
const read = binding.read(only);
|
|
253
|
+
if (!isRefusal(read)) {
|
|
254
|
+
found = { binding, read };
|
|
255
|
+
break;
|
|
256
|
+
}
|
|
257
|
+
if (read.code !== "x402/no-payable-option")
|
|
258
|
+
unreadable ??= read.code;
|
|
259
|
+
}
|
|
260
|
+
if (found === undefined || !isPublicProof(found.binding))
|
|
261
|
+
continue;
|
|
262
|
+
const limits = bounds(option);
|
|
263
|
+
if (limits === undefined)
|
|
264
|
+
continue;
|
|
265
|
+
const piece = pieceOf(found.binding);
|
|
266
|
+
const chosen = await piece.choose(found.read, account, inputs, now, newRef(), only);
|
|
267
|
+
if (isRefusal(chosen)) {
|
|
268
|
+
unpayable ??= chosen.code;
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
return { option: option, binding: found.binding, read: found.read, chosen, limits };
|
|
272
|
+
}
|
|
273
|
+
if (unpayable === undefined && unreadable !== undefined)
|
|
274
|
+
return declined("offer-unreadable", unreadable);
|
|
275
|
+
return declined("no-payable-option", unpayable ?? "x402/no-payable-option");
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* The code the x402 reads give a challenge that serves no option: the first refusal, in the protocol package's order,
|
|
279
|
+
* that is not `x402/no-payable-option` (a fault of the whole challenge, such as its version or legal context, or an
|
|
280
|
+
* `accepts` that is not a list of at most 32 entries), else `x402/no-payable-option`.
|
|
281
|
+
*/
|
|
282
|
+
function unservedCode(required) {
|
|
283
|
+
for (const binding of X402) {
|
|
284
|
+
const read = binding.read(required);
|
|
285
|
+
if (isRefusal(read) && read.code !== "x402/no-payable-option")
|
|
286
|
+
return read.code;
|
|
178
287
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
288
|
+
return "x402/no-payable-option";
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* The code the x402 reads give a challenge that none of them serves for a fault of its own beside its options, such as
|
|
292
|
+
* its version, legal context or agreement URL (`unservedCode`); undefined when a read serves it, or when none refuses it
|
|
293
|
+
* with a code other than `x402/no-payable-option`.
|
|
294
|
+
*/
|
|
295
|
+
function challengeFault(required) {
|
|
296
|
+
if (X402.some((binding) => !isRefusal(binding.read(required)))) {
|
|
297
|
+
return undefined;
|
|
186
298
|
}
|
|
187
|
-
|
|
299
|
+
const code = unservedCode(required);
|
|
300
|
+
return code === "x402/no-payable-option" ? undefined : code;
|
|
301
|
+
}
|
|
302
|
+
/**
|
|
303
|
+
* Whether `option` is one of `accepts`, by identity or by equal RFC 8785 form (`canonicalJson`), as the protocol
|
|
304
|
+
* package's build holds a chosen option to the document's: member order is not compared, and a number is its JSON
|
|
305
|
+
* value.
|
|
306
|
+
*/
|
|
307
|
+
function isOffered(accepts, option) {
|
|
308
|
+
return accepts.some((a) => {
|
|
309
|
+
if (a === option)
|
|
310
|
+
return true;
|
|
311
|
+
const text = canonicalJson(a);
|
|
312
|
+
return typeof text === "string" && text === canonicalJson(option);
|
|
313
|
+
});
|
|
188
314
|
}
|
|
189
|
-
/**
|
|
315
|
+
/**
|
|
316
|
+
* The paid request's deadline and the whole exchange's, in seconds, from the option's `maxTimeoutSeconds`: a JSON number
|
|
317
|
+
* with an integral value from 1 to 2^53 - 1.
|
|
318
|
+
*/
|
|
190
319
|
function bounds(option) {
|
|
191
320
|
const t = option.maxTimeoutSeconds;
|
|
192
321
|
if (typeof t !== "number" || !Number.isSafeInteger(t) || t <= 0)
|
|
@@ -194,59 +323,98 @@ function bounds(option) {
|
|
|
194
323
|
return { request: Math.min(t, EXCHANGE_CAP_S) + SETTLE_S + VERIFY_S, exchange: t + WINDOW_EXTRA_S };
|
|
195
324
|
}
|
|
196
325
|
/**
|
|
197
|
-
*
|
|
198
|
-
*
|
|
199
|
-
* whose offer named the URL, which a refused URL's detail carries with the protocol package's code.
|
|
326
|
+
* The option chosen from `required` for `h`, `approved` when given, with its bounds, once the challenge is found to
|
|
327
|
+
* advertise `h`.
|
|
200
328
|
*/
|
|
201
|
-
|
|
329
|
+
async function paying(required, h, account, inputs, approved) {
|
|
330
|
+
const selected = await select(required, account, inputs, approved);
|
|
331
|
+
if ("decline" in selected)
|
|
332
|
+
return selected;
|
|
333
|
+
if (!hashEquals(selected.read.h, h)) {
|
|
334
|
+
return declined("hash-mismatch", "The agreement challenge advertises another ATR hash.");
|
|
335
|
+
}
|
|
336
|
+
return { selected, limits: selected.limits };
|
|
337
|
+
}
|
|
338
|
+
/** Whether `v` has the form of an agreement payment: an agreement URL, an option and a payment request. */
|
|
339
|
+
function isAgreementPayment(v) {
|
|
340
|
+
return isObject(v) && typeof v["url"] === "string" && isObject(v["option"]) && isObject(v["required"]);
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Without `approved`: asks the agreement URL for its challenge and returns the agreement payment to approve, signing
|
|
344
|
+
* nothing, or the receipt where the agreement is already recorded. With `approved`: signs exactly that payment with
|
|
345
|
+
* `signer`, sends it to `url`, and returns the receipt once recorded; a payment whose challenge the protocol package's
|
|
346
|
+
* read refuses for a fault of its own (its version, legal context or agreement URL, or an `accepts` that is not a list
|
|
347
|
+
* of at most 32 entries holding an object) is declined as the unpaid request declines that challenge, and one whose
|
|
348
|
+
* option is not one of that challenge's `accepts`, by RFC 8785 form, is declined `offer-unreadable` with
|
|
349
|
+
* `x402/option-not-in-document`, each before any fetch or signer call.
|
|
350
|
+
* `bytes` are the ATR the gate compared, whose hash the agreement payment carries; `inputs` are the buyer's own chain
|
|
351
|
+
* values; `signal` ends the exchange. Options holding anything but `approved`, `inputs` and `signal`, a `signal` that
|
|
352
|
+
* is not an `AbortSignal`, an `approved` that is not of the agreement payment's form, `inputs` that is not an object,
|
|
353
|
+
* or a signer whose `account` is not a string, is declined `no-payable-option` with `x402/input-malformed` before any
|
|
354
|
+
* fetch or signer call. A `url` that is not an https URL is declined `link-not-https` with `x402/link-not-https` for an
|
|
355
|
+
* absolute URL of another scheme and `x402/legal-context-malformed` for any other value, before any fetch.
|
|
356
|
+
*/
|
|
357
|
+
export function agree(bytes, url, signer, fetch, options) {
|
|
358
|
+
return exchange(bytes, url, signer, fetch, options === undefined ? {} : options, undefined);
|
|
359
|
+
}
|
|
360
|
+
const OPTION_KEYS = ["approved", "inputs", "signal"];
|
|
361
|
+
/** Whether `agree`'s options are an object holding only `approved`, `inputs` and `signal`, the signal an `AbortSignal`. */
|
|
362
|
+
function optionsOk(options) {
|
|
363
|
+
if (!isObject(options) || !Object.keys(options).every((k) => OPTION_KEYS.includes(k)))
|
|
364
|
+
return false;
|
|
365
|
+
const signal = options["signal"];
|
|
366
|
+
return signal === undefined || signal instanceof AbortSignal;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* `agree`, where `ns` is the namespace of the pairing whose offer named the URL, x402 when none did: a refused URL
|
|
370
|
+
* declines `link-not-https`, its detail the protocol package's code in that namespace, `link-not-https` for an absolute
|
|
371
|
+
* URL of another scheme and `legal-context-malformed` for any other value.
|
|
372
|
+
*/
|
|
373
|
+
export async function exchange(bytes, url, signer, fetch, options, ns) {
|
|
202
374
|
if (!isHttpsLink(url)) {
|
|
203
375
|
const fault = isOtherSchemeLink(url) ? "link-not-https" : "legal-context-malformed";
|
|
204
|
-
return declined("link-not-https",
|
|
376
|
+
return declined("link-not-https", `${ns ?? "x402"}/${fault}`);
|
|
205
377
|
}
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
const
|
|
209
|
-
if (
|
|
210
|
-
return
|
|
211
|
-
if ("unanswered" in unpaid)
|
|
212
|
-
return failed("The agreement URL could not be reached.");
|
|
213
|
-
if (unpaid.status === 200)
|
|
214
|
-
return receiptOf(unpaid.body, h);
|
|
215
|
-
if (unpaid.status === 202) {
|
|
216
|
-
return declined("agreement-pending", "An agreement payment for this ATR is already settling.");
|
|
378
|
+
if (!optionsOk(options))
|
|
379
|
+
return declined("no-payable-option", `${ns ?? "x402"}/input-malformed`);
|
|
380
|
+
const { approved, signal, inputs = {} } = options;
|
|
381
|
+
if ((approved !== undefined && !isAgreementPayment(approved)) || !isObject(inputs) || !hasAccount(signer)) {
|
|
382
|
+
return declined("no-payable-option", `${ns ?? "x402"}/input-malformed`);
|
|
217
383
|
}
|
|
218
|
-
if (
|
|
219
|
-
return
|
|
220
|
-
const
|
|
221
|
-
if (
|
|
222
|
-
return
|
|
223
|
-
|
|
384
|
+
if (isEnded(signal))
|
|
385
|
+
return ended();
|
|
386
|
+
const h = await hash(bytes);
|
|
387
|
+
if (approved === undefined)
|
|
388
|
+
return offer(bytes, h, url, signer, fetch, inputs, signal);
|
|
389
|
+
if (approved.url !== url)
|
|
390
|
+
return failed("The approved agreement payment names another agreement URL.");
|
|
391
|
+
const found = await paying(approved.required, h, signer.account, inputs, approved.option);
|
|
224
392
|
if ("decline" in found)
|
|
225
393
|
return found;
|
|
226
|
-
const limits =
|
|
227
|
-
|
|
228
|
-
return declined("offer-unreadable", "x402/option-malformed");
|
|
229
|
-
const read = found.binding.read(required);
|
|
230
|
-
if (isRefusal(read))
|
|
231
|
-
return declined("offer-unreadable", read.code);
|
|
232
|
-
if (!hashEquals(read.h, h)) {
|
|
233
|
-
return declined("hash-mismatch", "The agreement challenge advertises another ATR hash.");
|
|
234
|
-
}
|
|
235
|
-
const paid = await pay(found.binding, read, required, signer, inputs, bytes);
|
|
394
|
+
const { selected, limits } = found;
|
|
395
|
+
const paid = await pay(selected.binding, selected.chosen, signer, bytes);
|
|
236
396
|
if ("decline" in paid)
|
|
237
397
|
return paid;
|
|
238
398
|
if (paid.signed === null)
|
|
239
399
|
return declined("offer-unreadable", "The agreement payment gave nothing to sign.");
|
|
400
|
+
if (isEnded(signal))
|
|
401
|
+
return ended();
|
|
240
402
|
const signed = paid.signed;
|
|
241
|
-
const
|
|
403
|
+
const text = paymentText(signed);
|
|
404
|
+
if (text === undefined)
|
|
405
|
+
return declined("signed-not-bound", "The agreement payment is not plain JSON.");
|
|
406
|
+
const payment = toBase64(new TextEncoder().encode(text));
|
|
242
407
|
const moved = { signed, bytes, h };
|
|
243
408
|
const keep = (d) => ({ ...d, moved });
|
|
409
|
+
const pending = (detail) => keep(declined("agreement-pending", detail));
|
|
244
410
|
const end = Date.now() + limits.exchange * 1000;
|
|
245
411
|
for (;;) {
|
|
246
412
|
const remaining = end - Date.now();
|
|
247
413
|
if (remaining <= 0)
|
|
248
|
-
return
|
|
249
|
-
const answer = await get(fetch, url, payment, Math.min(limits.request * 1000, remaining));
|
|
414
|
+
return pending("The agreement payment was sent and is not yet recorded.");
|
|
415
|
+
const answer = await get(fetch, url, payment, Math.min(limits.request * 1000, remaining), signal);
|
|
416
|
+
if (isEnded(signal))
|
|
417
|
+
return pending("The caller's signal ended the exchange after the agreement payment was sent.");
|
|
250
418
|
if ("decline" in answer)
|
|
251
419
|
return keep(answer);
|
|
252
420
|
let wait = RETRY_DEFAULT_S * 1000;
|
|
@@ -259,6 +427,32 @@ export async function agree(h, url, signer, fetch, held) {
|
|
|
259
427
|
return keep(failed(`The agreement URL answered status ${answer.status} to the payment.`));
|
|
260
428
|
wait = retrySeconds(answer.retryAfter) * 1000;
|
|
261
429
|
}
|
|
262
|
-
await sleep(Math.max(0, Math.min(wait, end - Date.now())));
|
|
430
|
+
await sleep(Math.max(0, Math.min(wait, end - Date.now())), signal);
|
|
431
|
+
if (isEnded(signal))
|
|
432
|
+
return pending("The caller's signal ended the exchange after the agreement payment was sent.");
|
|
263
433
|
}
|
|
264
434
|
}
|
|
435
|
+
/** The unpaid request: the agreement payment to approve, the receipt of an agreement already recorded, or a decline. */
|
|
436
|
+
async function offer(bytes, h, url, signer, fetch, inputs, signal) {
|
|
437
|
+
const unpaid = await get(fetch, url, undefined, UNPAID_DEADLINE_MS, signal);
|
|
438
|
+
if (isEnded(signal))
|
|
439
|
+
return ended();
|
|
440
|
+
if ("decline" in unpaid)
|
|
441
|
+
return unpaid;
|
|
442
|
+
if ("unanswered" in unpaid)
|
|
443
|
+
return failed("The agreement URL could not be reached.");
|
|
444
|
+
if (unpaid.status === 200)
|
|
445
|
+
return receiptOf(unpaid.body, h);
|
|
446
|
+
if (unpaid.status === 202) {
|
|
447
|
+
return declined("agreement-pending", "An agreement payment for this ATR is already settling.");
|
|
448
|
+
}
|
|
449
|
+
if (unpaid.status !== 402)
|
|
450
|
+
return failed(`The agreement URL answered status ${unpaid.status}.`);
|
|
451
|
+
const required = unpaid.paymentRequired === null ? undefined : fromBase64Json(unpaid.paymentRequired);
|
|
452
|
+
if (!isObject(required))
|
|
453
|
+
return failed("The agreement URL answered 402 without a readable PAYMENT-REQUIRED.");
|
|
454
|
+
const found = await paying(required, h, signer.account, inputs);
|
|
455
|
+
if ("decline" in found)
|
|
456
|
+
return found;
|
|
457
|
+
return { approve: { url, option: found.selected.option, required: required }, bytes, h };
|
|
458
|
+
}
|
package/dist/channels.d.ts
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* The buyer's channel steps. One ATR covers a whole channel: the gate compares it once, at the opening, and the caller
|
|
3
3
|
* keeps the result as a `ChannelHold`, the ATR's bytes together with the signed opening and the channel it names.
|
|
4
|
-
* `within` signs a later voucher only for a channel held this way,
|
|
5
|
-
* the
|
|
6
|
-
* MPP's sessions
|
|
7
|
-
*
|
|
4
|
+
* `within` signs a later voucher only for a channel held this way: the ATR's bytes, its hash and the channel come from
|
|
5
|
+
* the hold, and the amount from the new challenge. On x402's batch channels that challenge must advertise the held
|
|
6
|
+
* ATR's hash. On MPP's sessions a challenge that names another channel or another hash is declined, and one with no
|
|
7
|
+
* legal context is signed under the held hash. Both are served through the binding's `buildWithin`. `recordCharge`
|
|
8
|
+
* records the server's cumulative charge, bounded by what was signed.
|
|
8
9
|
*/
|
|
9
|
-
import { type AtrHash, type Json } from "@integraledger/lcp";
|
|
10
|
+
import { type AtrHash, type Json } from "@integraledger/lcp/core";
|
|
10
11
|
import { type Binding, type Declined, type Inputs, type Presented, type Signer } from "./types.js";
|
|
11
12
|
/** A channel the buyer opened for an ATR it compared, as JSON the caller keeps and hands back. */
|
|
12
13
|
export interface ChannelHold {
|
|
@@ -14,9 +15,12 @@ export interface ChannelHold {
|
|
|
14
15
|
network: string;
|
|
15
16
|
channel: string;
|
|
16
17
|
h: AtrHash;
|
|
17
|
-
/**
|
|
18
|
+
/** Padded standard base64 of the ATR bytes the opening compared, in its canonical form (RFC 4648 sections 3.5, 4). */
|
|
18
19
|
atr: string;
|
|
19
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* The signed opening payment as the gate returned it, written as plain JSON, with the landed receipt given beside it
|
|
22
|
+
* as its `landed` member, where one is given.
|
|
23
|
+
*/
|
|
20
24
|
opening: Json;
|
|
21
25
|
/** The server's cumulative charge last recorded, decimal; "0" at the opening. */
|
|
22
26
|
charged: string;
|
|
@@ -26,18 +30,37 @@ export interface ChannelHold {
|
|
|
26
30
|
/**
|
|
27
31
|
* Takes a channel pairing's signed opening and the ATR bytes the gate compared for it, with the landed receipt
|
|
28
32
|
* `transact` returned beside the opening, where it returned one. The opening, with that receipt, must be of kind `open`,
|
|
29
|
-
*
|
|
33
|
+
* the pairing must read the hash of these bytes from it, and it must name its channel; the hold keeps all three
|
|
34
|
+
* together.
|
|
30
35
|
*/
|
|
31
36
|
export declare function openChannel(bytes: Uint8Array, opened: Presented, binding: Binding, landed?: unknown): Promise<ChannelHold | Declined>;
|
|
32
37
|
/**
|
|
33
38
|
* Signs one later voucher, or a refund, in a held channel. The ATR bytes, the opening's hash and the opening's
|
|
34
|
-
* channel are re-derived from the hold
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* the
|
|
39
|
+
* channel are re-derived from the hold. An x402 challenge must advertise the held hash. An MPP session's challenge
|
|
40
|
+
* that names another channel or another hash is declined, and one with no legal context is signed under the held
|
|
41
|
+
* hash. A voucher's `maxClaimableAmount` is the recorded charge plus the option's amount; a refund's is the recorded
|
|
42
|
+
* charge. `inputs` are the buyer's own chain values a refund's build takes; `inputs` that is not an object is declined
|
|
43
|
+
* `no-payable-option` with `<namespace>/input-malformed`.
|
|
44
|
+
*
|
|
45
|
+
* A Solana refund is the voucher alone. Taken again after the receiver's binding is unavailable, it also carries the
|
|
46
|
+
* payer-signed `request_close`, built with the `recentBlockhash`, `computeUnitLimit` and `computeUnitPrice` of
|
|
47
|
+
* `inputs`: when the `errorReason` of `refund.paymentResponse`, the settle failure's decoded `PAYMENT-RESPONSE`, read
|
|
48
|
+
* first, or else the challenge's `error`, is `invalid_batch_settlement_svm_receiver_binding_unavailable`. A Solana
|
|
49
|
+
* refund value given in another form, or a `paymentResponse` that is not an object or whose `errorReason` is not a
|
|
50
|
+
* string, is declined `no-payable-option` with `x402/input-malformed`, and the refund taken again without a
|
|
51
|
+
* `recentBlockhash` with `x402/input-missing`. No other pairing's refund reads these values or this code.
|
|
52
|
+
*
|
|
53
|
+
* On x402's batch channels, the channel the built payment would name must be the held one before the signer is called.
|
|
54
|
+
* On MPP's sessions, a channel the challenge names must be the held one and a legal context, where present, must name
|
|
55
|
+
* the held hash, before the signer is called, and the voucher is built from the held opening. In both, the signed
|
|
56
|
+
* payment must then be of the expected kind, commit to the held hash where the pairing's voucher carries one, and
|
|
57
|
+
* name the held channel, or it is dropped.
|
|
38
58
|
*/
|
|
39
59
|
export declare function within(doc: unknown, hold: ChannelHold, binding: Binding, signer: Signer, refund?: {
|
|
40
60
|
amount?: string;
|
|
61
|
+
paymentResponse?: {
|
|
62
|
+
errorReason?: string;
|
|
63
|
+
};
|
|
41
64
|
}, inputs?: Inputs): Promise<{
|
|
42
65
|
signed: Presented;
|
|
43
66
|
hold: ChannelHold;
|