@integraledger/terms 0.1.0 → 0.2.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 +59 -23
- package/dist/agreement.d.ts +11 -17
- package/dist/agreement.js +171 -67
- package/dist/channels.d.ts +3 -2
- package/dist/channels.js +36 -7
- package/dist/gate.d.ts +13 -6
- package/dist/gate.js +30 -23
- package/dist/index.d.ts +1 -1
- package/dist/pairings/batch.js +2 -2
- package/dist/pairings/common.d.ts +6 -1
- package/dist/pairings/common.js +16 -2
- package/dist/pairings/evm-x402.js +3 -3
- package/dist/pairings/lightning.js +1 -1
- package/dist/pairings/mpp-charge-stellar.js +1 -1
- package/dist/pairings/mpp-session-solana.js +2 -2
- package/dist/pairings/mpp-session.js +1 -1
- package/dist/pairings/mpp.js +1 -1
- package/dist/pairings/x402-batch-settlement-eip155.js +1 -1
- package/dist/pairings/x402-batch-settlement-solana.js +1 -1
- package/dist/pairings/x402-exact-casper.js +3 -3
- package/dist/pairings/x402-exact-ccd.js +3 -3
- package/dist/pairings/x402-exact-stellar.js +1 -1
- package/dist/transact.d.ts +12 -8
- package/dist/transact.js +24 -21
- package/dist/types.d.ts +38 -3
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -102,6 +102,7 @@ const signer: Signer = {
|
|
|
102
102
|
|
|
103
103
|
const result = await transact(offer, exactEip3009, signer, fetch);
|
|
104
104
|
if ("decline" in result) throw new Error(`${result.decline.code}: ${result.decline.detail}`);
|
|
105
|
+
if ("approve" in result) throw new Error("this pairing pays no agreement first");
|
|
105
106
|
|
|
106
107
|
const payment = result.signed as Eip3009Payment;
|
|
107
108
|
console.log("H ", result.h);
|
|
@@ -135,7 +136,7 @@ sequenceDiagram
|
|
|
135
136
|
participant S as Seller
|
|
136
137
|
participant W as Your signer
|
|
137
138
|
A->>G: confirm(offer, binding, account, fetch)
|
|
138
|
-
G->>S: GET the link (https, no redirect, at most 1 MiB, 10 s)
|
|
139
|
+
G->>S: GET the link (https, identity coding, no redirect, at most 1 MiB, 10 s)
|
|
139
140
|
S-->>G: The ATR's bytes
|
|
140
141
|
G->>G: SHA-256(bytes) equals H?
|
|
141
142
|
G-->>A: The signing request, built with H
|
|
@@ -159,19 +160,30 @@ Every function returns a value, never throws for a protocol outcome: either its
|
|
|
159
160
|
|
|
160
161
|
### Pay in one call: `transact`
|
|
161
162
|
|
|
162
|
-
`transact(doc, binding, signer, fetch, options?)` runs the whole order: compare, pay the agreement
|
|
163
|
-
pairing needs one, sign, finish. Its result is:
|
|
163
|
+
`transact(doc, binding, signer, fetch, options?)` runs the whole order: compare, pay the agreement your agent approved
|
|
164
|
+
where the pairing needs one, sign, finish. Its result is:
|
|
164
165
|
|
|
165
166
|
| Member | What it is |
|
|
166
167
|
| --- | --- |
|
|
167
168
|
| `signed` | The payment to send, in the protocol's own form. `null` when the pairing gives the buyer nothing to sign. |
|
|
168
169
|
| `bytes` | The ATR's exact bytes: your copy of the record. |
|
|
169
170
|
| `h` | Their SHA-256. |
|
|
170
|
-
| `agreement` | The agreement's receipt, where an agreement
|
|
171
|
+
| `agreement` | The agreement's receipt, where the pairing needs an agreement payment. |
|
|
171
172
|
| `landed` | A landed receipt to keep beside the payment, for the few pairings that return one. |
|
|
172
173
|
|
|
173
|
-
|
|
174
|
-
|
|
174
|
+
Where the pairing needs an agreement payment that is not yet recorded, the result is instead
|
|
175
|
+
`{ approve, bytes, h }`, and nothing has been signed: see [Pay the agreement first](#pay-the-agreement-first).
|
|
176
|
+
|
|
177
|
+
`options` takes:
|
|
178
|
+
|
|
179
|
+
| Member | What it is |
|
|
180
|
+
| --- | --- |
|
|
181
|
+
| `inputs` | The buyer's own values a build needs, such as a recent blockhash. |
|
|
182
|
+
| `agreementSigner` | The wallet that pays the agreement, where it is not `signer`. |
|
|
183
|
+
| `approved` | The agreement payment your agent approved, exactly as a previous call returned it in `approve`. |
|
|
184
|
+
| `signal` | An `AbortSignal` that ends the agreement exchange. |
|
|
185
|
+
|
|
186
|
+
Any other member, or a member of the wrong kind, is declined before any fetch.
|
|
175
187
|
|
|
176
188
|
### Sign elsewhere: `confirm`, then `finish`
|
|
177
189
|
|
|
@@ -240,8 +252,16 @@ A pairing signed in two steps (a channel funding, then its first voucher) makes
|
|
|
240
252
|
|
|
241
253
|
Some payments are not a public proof of H: a card charge, a Stripe payment, a Lightning invoice, a checkout in which
|
|
242
254
|
the buyer signs nothing. For those pairings the seller's offer also names an **agreement URL**, an x402 resource for the
|
|
243
|
-
same H whose payment is a public proof.
|
|
244
|
-
|
|
255
|
+
same H whose payment is a public proof. The agreement payment is a payment like any other, so your agent approves it
|
|
256
|
+
before anything is signed:
|
|
257
|
+
|
|
258
|
+
1. `transact` fetches the agreement URL's payment request and returns `{ approve, bytes, h }`, signing nothing.
|
|
259
|
+
`approve.option` is the option it would pay: its `amount`, `asset`, `payTo` and `network`. `approve.url` is the
|
|
260
|
+
agreement URL, and `approve.required` the payment request as served.
|
|
261
|
+
2. Your agent approves it as it approves any payment. To pay it, call `transact` again with the same arguments and
|
|
262
|
+
`{ approved: approve }`.
|
|
263
|
+
3. The second call signs exactly that payment, sends it, and signs the main payment only after the agreement URL
|
|
264
|
+
answers with its receipt:
|
|
245
265
|
|
|
246
266
|
```json
|
|
247
267
|
{
|
|
@@ -252,11 +272,16 @@ URL answers with its receipt:
|
|
|
252
272
|
}
|
|
253
273
|
```
|
|
254
274
|
|
|
275
|
+
- The option paid is the first, in document order, that your signer can pay with a pairing whose payment is itself a
|
|
276
|
+
public proof: the same rule as for the main payment's options.
|
|
255
277
|
- The agreement URL's `402` must advertise the same H, or nothing is signed (`hash-mismatch`).
|
|
256
278
|
- Once the agreement payment is sent, the gate sends the same payment again after each `202`, `5xx` or timeout, within
|
|
257
|
-
the
|
|
279
|
+
the paid option's `maxTimeoutSeconds` plus 180 seconds. It never signs a second agreement payment. `signal` ends the
|
|
280
|
+
exchange sooner.
|
|
281
|
+
- Where the agreement is already recorded, the first call goes straight on to the main payment.
|
|
258
282
|
- A pairing that needs an agreement and whose offer names none is declined with `agreement-not-offered`.
|
|
259
|
-
- `agree(
|
|
283
|
+
- `agree(bytes, url, signer, fetch, { approved, inputs, signal })` runs the exchange on its own, in the same two calls,
|
|
284
|
+
for an agent that drives each step.
|
|
260
285
|
|
|
261
286
|
### Channels and sessions
|
|
262
287
|
|
|
@@ -315,7 +340,7 @@ const signer: Signer = {
|
|
|
315
340
|
const opened = await transact(offer, batchEvm, signer, fetch, {
|
|
316
341
|
inputs: { payerAuthorizer: authorizer.address, deposit: "100000" },
|
|
317
342
|
});
|
|
318
|
-
if ("decline" in opened || opened.signed === null) throw new Error("the channel did not open");
|
|
343
|
+
if ("decline" in opened || "approve" in opened || opened.signed === null) throw new Error("the channel did not open");
|
|
319
344
|
let hold = await openChannel(opened.bytes, opened.signed, batchEvm);
|
|
320
345
|
if ("decline" in hold) throw new Error(hold.decline.code);
|
|
321
346
|
console.log("channel ", hold.channel);
|
|
@@ -339,7 +364,8 @@ voucher up to 2000
|
|
|
339
364
|
```
|
|
340
365
|
|
|
341
366
|
The hold is plain JSON: store it, and pass the latest one to each call. `within` re-derives everything from the hold,
|
|
342
|
-
never from the new challenge, and signs only when that challenge advertises the held H
|
|
367
|
+
never from the new challenge, and signs only when that challenge advertises the held H and the payment it builds names
|
|
368
|
+
the held channel.
|
|
343
369
|
|
|
344
370
|
### Confirm a payment later: `check`
|
|
345
371
|
|
|
@@ -355,18 +381,18 @@ it again rather than signing a new payment.
|
|
|
355
381
|
|
|
356
382
|
| Code | Meaning |
|
|
357
383
|
| --- | --- |
|
|
358
|
-
| `pairing-not-supported` | The binding names no pairing the gate serves; `chosen` or a hold belongs to another pairing; the pairing has no channel
|
|
384
|
+
| `pairing-not-supported` | The binding names no pairing the gate serves; `chosen` or a hold belongs to another pairing; or the pairing has no channel. |
|
|
359
385
|
| `offer-unreadable` | The seller's document, the chosen option or a build could not be read, or a recorded charge is out of range. `detail` carries the reason. |
|
|
360
|
-
| `no-payable-option` | No option is payable by this account, an input the build needs is missing or malformed,
|
|
386
|
+
| `no-payable-option` | No option is payable by this account (for the agreement, with a public-proof pairing), an input the build needs is missing or malformed, the options of `transact` or `agree` are malformed, or a later channel challenge asks for a payment in a channel the hold did not open. |
|
|
361
387
|
| `link-not-https` | The ATR link or the agreement URL is not an `https` URL. Nothing was fetched. |
|
|
362
|
-
| `atr-unfetchable` | The link did not answer `200` with the bytes within 10 seconds (a redirect counts as a failure)
|
|
388
|
+
| `atr-unfetchable` | The link did not answer `200` with the bytes within 10 seconds (a redirect counts as a failure), or answered `200` with a `Content-Encoding` other than `identity`. |
|
|
363
389
|
| `atr-too-large` | The ATR is larger than 1 MiB (1,048,576 bytes). |
|
|
364
390
|
| `hash-mismatch` | The served bytes do not hash to the advertised H; the agreement URL or a later channel challenge advertises another H; or a hold's bytes do not hash to its H. Nothing was signed. |
|
|
365
391
|
| `signer-failed` | Your signer threw. |
|
|
366
392
|
| `signed-not-bound` | What was signed does not carry the hash of the compared bytes. The payment is not returned. |
|
|
367
393
|
| `agreement-not-offered` | The pairing's payment is not a public proof, and the offer names no agreement URL. |
|
|
368
394
|
| `agreement-pending` | The agreement payment was sent and is not yet recorded, or another is already settling. |
|
|
369
|
-
| `agreement-failed` | The agreement URL could not be reached, or answered with something other than a receipt for this H. |
|
|
395
|
+
| `agreement-failed` | The agreement URL could not be reached, answered `200` or `402` with a `Content-Encoding` other than `identity`, or answered with something other than a receipt for this H; the approved payment names another agreement URL; or `signal` ended the exchange before the payment was sent. |
|
|
370
396
|
|
|
371
397
|
## API reference
|
|
372
398
|
|
|
@@ -376,11 +402,11 @@ Everything below is exported from `@integraledger/terms`.
|
|
|
376
402
|
|
|
377
403
|
| Export | Signature | What it does |
|
|
378
404
|
| --- | --- | --- |
|
|
379
|
-
| `transact` | `(doc, binding, signer, fetch, options?) => Promise<{ signed, bytes, h, agreement?, landed? } \| Declined>` | Compare, pay the agreement first where needed, sign, finish. |
|
|
380
|
-
| `confirm` | `(doc, binding, account, fetch, inputs?) => Promise<{ chosen, request, bytes, h
|
|
405
|
+
| `transact` | `(doc, binding, signer, fetch, options?) => Promise<{ signed, bytes, h, agreement?, landed? } \| ToApprove \| Declined>` | Compare, pay the approved agreement first where needed, sign, finish. |
|
|
406
|
+
| `confirm` | `(doc, binding, account, fetch, inputs?) => Promise<{ chosen, request, bytes, h } \| Declined>` | Read, fetch, compare, and build the signing request with H. `request` is `null` when there is nothing to sign; `chosen.agreement` is the agreement URL, where the pairing needs one. |
|
|
381
407
|
| `finish` | `(bytes, chosen, signature, binding) => Promise<{ signed, h, landed? } \| { next, h } \| Declined>` | Rebuild from `chosen` and the bytes, join the signature, and return the payment only when what was signed carries H. |
|
|
382
408
|
| `check` | `(bytes, presented, binding) => Promise<{ h } \| Declined>` | Confirm a held payment carries the hash of the kept bytes. |
|
|
383
|
-
| `agree` | `(
|
|
409
|
+
| `agree` | `(bytes, url, signer, fetch, options?) => Promise<ToApprove \| { receipt } \| Declined>` | Without `options.approved`, return the agreement payment to approve, signing nothing; with it, pay that payment and return the receipt. |
|
|
384
410
|
| `openChannel` | `(bytes, opened, binding, landed?) => Promise<ChannelHold \| Declined>` | Hold a channel opened for the compared ATR. |
|
|
385
411
|
| `within` | `(doc, hold, binding, signer, refund?, inputs?) => Promise<{ signed, hold } \| Declined>` | Sign a later voucher, or a refund with `refund`, in a held channel. |
|
|
386
412
|
| `recordCharge` | `(hold, chargedCumulativeAmount) => ChannelHold \| Declined` | Record the seller's cumulative charge, between the last recorded and the most signed. |
|
|
@@ -395,9 +421,12 @@ Everything below is exported from `@integraledger/terms`.
|
|
|
395
421
|
| `Signature` | The signer's answer, as JSON. Byte strings are `0x` hex. |
|
|
396
422
|
| `Fetch` | WHATWG `fetch`, or anything with its call shape. |
|
|
397
423
|
| `Inputs` | The buyer's own values a build needs: `{ [name]: Json }`. |
|
|
398
|
-
| `TransactOptions` | `{ inputs?, agreementSigner? }`. |
|
|
399
|
-
| `
|
|
424
|
+
| `TransactOptions` | `{ inputs?, agreementSigner?, approved?, signal? }`. |
|
|
425
|
+
| `AgreeOptions` | `{ approved?, inputs?, signal? }`. |
|
|
426
|
+
| `Chosen` | What the gate chose to pay, as plain JSON: `{ pairing, choice, ref, agreement? }`. |
|
|
400
427
|
| `Presented` | A payment in its protocol's form. |
|
|
428
|
+
| `AgreementPayment` | The agreement payment to approve: `{ url, option, required }`. |
|
|
429
|
+
| `ToApprove` | `{ approve: AgreementPayment; bytes; h }`. |
|
|
401
430
|
| `AgreementReceipt` | `{ atrHash, agreed: true, network, transaction }`. |
|
|
402
431
|
| `ChannelHold` | `{ pairing, network, channel, h, atr, opening, charged, signedMax }`, all JSON. |
|
|
403
432
|
| `Declined` | `{ decline: Reason; moved?: { signed, bytes, h } }`. |
|
|
@@ -497,16 +526,23 @@ What the gate guarantees, in the code:
|
|
|
497
526
|
- **What was signed is read back.** `finish` returns a payment only when the binding reads, from what was signed, the
|
|
498
527
|
hash of the compared bytes. For a pairing whose payment is not a public proof, the payment is returned only after the
|
|
499
528
|
agreement's receipt for that hash.
|
|
529
|
+
- **Every payment is shown before it is signed.** The agreement payment is returned for your agent's approval, with its
|
|
530
|
+
amount, asset, payee and network, and is signed only when a second call carries it back.
|
|
500
531
|
- **One bounded fetch.** One `GET` of an `https` link, no redirect, one 10-second deadline over headers and body, at most
|
|
501
532
|
1 MiB read. A declared or streamed length over the bound cancels the body.
|
|
502
|
-
- **Exact bytes.** The ATR is hashed as received and returned as received. It is never parsed.
|
|
533
|
+
- **Exact bytes.** The ATR is hashed as received and returned as received. It is never parsed. Every request asks for
|
|
534
|
+
`Accept-Encoding: identity`, and a `200` whose `Content-Encoding` names any coding is declined unread, so nothing is
|
|
535
|
+
decompressed: the bytes hashed are the bytes sent.
|
|
503
536
|
- **No keys.** The gate hands requests to your signer and holds nothing that could sign.
|
|
504
537
|
- **Your network policy.** Every request goes through the `fetch` you pass.
|
|
505
538
|
|
|
506
539
|
What it does not do:
|
|
507
540
|
|
|
508
541
|
- It does not read or judge the ATR's content.
|
|
509
|
-
- It does not check amount, payee, asset, timing or payer against the ATR
|
|
542
|
+
- It does not check amount, payee, asset, timing or payer against the ATR, and applies no spending limit to the
|
|
543
|
+
agreement payment. A discrepancy is between the parties; what to approve is your agent's decision.
|
|
544
|
+
- It does not authenticate the agreement's receipt. The public proof is the transaction the receipt names, on its
|
|
545
|
+
network.
|
|
510
546
|
- It carries no business or legal logic.
|
|
511
547
|
- It does not store the ATR, talk to a facilitator, or settle a payment.
|
|
512
548
|
|
package/dist/agreement.d.ts
CHANGED
|
@@ -1,23 +1,17 @@
|
|
|
1
|
+
import type { AgreeOptions, AgreementReceipt, Declined, Fetch, Signer, ToApprove } from "./types.js";
|
|
1
2
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
* timeout, each paid request bounded by min(`maxTimeoutSeconds`, 120) + 60 + 10 seconds and the whole exchange by the
|
|
7
|
-
* agreement option's `maxTimeoutSeconds` + 180 seconds; no second agreement payment is signed, and every decline after
|
|
8
|
-
* it was sent carries it as `moved`.
|
|
3
|
+
* Without `approved`: asks the agreement URL for its challenge and returns the agreement payment to approve, signing
|
|
4
|
+
* nothing, or the receipt where the agreement is already recorded. With `approved`: signs exactly that payment with
|
|
5
|
+
* `signer`, sends it to `url`, and returns the receipt once recorded. `bytes` are the ATR the gate compared, whose hash
|
|
6
|
+
* the agreement payment carries; `inputs` are the buyer's own chain values; `signal` ends the exchange.
|
|
9
7
|
*/
|
|
10
|
-
|
|
11
|
-
|
|
8
|
+
export declare function agree(bytes: Uint8Array, url: string, signer: Signer, fetch: Fetch, options?: AgreeOptions): Promise<ToApprove | {
|
|
9
|
+
receipt: AgreementReceipt;
|
|
10
|
+
} | Declined>;
|
|
12
11
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* whose offer named the URL, which a refused URL's detail carries with the protocol package's code.
|
|
12
|
+
* `agree`, where `ns` is the namespace of the pairing whose offer named the URL: a refused URL's detail carries it with
|
|
13
|
+
* the protocol package's code.
|
|
16
14
|
*/
|
|
17
|
-
export declare function
|
|
18
|
-
bytes: Uint8Array;
|
|
19
|
-
inputs?: Inputs;
|
|
20
|
-
ns?: string;
|
|
21
|
-
}): Promise<{
|
|
15
|
+
export declare function exchange(bytes: Uint8Array, url: string, signer: Signer, fetch: Fetch, options: AgreeOptions, ns: string | undefined): Promise<ToApprove | {
|
|
22
16
|
receipt: AgreementReceipt;
|
|
23
17
|
} | Declined>;
|
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 what was signed carries the hash. Once sent, the same signed payment is sent again after each 202, 5xx
|
|
6
|
-
* timeout, each paid request bounded by min(`maxTimeoutSeconds`, 120) + 60 + 10 seconds and the whole exchange by
|
|
7
|
-
*
|
|
8
|
-
* it was sent carries it as `moved`.
|
|
7
|
+
* sent unless what was signed carries the hash. Once sent, the same signed payment is sent again after each 202, 5xx
|
|
8
|
+
* or timeout, each paid request bounded by min(`maxTimeoutSeconds`, 120) + 60 + 10 seconds and the whole exchange by
|
|
9
|
+
* the paid option's `maxTimeoutSeconds` + 180 seconds; no second agreement payment is signed, and every decline after
|
|
10
|
+
* 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, hash, hashEquals, isHttpsLink, isOtherSchemeLink, parseJson, } from "@integraledger/lcp";
|
|
13
|
+
import { IDENTITY, isIdentity, newRef, pay, pieceOf, redirected } 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,9 +28,9 @@ 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
|
}
|
|
@@ -60,17 +66,36 @@ function retrySeconds(header) {
|
|
|
60
66
|
function isServerError(status) {
|
|
61
67
|
return status >= 500 && status <= 599;
|
|
62
68
|
}
|
|
63
|
-
|
|
64
|
-
|
|
69
|
+
/** Waits `ms`, or less when the caller's signal ends the wait. */
|
|
70
|
+
function sleep(ms, signal) {
|
|
71
|
+
return new Promise((resolve) => {
|
|
72
|
+
const done = () => {
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
signal?.removeEventListener("abort", done);
|
|
75
|
+
resolve();
|
|
76
|
+
};
|
|
77
|
+
const timer = setTimeout(done, ms);
|
|
78
|
+
signal?.addEventListener("abort", done, { once: true });
|
|
79
|
+
if (signal?.aborted === true)
|
|
80
|
+
done();
|
|
81
|
+
});
|
|
65
82
|
}
|
|
66
83
|
/**
|
|
67
|
-
* One GET of the agreement URL, with no redirect followed and a deadline of `ms` over
|
|
68
|
-
*
|
|
84
|
+
* One GET of the agreement URL, asking for the identity coding, with no redirect followed and a deadline of `ms` over
|
|
85
|
+
* headers and body; the caller's signal ends it as the deadline does. A redirect is `agreement-failed`, and so is a 200
|
|
86
|
+
* or a 402, the answers the exchange reads, whose `Content-Encoding` names any coding. A 200 body is read as sent, up to
|
|
87
|
+
* 64 KiB; any other body is cancelled unread.
|
|
69
88
|
*/
|
|
70
|
-
async function get(fetch, url, signature, ms) {
|
|
89
|
+
async function get(fetch, url, signature, ms, signal) {
|
|
71
90
|
const controller = new AbortController();
|
|
72
91
|
const timer = setTimeout(() => controller.abort(new DOMException("The agreement request passed its deadline.", "TimeoutError")), ms);
|
|
92
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
93
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
94
|
+
if (signal?.aborted === true)
|
|
95
|
+
onAbort();
|
|
73
96
|
const deadline = new Promise((_, reject) => {
|
|
97
|
+
if (controller.signal.aborted)
|
|
98
|
+
reject(controller.signal.reason);
|
|
74
99
|
controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
|
|
75
100
|
});
|
|
76
101
|
deadline.catch(() => undefined);
|
|
@@ -78,9 +103,10 @@ async function get(fetch, url, signature, ms) {
|
|
|
78
103
|
let reader;
|
|
79
104
|
let whole = false;
|
|
80
105
|
try {
|
|
81
|
-
const
|
|
106
|
+
const headers = { ...IDENTITY };
|
|
82
107
|
if (signature !== undefined)
|
|
83
|
-
|
|
108
|
+
headers["PAYMENT-SIGNATURE"] = signature;
|
|
109
|
+
const init = { method: "GET", redirect: "manual", signal: controller.signal, headers };
|
|
84
110
|
const response = await Promise.race([fetch(url, init), deadline]);
|
|
85
111
|
body = response.body;
|
|
86
112
|
if (redirected(response))
|
|
@@ -91,6 +117,9 @@ async function get(fetch, url, signature, ms) {
|
|
|
91
117
|
retryAfter: response.headers.get("retry-after"),
|
|
92
118
|
body: null,
|
|
93
119
|
};
|
|
120
|
+
if (READ_STATUSES.includes(response.status) && !isIdentity(response.headers.get("content-encoding"))) {
|
|
121
|
+
return failed("The agreement URL served a content coding other than identity.");
|
|
122
|
+
}
|
|
94
123
|
if (response.status !== 200)
|
|
95
124
|
return answer;
|
|
96
125
|
const declared = response.headers.get("content-length")?.trim();
|
|
@@ -129,6 +158,7 @@ async function get(fetch, url, signature, ms) {
|
|
|
129
158
|
}
|
|
130
159
|
finally {
|
|
131
160
|
clearTimeout(timer);
|
|
161
|
+
signal?.removeEventListener("abort", onAbort);
|
|
132
162
|
if (!whole) {
|
|
133
163
|
cancel(reader ?? body);
|
|
134
164
|
controller.abort();
|
|
@@ -170,83 +200,131 @@ function isPublicProof(binding) {
|
|
|
170
200
|
const pattern = binding.pattern;
|
|
171
201
|
return isObject(pattern) && pattern["publicProof"] === true;
|
|
172
202
|
}
|
|
173
|
-
/** The
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
203
|
+
/** The x402 pairings the gate pays, in the protocol package's order. */
|
|
204
|
+
const X402 = BINDINGS.filter((b) => String(b.id).startsWith("x402/") && pieceOf(b) !== undefined);
|
|
205
|
+
/**
|
|
206
|
+
* The option the agreement is paid with, by the main payment's rule: the options in document order, and the first one
|
|
207
|
+
* the signer can pay whose pairing's payment is itself a public proof. An option's pairing is the first x402 pairing,
|
|
208
|
+
* in the protocol package's order, whose read accepts the challenge holding only that option.
|
|
209
|
+
*/
|
|
210
|
+
async function select(required, account, inputs) {
|
|
211
|
+
const accepts = required["accepts"];
|
|
212
|
+
if (!Array.isArray(accepts) || accepts.length === 0)
|
|
177
213
|
return declined("offer-unreadable", "x402/no-payable-option");
|
|
214
|
+
if (accepts.length > MAX_OPTIONS)
|
|
215
|
+
return declined("offer-unreadable", "x402/option-malformed");
|
|
216
|
+
const now = Math.floor(Date.now() / 1000);
|
|
217
|
+
let unreadable;
|
|
218
|
+
let unpayable;
|
|
219
|
+
for (const option of accepts) {
|
|
220
|
+
if (!isObject(option))
|
|
221
|
+
continue;
|
|
222
|
+
const only = { ...required, accepts: [option] };
|
|
223
|
+
let found;
|
|
224
|
+
for (const binding of X402) {
|
|
225
|
+
const read = binding.read(only);
|
|
226
|
+
if (!isRefusal(read)) {
|
|
227
|
+
found = { binding, read };
|
|
228
|
+
break;
|
|
229
|
+
}
|
|
230
|
+
if (read.code !== "x402/no-payable-option")
|
|
231
|
+
unreadable ??= read.code;
|
|
232
|
+
}
|
|
233
|
+
if (found === undefined || !isPublicProof(found.binding))
|
|
234
|
+
continue;
|
|
235
|
+
const piece = pieceOf(found.binding);
|
|
236
|
+
const chosen = await piece.choose(found.read, account, inputs, now, newRef(), only);
|
|
237
|
+
if (isRefusal(chosen)) {
|
|
238
|
+
unpayable ??= chosen.code;
|
|
239
|
+
continue;
|
|
240
|
+
}
|
|
241
|
+
return { option: option, binding: found.binding, read: found.read, chosen };
|
|
178
242
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
if (binding === undefined)
|
|
183
|
-
return declined("pairing-not-supported", "The agreement option names no pairing the gate serves.");
|
|
184
|
-
if (!isPublicProof(binding)) {
|
|
185
|
-
return declined("pairing-not-supported", `The agreement pairing ${String(id)} is not itself a public proof.`);
|
|
186
|
-
}
|
|
187
|
-
return { binding, option };
|
|
243
|
+
if (unpayable === undefined && unreadable !== undefined)
|
|
244
|
+
return declined("offer-unreadable", unreadable);
|
|
245
|
+
return declined("no-payable-option", unpayable ?? "x402/no-payable-option");
|
|
188
246
|
}
|
|
189
|
-
/**
|
|
247
|
+
/**
|
|
248
|
+
* The paid request's deadline and the whole exchange's, in seconds, from the option's `maxTimeoutSeconds`: a JSON number
|
|
249
|
+
* with an integral value from 1 to 2^53 - 1.
|
|
250
|
+
*/
|
|
190
251
|
function bounds(option) {
|
|
191
252
|
const t = option.maxTimeoutSeconds;
|
|
192
253
|
if (typeof t !== "number" || !Number.isSafeInteger(t) || t <= 0)
|
|
193
254
|
return undefined;
|
|
194
255
|
return { request: Math.min(t, EXCHANGE_CAP_S) + SETTLE_S + VERIFY_S, exchange: t + WINDOW_EXTRA_S };
|
|
195
256
|
}
|
|
257
|
+
/** The option chosen from `required` for `h`, with its bounds, once the challenge is found to advertise `h`. */
|
|
258
|
+
async function paying(required, h, account, inputs) {
|
|
259
|
+
const selected = await select(required, account, inputs);
|
|
260
|
+
if ("decline" in selected)
|
|
261
|
+
return selected;
|
|
262
|
+
const limits = bounds(selected.option);
|
|
263
|
+
if (limits === undefined)
|
|
264
|
+
return declined("offer-unreadable", "x402/option-malformed");
|
|
265
|
+
if (!hashEquals(selected.read.h, h)) {
|
|
266
|
+
return declined("hash-mismatch", "The agreement challenge advertises another ATR hash.");
|
|
267
|
+
}
|
|
268
|
+
return { selected, limits };
|
|
269
|
+
}
|
|
270
|
+
/** Whether `v` has the form of an agreement payment: an agreement URL, an option and a payment request. */
|
|
271
|
+
function isAgreementPayment(v) {
|
|
272
|
+
return isObject(v) && typeof v["url"] === "string" && isObject(v["option"]) && isObject(v["required"]);
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Without `approved`: asks the agreement URL for its challenge and returns the agreement payment to approve, signing
|
|
276
|
+
* nothing, or the receipt where the agreement is already recorded. With `approved`: signs exactly that payment with
|
|
277
|
+
* `signer`, sends it to `url`, and returns the receipt once recorded. `bytes` are the ATR the gate compared, whose hash
|
|
278
|
+
* the agreement payment carries; `inputs` are the buyer's own chain values; `signal` ends the exchange.
|
|
279
|
+
*/
|
|
280
|
+
export function agree(bytes, url, signer, fetch, options) {
|
|
281
|
+
return exchange(bytes, url, signer, fetch, options ?? {}, undefined);
|
|
282
|
+
}
|
|
196
283
|
/**
|
|
197
|
-
*
|
|
198
|
-
*
|
|
199
|
-
* whose offer named the URL, which a refused URL's detail carries with the protocol package's code.
|
|
284
|
+
* `agree`, where `ns` is the namespace of the pairing whose offer named the URL: a refused URL's detail carries it with
|
|
285
|
+
* the protocol package's code.
|
|
200
286
|
*/
|
|
201
|
-
export async function
|
|
287
|
+
export async function exchange(bytes, url, signer, fetch, options, ns) {
|
|
202
288
|
if (!isHttpsLink(url)) {
|
|
203
289
|
const fault = isOtherSchemeLink(url) ? "link-not-https" : "legal-context-malformed";
|
|
204
|
-
return declined("link-not-https",
|
|
290
|
+
return declined("link-not-https", ns === undefined ? "The agreement URL is not an https URL." : `${ns}/${fault}`);
|
|
205
291
|
}
|
|
206
|
-
const {
|
|
207
|
-
const inputs =
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
return unpaid;
|
|
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.");
|
|
292
|
+
const { approved, signal } = options;
|
|
293
|
+
const inputs = isObject(options.inputs) ? options.inputs : {};
|
|
294
|
+
if (approved !== undefined && !isAgreementPayment(approved)) {
|
|
295
|
+
return declined("no-payable-option", `${ns ?? "x402"}/input-malformed`);
|
|
217
296
|
}
|
|
218
|
-
if (
|
|
219
|
-
return
|
|
220
|
-
const
|
|
221
|
-
if (
|
|
222
|
-
return
|
|
223
|
-
|
|
297
|
+
if (isEnded(signal))
|
|
298
|
+
return ended();
|
|
299
|
+
const h = await hash(bytes);
|
|
300
|
+
if (approved === undefined)
|
|
301
|
+
return offer(bytes, h, url, signer, fetch, inputs, signal);
|
|
302
|
+
if (approved.url !== url)
|
|
303
|
+
return failed("The approved agreement payment names another agreement URL.");
|
|
304
|
+
const found = await paying({ ...approved.required, accepts: [approved.option] }, h, signer.account, inputs);
|
|
224
305
|
if ("decline" in found)
|
|
225
306
|
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);
|
|
307
|
+
const { selected, limits } = found;
|
|
308
|
+
const paid = await pay(selected.binding, selected.chosen, signer, bytes);
|
|
236
309
|
if ("decline" in paid)
|
|
237
310
|
return paid;
|
|
238
311
|
if (paid.signed === null)
|
|
239
312
|
return declined("offer-unreadable", "The agreement payment gave nothing to sign.");
|
|
313
|
+
if (isEnded(signal))
|
|
314
|
+
return ended();
|
|
240
315
|
const signed = paid.signed;
|
|
241
316
|
const payment = toBase64(JSON.stringify(signed));
|
|
242
317
|
const moved = { signed, bytes, h };
|
|
243
318
|
const keep = (d) => ({ ...d, moved });
|
|
319
|
+
const pending = (detail) => keep(declined("agreement-pending", detail));
|
|
244
320
|
const end = Date.now() + limits.exchange * 1000;
|
|
245
321
|
for (;;) {
|
|
246
322
|
const remaining = end - Date.now();
|
|
247
323
|
if (remaining <= 0)
|
|
248
|
-
return
|
|
249
|
-
const answer = await get(fetch, url, payment, Math.min(limits.request * 1000, remaining));
|
|
324
|
+
return pending("The agreement payment was sent and is not yet recorded.");
|
|
325
|
+
const answer = await get(fetch, url, payment, Math.min(limits.request * 1000, remaining), signal);
|
|
326
|
+
if (isEnded(signal))
|
|
327
|
+
return pending("The caller's signal ended the exchange after the agreement payment was sent.");
|
|
250
328
|
if ("decline" in answer)
|
|
251
329
|
return keep(answer);
|
|
252
330
|
let wait = RETRY_DEFAULT_S * 1000;
|
|
@@ -259,6 +337,32 @@ export async function agree(h, url, signer, fetch, held) {
|
|
|
259
337
|
return keep(failed(`The agreement URL answered status ${answer.status} to the payment.`));
|
|
260
338
|
wait = retrySeconds(answer.retryAfter) * 1000;
|
|
261
339
|
}
|
|
262
|
-
await sleep(Math.max(0, Math.min(wait, end - Date.now())));
|
|
340
|
+
await sleep(Math.max(0, Math.min(wait, end - Date.now())), signal);
|
|
341
|
+
if (isEnded(signal))
|
|
342
|
+
return pending("The caller's signal ended the exchange after the agreement payment was sent.");
|
|
263
343
|
}
|
|
264
344
|
}
|
|
345
|
+
/** The unpaid request: the agreement payment to approve, the receipt of an agreement already recorded, or a decline. */
|
|
346
|
+
async function offer(bytes, h, url, signer, fetch, inputs, signal) {
|
|
347
|
+
const unpaid = await get(fetch, url, undefined, UNPAID_DEADLINE_MS, signal);
|
|
348
|
+
if (isEnded(signal))
|
|
349
|
+
return ended();
|
|
350
|
+
if ("decline" in unpaid)
|
|
351
|
+
return unpaid;
|
|
352
|
+
if ("unanswered" in unpaid)
|
|
353
|
+
return failed("The agreement URL could not be reached.");
|
|
354
|
+
if (unpaid.status === 200)
|
|
355
|
+
return receiptOf(unpaid.body, h);
|
|
356
|
+
if (unpaid.status === 202) {
|
|
357
|
+
return declined("agreement-pending", "An agreement payment for this ATR is already settling.");
|
|
358
|
+
}
|
|
359
|
+
if (unpaid.status !== 402)
|
|
360
|
+
return failed(`The agreement URL answered status ${unpaid.status}.`);
|
|
361
|
+
const required = unpaid.paymentRequired === null ? undefined : fromBase64Json(unpaid.paymentRequired);
|
|
362
|
+
if (!isObject(required))
|
|
363
|
+
return failed("The agreement URL answered 402 without a readable PAYMENT-REQUIRED.");
|
|
364
|
+
const found = await paying(required, h, signer.account, inputs);
|
|
365
|
+
if ("decline" in found)
|
|
366
|
+
return found;
|
|
367
|
+
return { approve: { url, option: found.selected.option, required: required }, bytes, h };
|
|
368
|
+
}
|
package/dist/channels.d.ts
CHANGED
|
@@ -33,8 +33,9 @@ export declare function openChannel(bytes: Uint8Array, opened: Presented, bindin
|
|
|
33
33
|
* Signs one later voucher, or a refund, in a held channel. The ATR bytes, the opening's hash and the opening's
|
|
34
34
|
* channel are re-derived from the hold, and the challenge must advertise the held hash. A voucher's
|
|
35
35
|
* `maxClaimableAmount` is the recorded charge plus the option's amount; a refund's is the recorded charge. `inputs`
|
|
36
|
-
* are the buyer's own chain values a refund's build takes.
|
|
37
|
-
* the held channel, or it
|
|
36
|
+
* are the buyer's own chain values a refund's build takes. Before the signer is called, the channel the built payment
|
|
37
|
+
* would name must be the held one. What was signed must be of the expected kind and belong to the held channel, or it
|
|
38
|
+
* is dropped.
|
|
38
39
|
*/
|
|
39
40
|
export declare function within(doc: unknown, hold: ChannelHold, binding: Binding, signer: Signer, refund?: {
|
|
40
41
|
amount?: string;
|