@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/dist/channels.js CHANGED
@@ -9,7 +9,7 @@
9
9
  import { fromLcpString, hash, hashEquals, parseJson } from "@integraledger/lcp";
10
10
  import { network as mppNetwork, sessionResume } from "@integraledger/lcp/mpp";
11
11
  import { offers, requestOf } from "./pairings/mpp.js";
12
- import { withPaymentIdentifier } from "./pairings/common.js";
12
+ import { isRefusal, refuse, withPaymentIdentifier } from "./pairings/common.js";
13
13
  import { MAX_ATR_BYTES, } from "./types.js";
14
14
  const DECIMAL = /^[0-9]{1,78}$/;
15
15
  /** At most this many challenges of a within document are looked at, as the MPP entry point reads a document. */
@@ -19,12 +19,19 @@ const MAX_OPAQUE = 10_924;
19
19
  const NOT_BOUND_WITHIN = /\/not-bound-within$/;
20
20
  const REF_BYTES = 24;
21
21
  const HOLD_KEYS = ["pairing", "network", "channel", "h", "atr", "charged", "signedMax"];
22
+ /**
23
+ * For each request kind an in-channel build returns, an answer of the form that kind takes, of zero bytes: 65 bytes in
24
+ * `0x` hex for `eip712`, 64 bytes in base58 for `ed25519-raw` and `solana-message`. It completes a build without a
25
+ * signature, so that the channel its payment names can be read before the signer is called.
26
+ */
27
+ const UNSIGNED_ANSWER = Object.freeze({
28
+ eip712: `0x${"00".repeat(65)}`,
29
+ "ed25519-raw": "1".repeat(64),
30
+ "solana-message": "1".repeat(64),
31
+ });
22
32
  function declined(code, detail) {
23
33
  return { decline: { code, detail } };
24
34
  }
25
- function isRefusal(v) {
26
- return typeof v === "object" && v !== null && v.refused === true;
27
- }
28
35
  function isObject(v) {
29
36
  return typeof v === "object" && v !== null && !Array.isArray(v);
30
37
  }
@@ -35,7 +42,7 @@ async function guarded(run) {
35
42
  return await run();
36
43
  }
37
44
  catch {
38
- return { refused: true, code: "member-failed" };
45
+ return refuse("member-failed");
39
46
  }
40
47
  }
41
48
  function toBase64(bytes) {
@@ -70,6 +77,21 @@ function isHold(v) {
70
77
  DECIMAL.test(v["signedMax"]) &&
71
78
  isObject(v["opening"]));
72
79
  }
80
+ /**
81
+ * The channel an in-channel build's payment would name, read by the binding's `channel.ref` from the build completed
82
+ * with `UNSIGNED_ANSWER`s, before anything is signed.
83
+ */
84
+ async function wouldBeChannel(batch, channel) {
85
+ const answers = batch.requests.map((r) => (Object.hasOwn(UNSIGNED_ANSWER, r.kind) ? UNSIGNED_ANSWER[r.kind] : undefined));
86
+ if (!answers.every((a) => a !== undefined)) {
87
+ return declined("offer-unreadable", "The in-channel payment's channel cannot be read before it is signed.");
88
+ }
89
+ const completed = await guarded(() => batch.complete(answers));
90
+ if (isRefusal(completed))
91
+ return declined("offer-unreadable", completed.code);
92
+ const ref = await guarded(() => channel.ref(completed));
93
+ return isRefusal(ref) ? declined("offer-unreadable", ref.code) : ref;
94
+ }
73
95
  /**
74
96
  * The buyer's own chain values a refund's build takes: a Solana `request_close` needs a recent blockhash when the option
75
97
  * names none, and may take the Compute Budget values.
@@ -144,8 +166,9 @@ export async function openChannel(bytes, opened, binding, landed) {
144
166
  * Signs one later voucher, or a refund, in a held channel. The ATR bytes, the opening's hash and the opening's
145
167
  * channel are re-derived from the hold, and the challenge must advertise the held hash. A voucher's
146
168
  * `maxClaimableAmount` is the recorded charge plus the option's amount; a refund's is the recorded charge. `inputs`
147
- * are the buyer's own chain values a refund's build takes. What was signed must be of the expected kind and belong to
148
- * the held channel, or it is dropped.
169
+ * are the buyer's own chain values a refund's build takes. Before the signer is called, the channel the built payment
170
+ * would name must be the held one. What was signed must be of the expected kind and belong to the held channel, or it
171
+ * is dropped.
149
172
  */
150
173
  export async function within(doc, hold, binding, signer, refund, inputs = {}) {
151
174
  const b = stepsOf(binding);
@@ -213,6 +236,12 @@ export async function within(doc, hold, binding, signer, refund, inputs = {}) {
213
236
  if (isRefusal(unsigned))
214
237
  return declined("offer-unreadable", unsigned.code);
215
238
  const batch = unsigned;
239
+ const wouldBe = await wouldBeChannel(batch, channel);
240
+ if ("decline" in wouldBe)
241
+ return wouldBe;
242
+ if (wouldBe.network !== hold.network || wouldBe.channel !== hold.channel) {
243
+ return declined("no-payable-option", "The challenge asks for a payment in a channel this hold did not open.");
244
+ }
216
245
  const request = {
217
246
  kind: "batch",
218
247
  requests: batch.requests,
package/dist/gate.d.ts CHANGED
@@ -6,7 +6,7 @@
6
6
  * kept bytes.
7
7
  */
8
8
  import { type AtrHash } from "@integraledger/lcp";
9
- import { type Binding, type BuyerPiece, type Chosen, type DeclineCode, type Declined, type Fetch, type Inputs, type Presented, type Read, type Signature, type Signer, type SigningRequest } from "./types.js";
9
+ import { type Binding, type BuyerPiece, type Chosen, type DeclineCode, type Declined, type Fetch, type Inputs, type Presented, type Signature, type Signer, type SigningRequest } from "./types.js";
10
10
  export declare function declined(code: DeclineCode, detail: string): Declined;
11
11
  export declare function isObject(v: unknown): v is Record<string, unknown>;
12
12
  /** The pairing's namespace: its id up to the first `/`. */
@@ -17,17 +17,23 @@ export declare function unsupported(binding: Binding): Declined;
17
17
  export declare function newRef(): string;
18
18
  /** Whether an answer to a `redirect: "manual"` request is a redirect: a 3xx status, or the opaque form a browser gives. */
19
19
  export declare function redirected(response: Response): boolean;
20
+ /** The request header that asks for the body with no content coding, so the bytes hashed are the bytes sent. */
21
+ export declare const IDENTITY: {
22
+ readonly "Accept-Encoding": "identity";
23
+ };
24
+ /** Whether a `Content-Encoding` value names no coding: absent, empty, or `identity`. */
25
+ export declare function isIdentity(contentEncoding: string | null): boolean;
20
26
  /**
21
27
  * Reads the offer, chooses the option, fetches the ATR and compares its SHA-256 with the advertised hash. Only on a
22
28
  * match does it build, with the hash it computed. A pairing whose build has nothing for the buyer to sign returns
23
- * `request: null`: the comparison is the whole of the buyer's step.
29
+ * `request: null`: the comparison is the whole of the buyer's step. For a pairing whose payment is not itself a public
30
+ * proof, `chosen.agreement` is the agreement URL the offer names.
24
31
  */
25
32
  export declare function confirm(doc: unknown, binding: Binding, account: string, fetch: Fetch, inputs?: Inputs): Promise<{
26
33
  chosen: Chosen;
27
34
  request: SigningRequest | null;
28
35
  bytes: Uint8Array;
29
36
  h: AtrHash;
30
- agreement?: string;
31
37
  } | Declined>;
32
38
  /**
33
39
  * Rebuilds the payment from `chosen` and the bytes, joins the signer's answer, and returns the payment only when what
@@ -50,10 +56,11 @@ export declare function check(bytes: Uint8Array, presented: unknown, binding: Bi
50
56
  h: AtrHash;
51
57
  } | Declined>;
52
58
  /**
53
- * Chooses, builds and signs one payment for a read the caller has already compared: the signer is called once, or,
54
- * for a pairing signed in steps, once per step in order, and the payment is returned only through `finish`.
59
+ * Builds and signs the payment `chosen` names, with the hash of `bytes`: the signer is called once, or, for a pairing
60
+ * signed in steps, once per step in order, and the payment is returned only through `finish`. `signed` is null where the
61
+ * pairing has nothing for the buyer to sign.
55
62
  */
56
- export declare function pay(binding: Binding, read: Read, doc: unknown, signer: Signer, inputs: Inputs, bytes: Uint8Array): Promise<{
63
+ export declare function pay(binding: Binding, chosen: Chosen, signer: Signer, bytes: Uint8Array): Promise<{
57
64
  signed: Presented | null;
58
65
  landed?: unknown;
59
66
  h: AtrHash;
package/dist/gate.js CHANGED
@@ -6,6 +6,7 @@
6
6
  * kept bytes.
7
7
  */
8
8
  import { hash, hashEquals, isHttpsLink, isOtherSchemeLink } from "@integraledger/lcp";
9
+ import { isRefusal, refuse } from "./pairings/common.js";
9
10
  import { PIECES } from "./pairings/index.js";
10
11
  import { MAX_ATR_BYTES, } from "./types.js";
11
12
  const steps = (binding) => binding;
@@ -20,9 +21,6 @@ const DECIMAL = /^[0-9]+$/;
20
21
  export function declined(code, detail) {
21
22
  return { decline: { code, detail } };
22
23
  }
23
- function isRefusal(v) {
24
- return typeof v === "object" && v !== null && v.refused === true;
25
- }
26
24
  export function isObject(v) {
27
25
  return typeof v === "object" && v !== null && !Array.isArray(v);
28
26
  }
@@ -62,9 +60,17 @@ export function newRef() {
62
60
  export function redirected(response) {
63
61
  return response.type === "opaqueredirect" || (response.status >= 300 && response.status <= 399);
64
62
  }
63
+ /** The request header that asks for the body with no content coding, so the bytes hashed are the bytes sent. */
64
+ export const IDENTITY = { "Accept-Encoding": "identity" };
65
+ /** Whether a `Content-Encoding` value names no coding: absent, empty, or `identity`. */
66
+ export function isIdentity(contentEncoding) {
67
+ const v = (contentEncoding ?? "").trim().toLowerCase();
68
+ return v === "" || v === "identity";
69
+ }
65
70
  /**
66
- * One GET of the link, with no redirect followed, one 10-second deadline over headers and body, and at most
67
- * `MAX_ATR_BYTES` read. A redirect, like any status but 200, is `atr-unfetchable`. A declared or streamed length over the
71
+ * One GET of the link, asking for the identity coding, with no redirect followed, one 10-second deadline over headers
72
+ * and body, and at most `MAX_ATR_BYTES` read. A redirect, like any status but 200, is `atr-unfetchable`, and so is a 200
73
+ * whose `Content-Encoding` names any coding: its body is never read or decoded. A declared or streamed length over the
68
74
  * bound cancels the body. The bytes are returned exactly as received.
69
75
  */
70
76
  async function fetchAtr(fetch, link) {
@@ -79,7 +85,7 @@ async function fetchAtr(fetch, link) {
79
85
  let whole = false;
80
86
  try {
81
87
  const response = await Promise.race([
82
- fetch(link, { method: "GET", redirect: "manual", signal: controller.signal }),
88
+ fetch(link, { method: "GET", redirect: "manual", signal: controller.signal, headers: { ...IDENTITY } }),
83
89
  deadline,
84
90
  ]);
85
91
  body = response.body;
@@ -87,6 +93,9 @@ async function fetchAtr(fetch, link) {
87
93
  return declined("atr-unfetchable", "The link answered with a redirect.");
88
94
  if (response.status !== 200)
89
95
  return declined("atr-unfetchable", `The link answered status ${response.status}.`);
96
+ if (!isIdentity(response.headers.get("content-encoding"))) {
97
+ return declined("atr-unfetchable", "The link served a content coding other than identity.");
98
+ }
90
99
  const declared = response.headers.get("content-length")?.trim();
91
100
  if (declared !== undefined && DECIMAL.test(declared) && Number(declared) > MAX_ATR_BYTES)
92
101
  return tooLarge();
@@ -142,7 +151,8 @@ function cancel(s) {
142
151
  /**
143
152
  * Reads the offer, chooses the option, fetches the ATR and compares its SHA-256 with the advertised hash. Only on a
144
153
  * match does it build, with the hash it computed. A pairing whose build has nothing for the buyer to sign returns
145
- * `request: null`: the comparison is the whole of the buyer's step.
154
+ * `request: null`: the comparison is the whole of the buyer's step. For a pairing whose payment is not itself a public
155
+ * proof, `chosen.agreement` is the agreement URL the offer names.
146
156
  */
147
157
  export async function confirm(doc, binding, account, fetch, inputs = {}) {
148
158
  const piece = pieceOf(binding);
@@ -156,9 +166,10 @@ export async function confirm(doc, binding, account, fetch, inputs = {}) {
156
166
  if (agreement !== undefined && typeof agreement !== "string") {
157
167
  return declined("offer-unreadable", "The offer names an agreement URL that is not a string.");
158
168
  }
159
- const chosen = await piece.choose(read, account, isObject(inputs) ? inputs : {}, Math.floor(Date.now() / 1000), newRef(), doc);
160
- if (isRefusal(chosen))
161
- return declined("no-payable-option", chosen.code);
169
+ const choice = await piece.choose(read, account, isObject(inputs) ? inputs : {}, Math.floor(Date.now() / 1000), newRef(), doc);
170
+ if (isRefusal(choice))
171
+ return declined("no-payable-option", choice.code);
172
+ const chosen = agreement === undefined ? choice : { ...choice, agreement };
162
173
  if (!isHttpsLink(read.link))
163
174
  return declined("link-not-https", linkRefusal(binding, read.link));
164
175
  const bytes = await fetchAtr(fetch, read.link);
@@ -172,16 +183,15 @@ export async function confirm(doc, binding, account, fetch, inputs = {}) {
172
183
  return declined("agreement-not-offered", "The pairing's payment carries no public proof and the offer names no agreement URL.");
173
184
  }
174
185
  const unsigned = await buildWith(piece, b, chosen, computed, bytes);
175
- const withAgreement = agreement === undefined ? {} : { agreement };
176
186
  if (isRefusal(unsigned)) {
177
187
  if (NOTHING_TO_SIGN.test(unsigned.code))
178
- return { chosen, request: null, bytes, h: computed, ...withAgreement };
188
+ return { chosen, request: null, bytes, h: computed };
179
189
  return declined("offer-unreadable", unsigned.code);
180
190
  }
181
191
  const request = piece.request(unsigned);
182
192
  if (isRefusal(request))
183
193
  return declined("offer-unreadable", request.code);
184
- return { chosen, request, bytes, h: computed, ...withAgreement };
194
+ return { chosen, request, bytes, h: computed };
185
195
  }
186
196
  /** The pairing's build over the choice the piece revives from `chosen`. */
187
197
  async function buildWith(piece, b, chosen, h, bytes) {
@@ -192,7 +202,7 @@ async function buildWith(piece, b, chosen, h, bytes) {
192
202
  return await (piece.build !== undefined ? piece.build(choice, h) : b.build(choice, h));
193
203
  }
194
204
  catch {
195
- return { refused: true, code: `${b.id.split("/")[0]}/build-failed` };
205
+ return refuse(`${b.id.split("/")[0]}/build-failed`);
196
206
  }
197
207
  }
198
208
  /**
@@ -267,7 +277,7 @@ async function boundOf(b, presented) {
267
277
  return await b.bound(presented);
268
278
  }
269
279
  catch {
270
- return { refused: true, code: "bound-failed" };
280
+ return refuse("bound-failed");
271
281
  }
272
282
  }
273
283
  /** Confirms that a payment held later carries, inside what was signed, the hash of the kept bytes. */
@@ -282,19 +292,16 @@ export async function check(bytes, presented, binding) {
282
292
  return { h };
283
293
  }
284
294
  /**
285
- * Chooses, builds and signs one payment for a read the caller has already compared: the signer is called once, or,
286
- * for a pairing signed in steps, once per step in order, and the payment is returned only through `finish`.
295
+ * Builds and signs the payment `chosen` names, with the hash of `bytes`: the signer is called once, or, for a pairing
296
+ * signed in steps, once per step in order, and the payment is returned only through `finish`. `signed` is null where the
297
+ * pairing has nothing for the buyer to sign.
287
298
  */
288
- export async function pay(binding, read, doc, signer, inputs, bytes) {
299
+ export async function pay(binding, chosen, signer, bytes) {
289
300
  const piece = pieceOf(binding);
290
301
  if (piece === undefined)
291
302
  return unsupported(binding);
292
- const b = steps(binding);
293
- const chosen = await piece.choose(read, signer.account, isObject(inputs) ? inputs : {}, Math.floor(Date.now() / 1000), newRef(), doc);
294
- if (isRefusal(chosen))
295
- return declined("no-payable-option", chosen.code);
296
303
  const h = await hash(bytes);
297
- const unsigned = await buildWith(piece, b, chosen, h, bytes);
304
+ const unsigned = await buildWith(piece, steps(binding), chosen, h, bytes);
298
305
  if (isRefusal(unsigned)) {
299
306
  if (NOTHING_TO_SIGN.test(unsigned.code))
300
307
  return { signed: null, h };
package/dist/index.d.ts CHANGED
@@ -2,4 +2,4 @@ export { agree } from "./agreement.js";
2
2
  export { openChannel, recordCharge, within, type ChannelHold } from "./channels.js";
3
3
  export { check, confirm, finish } from "./gate.js";
4
4
  export { transact } from "./transact.js";
5
- export type { AgreementReceipt, Binding, Chosen, DeclineCode, Declined, Fetch, Inputs, Presented, Reason, Signature, Signer, SigningRequest, TransactOptions, } from "./types.js";
5
+ export type { AgreeOptions, AgreementPayment, AgreementReceipt, Binding, Chosen, DeclineCode, Declined, Fetch, Inputs, Presented, Reason, Signature, Signer, SigningRequest, ToApprove, TransactOptions, } from "./types.js";
@@ -1,4 +1,4 @@
1
- import { bigintOf, choiceOf, hexOf, isObject, refuse, withPaymentIdentifier } from "./common.js";
1
+ import { bigintOf, choiceOf, hexOf, isObject, isRefusal, refuse, withPaymentIdentifier } from "./common.js";
2
2
  /**
3
3
  * The deposit: `extra.minDeposit` when the option carries one, else the buyer's `deposit` input. A deposit above the
4
4
  * buyer's `maxDeposit` input, when given, is refused.
@@ -47,7 +47,7 @@ export async function batchComplete(unsigned, signature, chosen) {
47
47
  return refuse("x402/signature-malformed");
48
48
  }
49
49
  const signed = u.complete(signature);
50
- if ("refused" in signed)
50
+ if (isRefusal(signed))
51
51
  return signed;
52
52
  return withPaymentIdentifier(signed, choiceOf(chosen)?.["required"], chosen.ref);
53
53
  }
@@ -2,10 +2,15 @@
2
2
  * What the buyer pieces share: the CAIP-10 account, the first x402 option on the account's network, the payment
3
3
  * identifier the x402 client writes, and the JSON forms of byte strings and integers.
4
4
  */
5
- import type { Json, Refusal } from "@integraledger/lcp";
5
+ import { type Json, type Refusal } from "@integraledger/lcp";
6
6
  import type { PaymentRequired, PaymentRequirements, X402Offer } from "@integraledger/lcp/x402";
7
7
  import type { Chosen, Inputs, Read } from "../types.js";
8
+ /** A refusal with `code`, made by the gate. */
8
9
  export declare function refuse(code: string): Refusal;
10
+ /**
11
+ * True for a refusal the protocol package made (its `isRefusal`) or the gate made (`refuse`). A value from a seller,
12
+ * a signer or a caller that is shaped `{ refused: true, … }` is neither, so it is never passed on as a refusal.
13
+ */
9
14
  export declare function isRefusal(v: unknown): v is Refusal;
10
15
  export declare function isObject(v: unknown): v is Record<string, unknown>;
11
16
  /**
@@ -1,12 +1,26 @@
1
+ /**
2
+ * What the buyer pieces share: the CAIP-10 account, the first x402 option on the account's network, the payment
3
+ * identifier the x402 client writes, and the JSON forms of byte strings and integers.
4
+ */
5
+ import { isRefusal as isLcpRefusal } from "@integraledger/lcp";
1
6
  const CAIP10 = /^([-a-z0-9]{3,8}):([-_a-zA-Z0-9]{1,32}):([-.%a-zA-Z0-9]{1,128})$/;
2
7
  const PAYMENT_IDENTIFIER = "payment-identifier";
3
8
  const HEX = /^0x(?:[0-9a-fA-F]{2})*$/;
4
9
  const DECIMAL = /^[0-9]{1,78}$/;
10
+ /** Every refusal the gate makes. Membership, not shape, is what makes a value one of them. */
11
+ const made = new WeakSet();
12
+ /** A refusal with `code`, made by the gate. */
5
13
  export function refuse(code) {
6
- return { refused: true, code };
14
+ const r = { refused: true, code };
15
+ made.add(r);
16
+ return r;
7
17
  }
18
+ /**
19
+ * True for a refusal the protocol package made (its `isRefusal`) or the gate made (`refuse`). A value from a seller,
20
+ * a signer or a caller that is shaped `{ refused: true, … }` is neither, so it is never passed on as a refusal.
21
+ */
8
22
  export function isRefusal(v) {
9
- return typeof v === "object" && v !== null && v.refused === true;
23
+ return isLcpRefusal(v) || (typeof v === "object" && v !== null && made.has(v));
10
24
  }
11
25
  export function isObject(v) {
12
26
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -1,4 +1,4 @@
1
- import { choiceOf, firstOption, isObject, refuse, withPaymentIdentifier, x402Chosen } from "./common.js";
1
+ import { choiceOf, firstOption, isObject, isRefusal, refuse, withPaymentIdentifier, x402Chosen } from "./common.js";
2
2
  const EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
3
3
  /** An EIP-712 signing request, from either form of an EVM x402 build. */
4
4
  function request(unsigned) {
@@ -29,7 +29,7 @@ async function complete(unsigned, signature, chosen) {
29
29
  delegator: delegator,
30
30
  });
31
31
  }
32
- if ("refused" in signed)
32
+ if (isRefusal(signed))
33
33
  return signed;
34
34
  return withPaymentIdentifier(signed, choiceOf(chosen)?.["required"], chosen.ref);
35
35
  }
@@ -38,7 +38,7 @@ export function evmX402Piece(pairing) {
38
38
  return Object.freeze({
39
39
  choose(read, account, _inputs, now, ref) {
40
40
  const o = firstOption(read, account, "eip155", pairing, EVM_ADDRESS);
41
- if ("refused" in o)
41
+ if (isRefusal(o))
42
42
  return refuse("x402/no-payable-option");
43
43
  return x402Chosen(pairing, { required: o.required, accepted: o.accepted, from: o.address, now }, ref);
44
44
  },
@@ -41,7 +41,7 @@ export function lnbtcPiece(pairing, named) {
41
41
  return Object.freeze({
42
42
  async choose(read, account, inputs, _now, ref) {
43
43
  const o = firstOption(read, account, "lnbtc", pairing);
44
- if ("refused" in o)
44
+ if (isRefusal(o))
45
45
  return refuse("x402/no-payable-option");
46
46
  const request = isObject(inputs) ? inputs["request"] : undefined;
47
47
  if (request === undefined)
@@ -8,7 +8,7 @@ export const mppChargeStellar = mppRailPiece({
8
8
  pairing: PAIRING,
9
9
  namespace: "stellar",
10
10
  address: STELLAR_ACCOUNT,
11
- payer: null,
11
+ payer: "payer",
12
12
  now: true,
13
13
  inputs,
14
14
  revive: (c) => c,
@@ -1,5 +1,5 @@
1
1
  import { sessionProof } from "@integraledger/lcp/svm";
2
- import { choiceOf, inputsOf, isObject, refuse } from "./common.js";
2
+ import { choiceOf, inputsOf, isObject, isRefusal, refuse } from "./common.js";
3
3
  import { requestOf } from "./mpp.js";
4
4
  import { completeWith, mppRailPiece, sessionRevive } from "./mpp-rails.js";
5
5
  import { SOLANA_ADDRESS } from "./x402-exact-solana.js";
@@ -30,7 +30,7 @@ async function complete(unsigned, signature, chosen) {
30
30
  const mode = operatorMode(chosen);
31
31
  if (mode === null)
32
32
  return completeOpen(unsigned, signature, chosen);
33
- if ("refused" in mode)
33
+ if (isRefusal(mode))
34
34
  return mode;
35
35
  if (isObject(signature)) {
36
36
  const channelId = signature["channelId"];
@@ -35,7 +35,7 @@ async function sessionComplete(unsigned, signature) {
35
35
  const u = unsigned;
36
36
  if (typeof signature === "string") {
37
37
  const voucher = u.voucher(signature);
38
- if ("refused" in voucher)
38
+ if (isRefusal(voucher))
39
39
  return voucher;
40
40
  return { next: { kind: "eip712", typedData: voucher } };
41
41
  }
@@ -176,7 +176,7 @@ export async function pushComplete(unsigned, signature) {
176
176
  if (!isObject(signature) || typeof signature["hash"] !== "string")
177
177
  return refuse("mpp/credential-malformed");
178
178
  const credential = unsigned.complete(signature["hash"]);
179
- if ("refused" in credential)
179
+ if (isRefusal(credential))
180
180
  return credential;
181
181
  const landed = signature["landed"];
182
182
  if (landed === undefined)
@@ -6,7 +6,7 @@ const HASH32 = /^0x[0-9a-fA-F]{64}$/;
6
6
  export const x402BatchSettlementEip155 = Object.freeze({
7
7
  choose(read, account, inputs, now, ref) {
8
8
  const o = firstOption(read, account, "eip155", PAIRING, EVM_ADDRESS);
9
- if ("refused" in o)
9
+ if (isRefusal(o))
10
10
  return refuse("x402/no-payable-option");
11
11
  const given = optionalInputs(inputs, "x402", { payerAuthorizer: EVM_ADDRESS, authSalt: HASH32 });
12
12
  if (isRefusal(given))
@@ -8,7 +8,7 @@ const isU64 = (v) => typeof v === "string" && U64.test(v) && BigInt(v) < U64_LIM
8
8
  export const x402BatchSettlementSolana = Object.freeze({
9
9
  choose(read, account, inputs, now, ref) {
10
10
  const o = firstOption(read, account, "solana", PAIRING, KEY);
11
- if ("refused" in o)
11
+ if (isRefusal(o))
12
12
  return refuse("x402/no-payable-option");
13
13
  const extra = isObject(o.accepted.extra) ? o.accepted.extra : {};
14
14
  const offered = extra["recentBlockhash"];
@@ -1,9 +1,9 @@
1
- import { choiceOf, firstOption, isObject, refuse, withPaymentIdentifier, x402Chosen } from "./common.js";
1
+ import { choiceOf, firstOption, isObject, isRefusal, refuse, withPaymentIdentifier, x402Chosen } from "./common.js";
2
2
  const ID = "x402/exact/casper";
3
3
  export const x402ExactCasper = Object.freeze({
4
4
  choose(read, account, _inputs, now, ref) {
5
5
  const o = firstOption(read, account, "casper", ID);
6
- if ("refused" in o)
6
+ if (isRefusal(o))
7
7
  return refuse("x402/no-payable-option");
8
8
  return x402Chosen(ID, { required: o.required, accepted: o.accepted, from: o.address, now }, ref);
9
9
  },
@@ -14,7 +14,7 @@ export const x402ExactCasper = Object.freeze({
14
14
  return refuse("x402/signature-malformed");
15
15
  }
16
16
  const signed = unsigned.complete(signature["publicKey"], signature["signature"]);
17
- if ("refused" in signed)
17
+ if (isRefusal(signed))
18
18
  return signed;
19
19
  return withPaymentIdentifier(signed, choiceOf(chosen)?.["required"], chosen.ref);
20
20
  },
@@ -1,9 +1,9 @@
1
- import { choiceOf, firstOption, isObject, refuse, withPaymentIdentifier, x402Chosen } from "./common.js";
1
+ import { choiceOf, firstOption, isObject, isRefusal, refuse, withPaymentIdentifier, x402Chosen } from "./common.js";
2
2
  const ID = "x402/exact/ccd";
3
3
  export const x402ExactCcd = Object.freeze({
4
4
  choose(read, account, _inputs, now, ref) {
5
5
  const o = firstOption(read, account, "ccd", ID);
6
- if ("refused" in o)
6
+ if (isRefusal(o))
7
7
  return refuse("x402/no-payable-option");
8
8
  return x402Chosen(ID, { required: o.required, accepted: o.accepted, now }, ref);
9
9
  },
@@ -13,7 +13,7 @@ export const x402ExactCcd = Object.freeze({
13
13
  if (!isObject(signature))
14
14
  return refuse("x402/signature-malformed");
15
15
  const signed = unsigned.complete(signature);
16
- if ("refused" in signed)
16
+ if (isRefusal(signed))
17
17
  return signed;
18
18
  return withPaymentIdentifier(signed, choiceOf(chosen)?.["required"], chosen.ref);
19
19
  },
@@ -8,7 +8,7 @@ export const x402ExactStellar = railPiece({
8
8
  pairing: PAIRING,
9
9
  namespace: "stellar",
10
10
  address: /^G[A-Z2-7]{55}$/,
11
- payer: null,
11
+ payer: "payer",
12
12
  now: false,
13
13
  inputs,
14
14
  revive: (c) => c,
@@ -1,15 +1,19 @@
1
1
  /**
2
2
  * `transact` is `confirm`, the agreement payment when the pairing's payment is not itself a public proof, the signer,
3
- * then `finish`.
3
+ * then `finish`. The agreement payment is signed only once the buyer's agent has approved it: the first call returns it
4
+ * in `approve`, and a second call with that payment as `approved` pays it and then the resource.
4
5
  */
5
6
  import type { AtrHash } from "@integraledger/lcp";
6
- import type { AgreementReceipt, Binding, Declined, Fetch, Presented, Signer, TransactOptions } from "./types.js";
7
+ import type { AgreementReceipt, Binding, Declined, Fetch, Presented, Signer, ToApprove, TransactOptions } from "./types.js";
7
8
  /**
8
- * `confirm`, then, for a pairing whose payment is not itself a public proof, the agreement payment and its receipt,
9
- * then the signer, then `finish`. On a decline before the signer the signer is never called. Where the build is itself
10
- * the payment the signer is not called; where the pairing has nothing for the buyer to sign, `signed` is null after the
11
- * comparison. When the agreement was paid first, `agreement` is its receipt. `landed` is `finish`'s, where it gives one.
12
- * Options holding anything but `inputs` and `agreementSigner` are declined before any fetch or signer call.
9
+ * `confirm`, then, for a pairing whose payment is not itself a public proof, the agreement, then the signer, then
10
+ * `finish`. Without `approved`, an agreement not yet recorded is returned as `approve`, the agreement payment for the
11
+ * agent to approve, and nothing is signed; with `approved`, that payment is signed and paid, and the resource's payment
12
+ * is signed only with the agreement's receipt in hand. On a decline before the signer the signer is never called. Where
13
+ * the build is itself the payment the signer is not called; where the pairing has nothing for the buyer to sign,
14
+ * `signed` is null after the comparison. `agreement` is the agreement's receipt, where the pairing needs one. `landed`
15
+ * is `finish`'s, where it gives one. `signal` ends the agreement exchange. Options holding anything but `inputs`,
16
+ * `agreementSigner`, `approved` and `signal` are declined before any fetch or signer call.
13
17
  */
14
18
  export declare function transact(doc: unknown, binding: Binding, signer: Signer, fetch: Fetch, options?: TransactOptions): Promise<{
15
19
  signed: Presented | null;
@@ -17,4 +21,4 @@ export declare function transact(doc: unknown, binding: Binding, signer: Signer,
17
21
  bytes: Uint8Array;
18
22
  h: AtrHash;
19
23
  agreement?: AgreementReceipt;
20
- } | Declined>;
24
+ } | ToApprove | Declined>;
package/dist/transact.js CHANGED
@@ -1,32 +1,30 @@
1
- import { agree } from "./agreement.js";
1
+ import { exchange } from "./agreement.js";
2
2
  import { confirm, declined, isObject, namespaceOf, pieceOf, signSteps, unsupported } from "./gate.js";
3
3
  /**
4
- * `confirm`, then, for a pairing whose payment is not itself a public proof, the agreement payment and its receipt,
5
- * then the signer, then `finish`. On a decline before the signer the signer is never called. Where the build is itself
6
- * the payment the signer is not called; where the pairing has nothing for the buyer to sign, `signed` is null after the
7
- * comparison. When the agreement was paid first, `agreement` is its receipt. `landed` is `finish`'s, where it gives one.
8
- * Options holding anything but `inputs` and `agreementSigner` are declined before any fetch or signer call.
4
+ * `confirm`, then, for a pairing whose payment is not itself a public proof, the agreement, then the signer, then
5
+ * `finish`. Without `approved`, an agreement not yet recorded is returned as `approve`, the agreement payment for the
6
+ * agent to approve, and nothing is signed; with `approved`, that payment is signed and paid, and the resource's payment
7
+ * is signed only with the agreement's receipt in hand. On a decline before the signer the signer is never called. Where
8
+ * the build is itself the payment the signer is not called; where the pairing has nothing for the buyer to sign,
9
+ * `signed` is null after the comparison. `agreement` is the agreement's receipt, where the pairing needs one. `landed`
10
+ * is `finish`'s, where it gives one. `signal` ends the agreement exchange. Options holding anything but `inputs`,
11
+ * `agreementSigner`, `approved` and `signal` are declined before any fetch or signer call.
9
12
  */
10
13
  export async function transact(doc, binding, signer, fetch, options) {
11
14
  if (pieceOf(binding) === undefined)
12
15
  return unsupported(binding);
16
+ const ns = namespaceOf(binding);
13
17
  if (!optionsOk(options))
14
- return declined("no-payable-option", `${namespaceOf(binding)}/input-malformed`);
15
- const given = options ?? {};
16
- const inputs = given.inputs ?? {};
17
- const agreementSigner = given.agreementSigner;
18
+ return declined("no-payable-option", `${ns}/input-malformed`);
19
+ const { inputs = {}, agreementSigner, approved, signal } = options ?? {};
18
20
  const confirmed = await confirm(doc, binding, signer.account, fetch, inputs);
19
21
  if ("decline" in confirmed)
20
22
  return confirmed;
21
23
  const { bytes, chosen } = confirmed;
22
24
  let receipt = {};
23
- if (confirmed.agreement !== undefined) {
24
- const agreed = await agree(confirmed.h, confirmed.agreement, agreementSigner ?? signer, fetch, {
25
- bytes,
26
- inputs,
27
- ns: namespaceOf(binding),
28
- });
29
- if ("decline" in agreed)
25
+ if (chosen.agreement !== undefined) {
26
+ const agreed = await exchange(bytes, chosen.agreement, agreementSigner ?? signer, fetch, { approved, inputs, signal }, ns);
27
+ if (!("receipt" in agreed))
30
28
  return agreed;
31
29
  receipt = { agreement: agreed.receipt };
32
30
  }
@@ -36,18 +34,23 @@ export async function transact(doc, binding, signer, fetch, options) {
36
34
  const landed = done.landed === undefined ? {} : { landed: done.landed };
37
35
  return { signed: done.signed, ...landed, bytes, h: done.h, ...receipt };
38
36
  }
39
- const OPTION_KEYS = ["inputs", "agreementSigner"];
37
+ const OPTION_KEYS = ["inputs", "agreementSigner", "approved", "signal"];
40
38
  /**
41
- * Whether `transact`'s options are absent, or an object holding only `inputs` (an object, or undefined) and
42
- * `agreementSigner` (an object with a `sign` function, or undefined).
39
+ * Whether `transact`'s options are absent, or an object holding only `inputs` (an object, or undefined),
40
+ * `agreementSigner` (an object with a `sign` function, or undefined), `approved` (an object, or undefined) and `signal`
41
+ * (an `AbortSignal`, or undefined).
43
42
  */
44
43
  function optionsOk(options) {
45
44
  if (options === undefined)
46
45
  return true;
47
46
  if (!isObject(options) || !Object.keys(options).every((k) => OPTION_KEYS.includes(k)))
48
47
  return false;
49
- const { inputs, agreementSigner } = options;
48
+ const { inputs, agreementSigner, approved, signal } = options;
50
49
  if (inputs !== undefined && !isObject(inputs))
51
50
  return false;
51
+ if (approved !== undefined && !isObject(approved))
52
+ return false;
53
+ if (signal !== undefined && !(signal instanceof AbortSignal))
54
+ return false;
52
55
  return agreementSigner === undefined || (isObject(agreementSigner) && typeof agreementSigner["sign"] === "function");
53
56
  }