@integraledger/terms 0.1.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.
Files changed (171) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +539 -0
  3. package/dist/agreement.d.ts +23 -0
  4. package/dist/agreement.js +264 -0
  5. package/dist/channels.d.ts +49 -0
  6. package/dist/channels.js +395 -0
  7. package/dist/gate.d.ts +69 -0
  8. package/dist/gate.js +347 -0
  9. package/dist/index.d.ts +5 -0
  10. package/dist/index.js +4 -0
  11. package/dist/pairings/ack-payment-request.d.ts +1 -0
  12. package/dist/pairings/ack-payment-request.js +12 -0
  13. package/dist/pairings/acp-checkout-delegated.d.ts +2 -0
  14. package/dist/pairings/acp-checkout-delegated.js +28 -0
  15. package/dist/pairings/acp-checkout-undelegated.d.ts +1 -0
  16. package/dist/pairings/acp-checkout-undelegated.js +11 -0
  17. package/dist/pairings/ap2-checkout-mandate.d.ts +2 -0
  18. package/dist/pairings/ap2-checkout-mandate.js +23 -0
  19. package/dist/pairings/batch.d.ts +29 -0
  20. package/dist/pairings/batch.js +83 -0
  21. package/dist/pairings/card-mastercard-vi-autonomous.d.ts +1 -0
  22. package/dist/pairings/card-mastercard-vi-autonomous.js +3 -0
  23. package/dist/pairings/card-mastercard-vi-immediate.d.ts +1 -0
  24. package/dist/pairings/card-mastercard-vi-immediate.js +3 -0
  25. package/dist/pairings/card-seller-reference.d.ts +1 -0
  26. package/dist/pairings/card-seller-reference.js +3 -0
  27. package/dist/pairings/card-visa-tap.d.ts +1 -0
  28. package/dist/pairings/card-visa-tap.js +3 -0
  29. package/dist/pairings/card.d.ts +7 -0
  30. package/dist/pairings/card.js +68 -0
  31. package/dist/pairings/common.d.ts +54 -0
  32. package/dist/pairings/common.js +134 -0
  33. package/dist/pairings/evm-x402.d.ts +3 -0
  34. package/dist/pairings/evm-x402.js +49 -0
  35. package/dist/pairings/index.d.ts +3 -0
  36. package/dist/pairings/index.js +134 -0
  37. package/dist/pairings/lightning.d.ts +17 -0
  38. package/dist/pairings/lightning.js +112 -0
  39. package/dist/pairings/lnbtc-request.d.ts +24 -0
  40. package/dist/pairings/lnbtc-request.js +175 -0
  41. package/dist/pairings/mpp-charge-card.d.ts +1 -0
  42. package/dist/pairings/mpp-charge-card.js +3 -0
  43. package/dist/pairings/mpp-charge-evm-authorization.d.ts +1 -0
  44. package/dist/pairings/mpp-charge-evm-authorization.js +3 -0
  45. package/dist/pairings/mpp-charge-evm-hash.d.ts +1 -0
  46. package/dist/pairings/mpp-charge-evm-hash.js +3 -0
  47. package/dist/pairings/mpp-charge-evm-permit2.d.ts +1 -0
  48. package/dist/pairings/mpp-charge-evm-permit2.js +3 -0
  49. package/dist/pairings/mpp-charge-evm-transaction.d.ts +1 -0
  50. package/dist/pairings/mpp-charge-evm-transaction.js +3 -0
  51. package/dist/pairings/mpp-charge-hedera.d.ts +23 -0
  52. package/dist/pairings/mpp-charge-hedera.js +137 -0
  53. package/dist/pairings/mpp-charge-nearintents.d.ts +2 -0
  54. package/dist/pairings/mpp-charge-nearintents.js +19 -0
  55. package/dist/pairings/mpp-charge-solana.d.ts +1 -0
  56. package/dist/pairings/mpp-charge-solana.js +25 -0
  57. package/dist/pairings/mpp-charge-stellar.d.ts +1 -0
  58. package/dist/pairings/mpp-charge-stellar.js +16 -0
  59. package/dist/pairings/mpp-charge-stripe.d.ts +1 -0
  60. package/dist/pairings/mpp-charge-stripe.js +3 -0
  61. package/dist/pairings/mpp-charge-tempo-memo.d.ts +9 -0
  62. package/dist/pairings/mpp-charge-tempo-memo.js +10 -0
  63. package/dist/pairings/mpp-charge-tempo-push.d.ts +12 -0
  64. package/dist/pairings/mpp-charge-tempo-push.js +21 -0
  65. package/dist/pairings/mpp-charge-usdc-evm.d.ts +1 -0
  66. package/dist/pairings/mpp-charge-usdc-evm.js +6 -0
  67. package/dist/pairings/mpp-charge-usdc-gateway.d.ts +2 -0
  68. package/dist/pairings/mpp-charge-usdc-gateway.js +33 -0
  69. package/dist/pairings/mpp-charge-usdc-solana.d.ts +1 -0
  70. package/dist/pairings/mpp-charge-usdc-solana.js +25 -0
  71. package/dist/pairings/mpp-charge-usdc-stacks.d.ts +1 -0
  72. package/dist/pairings/mpp-charge-usdc-stacks.js +17 -0
  73. package/dist/pairings/mpp-charge-xrpl.d.ts +1 -0
  74. package/dist/pairings/mpp-charge-xrpl.js +20 -0
  75. package/dist/pairings/mpp-confirm-only.d.ts +2 -0
  76. package/dist/pairings/mpp-confirm-only.js +21 -0
  77. package/dist/pairings/mpp-rails.d.ts +48 -0
  78. package/dist/pairings/mpp-rails.js +71 -0
  79. package/dist/pairings/mpp-session-evm.d.ts +1 -0
  80. package/dist/pairings/mpp-session-evm.js +3 -0
  81. package/dist/pairings/mpp-session-hedera.d.ts +2 -0
  82. package/dist/pairings/mpp-session-hedera.js +41 -0
  83. package/dist/pairings/mpp-session-solana.d.ts +1 -0
  84. package/dist/pairings/mpp-session-solana.js +60 -0
  85. package/dist/pairings/mpp-session-tempo.d.ts +1 -0
  86. package/dist/pairings/mpp-session-tempo.js +3 -0
  87. package/dist/pairings/mpp-session-xrpl.d.ts +1 -0
  88. package/dist/pairings/mpp-session-xrpl.js +42 -0
  89. package/dist/pairings/mpp-session.d.ts +5 -0
  90. package/dist/pairings/mpp-session.js +65 -0
  91. package/dist/pairings/mpp-subscription-stripe.d.ts +1 -0
  92. package/dist/pairings/mpp-subscription-stripe.js +6 -0
  93. package/dist/pairings/mpp-subscription-tempo.d.ts +2 -0
  94. package/dist/pairings/mpp-subscription-tempo.js +2 -0
  95. package/dist/pairings/mpp.d.ts +43 -0
  96. package/dist/pairings/mpp.js +194 -0
  97. package/dist/pairings/protocol-groups.d.ts +17 -0
  98. package/dist/pairings/protocol-groups.js +27 -0
  99. package/dist/pairings/ucp-booking-ap2-mandate.d.ts +1 -0
  100. package/dist/pairings/ucp-booking-ap2-mandate.js +3 -0
  101. package/dist/pairings/ucp-booking-unsigned.d.ts +1 -0
  102. package/dist/pairings/ucp-booking-unsigned.js +3 -0
  103. package/dist/pairings/ucp-checkout-ap2-mandate.d.ts +1 -0
  104. package/dist/pairings/ucp-checkout-ap2-mandate.js +3 -0
  105. package/dist/pairings/ucp-checkout-unsigned.d.ts +1 -0
  106. package/dist/pairings/ucp-checkout-unsigned.js +3 -0
  107. package/dist/pairings/ucp.d.ts +5 -0
  108. package/dist/pairings/ucp.js +35 -0
  109. package/dist/pairings/x402-account-rails.d.ts +25 -0
  110. package/dist/pairings/x402-account-rails.js +52 -0
  111. package/dist/pairings/x402-auth-capture-eip155-eip3009.d.ts +1 -0
  112. package/dist/pairings/x402-auth-capture-eip155-eip3009.js +3 -0
  113. package/dist/pairings/x402-auth-capture-eip155-permit2.d.ts +1 -0
  114. package/dist/pairings/x402-auth-capture-eip155-permit2.js +3 -0
  115. package/dist/pairings/x402-batch-settlement-cloudflare.d.ts +2 -0
  116. package/dist/pairings/x402-batch-settlement-cloudflare.js +21 -0
  117. package/dist/pairings/x402-batch-settlement-eip155.d.ts +2 -0
  118. package/dist/pairings/x402-batch-settlement-eip155.js +32 -0
  119. package/dist/pairings/x402-batch-settlement-solana.d.ts +2 -0
  120. package/dist/pairings/x402-batch-settlement-solana.js +55 -0
  121. package/dist/pairings/x402-exact-algorand.d.ts +1 -0
  122. package/dist/pairings/x402-exact-algorand.js +37 -0
  123. package/dist/pairings/x402-exact-aptos.d.ts +1 -0
  124. package/dist/pairings/x402-exact-aptos.js +9 -0
  125. package/dist/pairings/x402-exact-cardano.d.ts +1 -0
  126. package/dist/pairings/x402-exact-cardano.js +7 -0
  127. package/dist/pairings/x402-exact-casper.d.ts +2 -0
  128. package/dist/pairings/x402-exact-casper.js +21 -0
  129. package/dist/pairings/x402-exact-ccd.d.ts +2 -0
  130. package/dist/pairings/x402-exact-ccd.js +20 -0
  131. package/dist/pairings/x402-exact-eip155-eip3009.d.ts +1 -0
  132. package/dist/pairings/x402-exact-eip155-eip3009.js +3 -0
  133. package/dist/pairings/x402-exact-eip155-erc7710-salt.d.ts +1 -0
  134. package/dist/pairings/x402-exact-eip155-erc7710-salt.js +3 -0
  135. package/dist/pairings/x402-exact-eip155-erc7710.d.ts +1 -0
  136. package/dist/pairings/x402-exact-eip155-erc7710.js +3 -0
  137. package/dist/pairings/x402-exact-eip155-permit2.d.ts +1 -0
  138. package/dist/pairings/x402-exact-eip155-permit2.js +3 -0
  139. package/dist/pairings/x402-exact-hedera-transfer-executor.d.ts +1 -0
  140. package/dist/pairings/x402-exact-hedera-transfer-executor.js +23 -0
  141. package/dist/pairings/x402-exact-hedera.d.ts +3 -0
  142. package/dist/pairings/x402-exact-hedera.js +46 -0
  143. package/dist/pairings/x402-exact-near.d.ts +2 -0
  144. package/dist/pairings/x402-exact-near.js +34 -0
  145. package/dist/pairings/x402-exact-polkadot-lcp-assets-remark.d.ts +2 -0
  146. package/dist/pairings/x402-exact-polkadot-lcp-assets-remark.js +20 -0
  147. package/dist/pairings/x402-exact-solana.d.ts +11 -0
  148. package/dist/pairings/x402-exact-solana.js +36 -0
  149. package/dist/pairings/x402-exact-starknet.d.ts +2 -0
  150. package/dist/pairings/x402-exact-starknet.js +20 -0
  151. package/dist/pairings/x402-exact-stellar.d.ts +1 -0
  152. package/dist/pairings/x402-exact-stellar.js +17 -0
  153. package/dist/pairings/x402-exact-sui.d.ts +1 -0
  154. package/dist/pairings/x402-exact-sui.js +10 -0
  155. package/dist/pairings/x402-exact-tron-lcp-trc20-memo.d.ts +2 -0
  156. package/dist/pairings/x402-exact-tron-lcp-trc20-memo.js +45 -0
  157. package/dist/pairings/x402-exact-tvm.d.ts +2 -0
  158. package/dist/pairings/x402-exact-tvm.js +35 -0
  159. package/dist/pairings/x402-exact-xrpl.d.ts +1 -0
  160. package/dist/pairings/x402-exact-xrpl.js +27 -0
  161. package/dist/pairings/x402-rail.d.ts +31 -0
  162. package/dist/pairings/x402-rail.js +65 -0
  163. package/dist/pairings/x402-upto-eip155-permit2.d.ts +1 -0
  164. package/dist/pairings/x402-upto-eip155-permit2.js +3 -0
  165. package/dist/pairings/x402-upto-solana.d.ts +1 -0
  166. package/dist/pairings/x402-upto-solana.js +42 -0
  167. package/dist/transact.d.ts +20 -0
  168. package/dist/transact.js +53 -0
  169. package/dist/types.d.ts +169 -0
  170. package/dist/types.js +2 -0
  171. package/package.json +64 -0
package/dist/gate.js ADDED
@@ -0,0 +1,347 @@
1
+ /**
2
+ * The buyer gate. `confirm` reads the offer, fetches the ATR from the seller's link, compares its SHA-256 with the
3
+ * advertised hash, and only on a match builds the signing request with the hash it computed. `finish` completes the
4
+ * payment with the signature and returns it only when what was signed carries the hash of these bytes, or, for a pairing
5
+ * whose proof is the agreement payment, completes it without that reading. `check` confirms a payment held later against
6
+ * kept bytes.
7
+ */
8
+ import { hash, hashEquals, isHttpsLink, isOtherSchemeLink } from "@integraledger/lcp";
9
+ import { PIECES } from "./pairings/index.js";
10
+ import { MAX_ATR_BYTES, } from "./types.js";
11
+ const steps = (binding) => binding;
12
+ /** A build refusal that means the pairing has nothing for the buyer to sign: the gate confirms only. */
13
+ const NOTHING_TO_SIGN = /\/(no-signed-place|nothing-to-sign)$/;
14
+ /** The most signer calls one payment takes: a funding and then a voucher. */
15
+ const MAX_STEPS = 2;
16
+ const FETCH_DEADLINE_MS = 10_000;
17
+ const REF_BYTES = 24;
18
+ const BASE64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
19
+ const DECIMAL = /^[0-9]+$/;
20
+ export function declined(code, detail) {
21
+ return { decline: { code, detail } };
22
+ }
23
+ function isRefusal(v) {
24
+ return typeof v === "object" && v !== null && v.refused === true;
25
+ }
26
+ export function isObject(v) {
27
+ return typeof v === "object" && v !== null && !Array.isArray(v);
28
+ }
29
+ /** The pairing's namespace: its id up to the first `/`. */
30
+ export function namespaceOf(binding) {
31
+ return String(binding.id).split("/")[0];
32
+ }
33
+ /** The protocol package's refusal code for a link that is not an https link, in the pairing's namespace. */
34
+ function linkRefusal(binding, link) {
35
+ return `${namespaceOf(binding)}/${isOtherSchemeLink(link) ? "link-not-https" : "legal-context-malformed"}`;
36
+ }
37
+ /** Whether the pairing's payment is itself a public proof of the hash, so the offer's agreement URL is not paid. */
38
+ function isPublicProof(binding) {
39
+ const pattern = isObject(binding) ? binding.pattern : undefined;
40
+ return isObject(pattern) && pattern["publicProof"] === true;
41
+ }
42
+ export function pieceOf(binding) {
43
+ const id = isObject(binding) ? binding.id : undefined;
44
+ return typeof id === "string" ? PIECES.get(id) : undefined;
45
+ }
46
+ export function unsupported(binding) {
47
+ const id = isObject(binding) ? binding.id : undefined;
48
+ return declined("pairing-not-supported", `The gate has no buyer piece for the pairing ${String(id)}.`);
49
+ }
50
+ const tooLarge = () => declined("atr-too-large", `The ATR is larger than ${MAX_ATR_BYTES} bytes.`);
51
+ /** 24 random bytes as unpadded base64url: 32 characters from `[A-Za-z0-9_-]`. */
52
+ export function newRef() {
53
+ const b = crypto.getRandomValues(new Uint8Array(REF_BYTES));
54
+ let s = "";
55
+ for (let i = 0; i < b.length; i += 3) {
56
+ const n = (b[i] << 16) | (b[i + 1] << 8) | b[i + 2];
57
+ s += BASE64URL[(n >> 18) & 63] + BASE64URL[(n >> 12) & 63] + BASE64URL[(n >> 6) & 63] + BASE64URL[n & 63];
58
+ }
59
+ return s;
60
+ }
61
+ /** Whether an answer to a `redirect: "manual"` request is a redirect: a 3xx status, or the opaque form a browser gives. */
62
+ export function redirected(response) {
63
+ return response.type === "opaqueredirect" || (response.status >= 300 && response.status <= 399);
64
+ }
65
+ /**
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
68
+ * bound cancels the body. The bytes are returned exactly as received.
69
+ */
70
+ async function fetchAtr(fetch, link) {
71
+ const controller = new AbortController();
72
+ const timer = setTimeout(() => controller.abort(new DOMException("The ATR fetch passed its deadline.", "TimeoutError")), FETCH_DEADLINE_MS);
73
+ const deadline = new Promise((_, reject) => {
74
+ controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true });
75
+ });
76
+ deadline.catch(() => undefined);
77
+ let body = null;
78
+ let reader;
79
+ let whole = false;
80
+ try {
81
+ const response = await Promise.race([
82
+ fetch(link, { method: "GET", redirect: "manual", signal: controller.signal }),
83
+ deadline,
84
+ ]);
85
+ body = response.body;
86
+ if (redirected(response))
87
+ return declined("atr-unfetchable", "The link answered with a redirect.");
88
+ if (response.status !== 200)
89
+ return declined("atr-unfetchable", `The link answered status ${response.status}.`);
90
+ const declared = response.headers.get("content-length")?.trim();
91
+ if (declared !== undefined && DECIMAL.test(declared) && Number(declared) > MAX_ATR_BYTES)
92
+ return tooLarge();
93
+ if (body === null) {
94
+ whole = true;
95
+ return new Uint8Array(0);
96
+ }
97
+ reader = body.getReader();
98
+ const chunks = [];
99
+ let total = 0;
100
+ for (;;) {
101
+ const next = await Promise.race([reader.read(), deadline]);
102
+ if (next.done)
103
+ break;
104
+ if (!(next.value instanceof Uint8Array))
105
+ return declined("atr-unfetchable", "The link served a non-byte chunk.");
106
+ total += next.value.length;
107
+ if (total > MAX_ATR_BYTES)
108
+ return tooLarge();
109
+ chunks.push(next.value);
110
+ }
111
+ whole = true;
112
+ const bytes = new Uint8Array(total);
113
+ let at = 0;
114
+ for (const c of chunks) {
115
+ bytes.set(c, at);
116
+ at += c.length;
117
+ }
118
+ return bytes;
119
+ }
120
+ catch {
121
+ return declined("atr-unfetchable", "The ATR could not be fetched from the link.");
122
+ }
123
+ finally {
124
+ clearTimeout(timer);
125
+ if (!whole) {
126
+ cancel(reader ?? body);
127
+ controller.abort();
128
+ }
129
+ }
130
+ }
131
+ /** Cancels a body or its reader, ignoring whatever the cancellation answers. */
132
+ function cancel(s) {
133
+ if (s === null || s === undefined)
134
+ return;
135
+ try {
136
+ s.cancel().catch(() => undefined);
137
+ }
138
+ catch {
139
+ // A body that cannot be cancelled is left to the fetch's own abort.
140
+ }
141
+ }
142
+ /**
143
+ * Reads the offer, chooses the option, fetches the ATR and compares its SHA-256 with the advertised hash. Only on a
144
+ * 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.
146
+ */
147
+ export async function confirm(doc, binding, account, fetch, inputs = {}) {
148
+ const piece = pieceOf(binding);
149
+ if (piece === undefined)
150
+ return unsupported(binding);
151
+ const b = steps(binding);
152
+ const read = b.read(doc);
153
+ if (isRefusal(read))
154
+ return declined("offer-unreadable", read.code);
155
+ const agreement = isPublicProof(binding) ? undefined : read.agreement;
156
+ if (agreement !== undefined && typeof agreement !== "string") {
157
+ return declined("offer-unreadable", "The offer names an agreement URL that is not a string.");
158
+ }
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);
162
+ if (!isHttpsLink(read.link))
163
+ return declined("link-not-https", linkRefusal(binding, read.link));
164
+ const bytes = await fetchAtr(fetch, read.link);
165
+ if (!(bytes instanceof Uint8Array))
166
+ return bytes;
167
+ const computed = await hash(bytes);
168
+ if (!hashEquals(read.h, computed)) {
169
+ return declined("hash-mismatch", "The bytes the link served do not hash to the advertised ATR hash.");
170
+ }
171
+ if (!isPublicProof(binding) && agreement === undefined) {
172
+ return declined("agreement-not-offered", "The pairing's payment carries no public proof and the offer names no agreement URL.");
173
+ }
174
+ const unsigned = await buildWith(piece, b, chosen, computed, bytes);
175
+ const withAgreement = agreement === undefined ? {} : { agreement };
176
+ if (isRefusal(unsigned)) {
177
+ if (NOTHING_TO_SIGN.test(unsigned.code))
178
+ return { chosen, request: null, bytes, h: computed, ...withAgreement };
179
+ return declined("offer-unreadable", unsigned.code);
180
+ }
181
+ const request = piece.request(unsigned);
182
+ if (isRefusal(request))
183
+ return declined("offer-unreadable", request.code);
184
+ return { chosen, request, bytes, h: computed, ...withAgreement };
185
+ }
186
+ /** The pairing's build over the choice the piece revives from `chosen`. */
187
+ async function buildWith(piece, b, chosen, h, bytes) {
188
+ const choice = piece.choice(chosen, bytes);
189
+ if (isRefusal(choice))
190
+ return choice;
191
+ try {
192
+ return await (piece.build !== undefined ? piece.build(choice, h) : b.build(choice, h));
193
+ }
194
+ catch {
195
+ return { refused: true, code: `${b.id.split("/")[0]}/build-failed` };
196
+ }
197
+ }
198
+ /**
199
+ * Rebuilds the payment from `chosen` and the bytes, joins the signer's answer, and returns the payment only when what
200
+ * was signed carries the hash of these bytes. For a pairing whose payment is not a public proof and whose `bound` finds
201
+ * no signed place for the hash, the proof is the agreement payment, and the completed payment is returned as it is.
202
+ * Where the signer moved the payment itself, a decline keeps it as `moved`. Where the completion carried the landed
203
+ * receipt `bound` reads and the payment sent leaves it out, `landed` is returned beside the payment as JSON, each integer
204
+ * a decimal string, so `check` and `openChannel` can later read the payment with it.
205
+ */
206
+ export async function finish(bytes, chosen, signature, binding) {
207
+ const piece = pieceOf(binding);
208
+ if (piece === undefined)
209
+ return unsupported(binding);
210
+ const b = steps(binding);
211
+ if (bytes.length > MAX_ATR_BYTES)
212
+ return tooLarge();
213
+ if (!isObject(chosen) || !isObject(chosen.choice)) {
214
+ return declined("offer-unreadable", "The chosen payment carries no choice to build from.");
215
+ }
216
+ if (chosen.pairing !== b.id) {
217
+ return declined("pairing-not-supported", `The chosen payment is not for the pairing ${b.id}.`);
218
+ }
219
+ const h = await hash(bytes);
220
+ const unsigned = await buildWith(piece, b, chosen, h, bytes);
221
+ if (isRefusal(unsigned))
222
+ return declined("offer-unreadable", unsigned.code);
223
+ const moves = signature !== null && movesWith(piece, unsigned);
224
+ const keep = (d, signed) => (moves ? { ...d, moved: { signed, bytes, h } } : d);
225
+ let signed;
226
+ try {
227
+ signed = await piece.complete(unsigned, signature, chosen);
228
+ }
229
+ catch {
230
+ return keep(declined("signed-not-bound", "The signer's answer did not complete the payment."), signature);
231
+ }
232
+ if (isRefusal(signed))
233
+ return keep(declined("signed-not-bound", signed.code), signature);
234
+ if (isNext(signed))
235
+ return { next: signed.next, h };
236
+ const sent = piece.sent !== undefined ? piece.sent(signed) : signed;
237
+ const inside = await boundOf(b, signed);
238
+ const onAgreement = !isPublicProof(binding) && isRefusal(inside) && NOTHING_TO_SIGN.test(inside.code);
239
+ if (!onAgreement && (isRefusal(inside) || !hashEquals(inside, h))) {
240
+ return keep(declined("signed-not-bound", "What was signed does not carry the hash of these bytes."), sent);
241
+ }
242
+ const landed = sent !== signed && isObject(signed) ? jsonSafe(signed.landed) : undefined;
243
+ return landed === undefined ? { signed: sent, h } : { signed: sent, landed, h };
244
+ }
245
+ /** A value as JSON, each bigint as its decimal string; undefined when it is undefined or has no JSON form. */
246
+ function jsonSafe(v) {
247
+ if (v === undefined)
248
+ return undefined;
249
+ try {
250
+ const text = JSON.stringify(v, (_k, x) => (typeof x === "bigint" ? x.toString() : x));
251
+ return text === undefined ? undefined : JSON.parse(text);
252
+ }
253
+ catch {
254
+ return undefined;
255
+ }
256
+ }
257
+ /** Whether the signer, handed the build's first request, moves the payment itself. */
258
+ function movesWith(piece, unsigned) {
259
+ if (piece.moves === undefined)
260
+ return false;
261
+ const request = piece.request(unsigned);
262
+ return request !== null && !isRefusal(request) && piece.moves(request);
263
+ }
264
+ /** The binding's `bound`, with a throw read as a refusal. */
265
+ async function boundOf(b, presented) {
266
+ try {
267
+ return await b.bound(presented);
268
+ }
269
+ catch {
270
+ return { refused: true, code: "bound-failed" };
271
+ }
272
+ }
273
+ /** Confirms that a payment held later carries, inside what was signed, the hash of the kept bytes. */
274
+ export async function check(bytes, presented, binding) {
275
+ if (bytes.length > MAX_ATR_BYTES)
276
+ return tooLarge();
277
+ const h = await hash(bytes);
278
+ const b = await boundOf(steps(binding), presented);
279
+ if (isRefusal(b) || !hashEquals(b, h)) {
280
+ return declined("signed-not-bound", "The payment does not carry the hash of these bytes.");
281
+ }
282
+ return { h };
283
+ }
284
+ /**
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`.
287
+ */
288
+ export async function pay(binding, read, doc, signer, inputs, bytes) {
289
+ const piece = pieceOf(binding);
290
+ if (piece === undefined)
291
+ 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
+ const h = await hash(bytes);
297
+ const unsigned = await buildWith(piece, b, chosen, h, bytes);
298
+ if (isRefusal(unsigned)) {
299
+ if (NOTHING_TO_SIGN.test(unsigned.code))
300
+ return { signed: null, h };
301
+ return declined("offer-unreadable", unsigned.code);
302
+ }
303
+ const request = piece.request(unsigned);
304
+ if (isRefusal(request))
305
+ return declined("offer-unreadable", request.code);
306
+ return signSteps(binding, chosen, request, signer, bytes, h);
307
+ }
308
+ /**
309
+ * The signer, once per step in order, then `finish` over its answers. A request of null is a build that is itself the
310
+ * payment: `finish` completes it with no signer call.
311
+ */
312
+ export async function signSteps(binding, chosen, first, signer, bytes, h) {
313
+ if (first === null) {
314
+ const whole = await finish(bytes, chosen, null, binding);
315
+ if ("decline" in whole && NOTHING_TO_SIGN.test(whole.decline.detail))
316
+ return { signed: null, h };
317
+ if ("decline" in whole)
318
+ return whole;
319
+ if ("next" in whole)
320
+ return declined("signed-not-bound", "The pairing asked for a signature it did not request.");
321
+ return whole;
322
+ }
323
+ const piece = pieceOf(binding);
324
+ const moves = piece.moves !== undefined && piece.moves(first);
325
+ const answers = [];
326
+ let request = first;
327
+ for (let step = 0; step < MAX_STEPS; step++) {
328
+ try {
329
+ answers.push(await signer.sign(request));
330
+ }
331
+ catch {
332
+ const d = declined("signer-failed", "The signer did not sign.");
333
+ return moves && answers.length > 0 ? { ...d, moved: { signed: answers.length === 1 ? answers[0] : answers, bytes, h } } : d;
334
+ }
335
+ const finished = await finish(bytes, chosen, answers.length === 1 ? answers[0] : answers, binding);
336
+ if ("decline" in finished)
337
+ return finished;
338
+ if (!("next" in finished))
339
+ return finished;
340
+ request = finished.next;
341
+ }
342
+ const d = declined("signed-not-bound", "The pairing asked for more signatures than a payment takes.");
343
+ return moves ? { ...d, moved: { signed: answers, bytes, h } } : d;
344
+ }
345
+ function isNext(v) {
346
+ return isObject(v) && isObject(v["next"]);
347
+ }
@@ -0,0 +1,5 @@
1
+ export { agree } from "./agreement.js";
2
+ export { openChannel, recordCharge, within, type ChannelHold } from "./channels.js";
3
+ export { check, confirm, finish } from "./gate.js";
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";
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { agree } from "./agreement.js";
2
+ export { openChannel, recordCharge, within } from "./channels.js";
3
+ export { check, confirm, finish } from "./gate.js";
4
+ export { transact } from "./transact.js";
@@ -0,0 +1 @@
1
+ export declare const ackPaymentRequest: import("../types.js").BuyerPiece;
@@ -0,0 +1,12 @@
1
+ import { accountOf, isObject, refuse } from "./common.js";
2
+ import { confirmOnlyPiece } from "./protocol-groups.js";
3
+ export const ackPaymentRequest = confirmOnlyPiece("ack/payment-request", (read, account, _inputs) => {
4
+ const a = accountOf(account);
5
+ const options = isObject(read.offer) ? read.offer["options"] : undefined;
6
+ if (a === undefined || !Array.isArray(options))
7
+ return refuse("ack/no-payable-option");
8
+ const option = options.find((o) => isObject(o) && o["network"] === a.network);
9
+ if (option === undefined)
10
+ return refuse("ack/no-payable-option");
11
+ return { option: option };
12
+ });
@@ -0,0 +1,2 @@
1
+ import type { BuyerPiece } from "../types.js";
2
+ export declare const acpCheckoutDelegated: BuyerPiece;
@@ -0,0 +1,28 @@
1
+ import { inputsOf, isObject, isRefusal, refuse } from "./common.js";
2
+ import { objectChoice, unnamedBuyer } from "./protocol-groups.js";
3
+ const PAIRING = "acp/checkout/delegated";
4
+ const ALLOWANCE_INPUTS = { max_amount: "uint", currency: "string", merchant_id: "string", expires_at: "string" };
5
+ export const acpCheckoutDelegated = Object.freeze({
6
+ choose(read, account, inputs, _now, ref) {
7
+ const unnamed = unnamedBuyer(account, "acp");
8
+ if (unnamed !== undefined)
9
+ return unnamed;
10
+ const session = isObject(read.offer) ? read.offer["session"] : undefined;
11
+ if (!isObject(session))
12
+ return refuse("acp/no-payable-option");
13
+ const values = inputsOf(inputs, PAIRING, ALLOWANCE_INPUTS);
14
+ if (isRefusal(values))
15
+ return values;
16
+ return { pairing: PAIRING, choice: { session: session, ...values }, ref };
17
+ },
18
+ choice: (chosen) => objectChoice(chosen, "acp"),
19
+ request: (unsigned) => ({
20
+ kind: "acp-allowance",
21
+ allowance: unsigned.allowance,
22
+ }),
23
+ async complete(unsigned, signature) {
24
+ if (!isObject(signature))
25
+ return refuse("acp/signature-malformed");
26
+ return unsigned.complete(signature);
27
+ },
28
+ });
@@ -0,0 +1 @@
1
+ export declare const acpCheckoutUndelegated: import("../types.js").BuyerPiece;
@@ -0,0 +1,11 @@
1
+ import { isObject, refuse } from "./common.js";
2
+ import { confirmOnlyPiece, unnamedBuyer } from "./protocol-groups.js";
3
+ export const acpCheckoutUndelegated = confirmOnlyPiece("acp/checkout/undelegated", (read, account, _inputs) => {
4
+ const unnamed = unnamedBuyer(account, "acp");
5
+ if (unnamed !== undefined)
6
+ return unnamed;
7
+ const session = isObject(read.offer) ? read.offer["session"] : undefined;
8
+ if (!isObject(session))
9
+ return refuse("acp/no-payable-option");
10
+ return { session: session };
11
+ });
@@ -0,0 +1,2 @@
1
+ import type { BuyerPiece } from "../types.js";
2
+ export declare const ap2CheckoutMandate: BuyerPiece;
@@ -0,0 +1,23 @@
1
+ import { isObject, refuse } from "./common.js";
2
+ import { objectChoice, unnamedBuyer } from "./protocol-groups.js";
3
+ const PAIRING = "ap2/checkout-mandate";
4
+ export const ap2CheckoutMandate = Object.freeze({
5
+ choose(read, account, _inputs, _now, ref) {
6
+ const unnamed = unnamedBuyer(account, "ap2");
7
+ if (unnamed !== undefined)
8
+ return unnamed;
9
+ if (!isObject(read.offer))
10
+ return refuse("ap2/no-payable-option");
11
+ return { pairing: PAIRING, choice: read.offer, ref };
12
+ },
13
+ choice: (chosen) => objectChoice(chosen, "ap2"),
14
+ request: (unsigned) => ({
15
+ kind: "ap2-checkout-mandate",
16
+ content: unsigned.content,
17
+ }),
18
+ async complete(unsigned, signature) {
19
+ if (typeof signature !== "string" || signature === "")
20
+ return refuse("ap2/signature-malformed");
21
+ return unsigned.complete(signature);
22
+ },
23
+ });
@@ -0,0 +1,29 @@
1
+ /**
2
+ * What the x402 `batch-settlement` pieces share: the deposit the buyer commits, the batch signing request exactly as
3
+ * built, and the payment the list of answers completes, with the payment
4
+ * identifier appended where the challenge advertises it.
5
+ */
6
+ import type { Json, Refusal } from "@integraledger/lcp";
7
+ import type { PaymentRequirements } from "@integraledger/lcp/x402";
8
+ import type { Chosen, Inputs, Presented, Signature, SigningRequest } from "../types.js";
9
+ /**
10
+ * The deposit: `extra.minDeposit` when the option carries one, else the buyer's `deposit` input. A deposit above the
11
+ * buyer's `maxDeposit` input, when given, is refused.
12
+ */
13
+ export declare function depositOf(accepted: PaymentRequirements, inputs: Inputs): string | Refusal;
14
+ /** `n` bytes from the platform's CSPRNG. */
15
+ export declare function randomBytes(n: number): Uint8Array;
16
+ /** 32 random bytes as `0x` hex. */
17
+ export declare function randomSalt32(): string;
18
+ /** 8 random bytes as a decimal u64. */
19
+ export declare function randomU64(): string;
20
+ /** The build's requests as one `batch` request, signed in order. */
21
+ export declare function batchRequest(unsigned: unknown): SigningRequest;
22
+ /** The payment the list of answers, one per request in order, completes. */
23
+ export declare function batchComplete(unsigned: unknown, signature: Signature, chosen: Chosen): Promise<Presented | Refusal>;
24
+ /** The choice with the named decimal members as bigints, or a refusal when one is not a decimal. */
25
+ export declare function reviveDecimals(chosen: Chosen, keys: readonly string[]): Record<string, unknown> | Refusal;
26
+ /** The optional inputs of the given kinds that are present, or the refusal naming the first malformed one. */
27
+ export declare function optionalInputs(inputs: Inputs, ns: string, spec: {
28
+ readonly [k: string]: RegExp | "object";
29
+ }): Record<string, Json> | Refusal;
@@ -0,0 +1,83 @@
1
+ import { bigintOf, choiceOf, hexOf, isObject, refuse, withPaymentIdentifier } from "./common.js";
2
+ /**
3
+ * The deposit: `extra.minDeposit` when the option carries one, else the buyer's `deposit` input. A deposit above the
4
+ * buyer's `maxDeposit` input, when given, is refused.
5
+ */
6
+ export function depositOf(accepted, inputs) {
7
+ const min = isObject(accepted.extra) ? accepted.extra["minDeposit"] : undefined;
8
+ const deposit = min !== undefined ? bigintOf(min) : bigintOf(inputs["deposit"]);
9
+ if (deposit === undefined)
10
+ return refuse(min !== undefined ? "x402/option-malformed" : "x402/input-missing");
11
+ if (inputs["maxDeposit"] !== undefined) {
12
+ const max = bigintOf(inputs["maxDeposit"]);
13
+ if (max === undefined)
14
+ return refuse("x402/input-missing");
15
+ if (deposit > max)
16
+ return refuse("x402/deposit-above-maximum");
17
+ }
18
+ return deposit.toString();
19
+ }
20
+ /** `n` bytes from the platform's CSPRNG. */
21
+ export function randomBytes(n) {
22
+ return crypto.getRandomValues(new Uint8Array(n));
23
+ }
24
+ /** 32 random bytes as `0x` hex. */
25
+ export function randomSalt32() {
26
+ return hexOf(randomBytes(32));
27
+ }
28
+ /** 8 random bytes as a decimal u64. */
29
+ export function randomU64() {
30
+ let n = 0n;
31
+ for (const b of randomBytes(8))
32
+ n = (n << 8n) | BigInt(b);
33
+ return n.toString();
34
+ }
35
+ /** The build's requests as one `batch` request, signed in order. */
36
+ export function batchRequest(unsigned) {
37
+ const u = unsigned;
38
+ return {
39
+ kind: "batch",
40
+ requests: u.requests,
41
+ };
42
+ }
43
+ /** The payment the list of answers, one per request in order, completes. */
44
+ export async function batchComplete(unsigned, signature, chosen) {
45
+ const u = unsigned;
46
+ if (!Array.isArray(signature) || signature.length !== u.requests.length || !signature.every((s) => typeof s === "string")) {
47
+ return refuse("x402/signature-malformed");
48
+ }
49
+ const signed = u.complete(signature);
50
+ if ("refused" in signed)
51
+ return signed;
52
+ return withPaymentIdentifier(signed, choiceOf(chosen)?.["required"], chosen.ref);
53
+ }
54
+ /** The choice with the named decimal members as bigints, or a refusal when one is not a decimal. */
55
+ export function reviveDecimals(chosen, keys) {
56
+ const c = choiceOf(chosen);
57
+ if (c === undefined)
58
+ return refuse("x402/choice-malformed");
59
+ const out = { ...c };
60
+ for (const k of keys) {
61
+ if (c[k] === undefined)
62
+ continue;
63
+ const v = bigintOf(c[k]);
64
+ if (v === undefined)
65
+ return refuse("x402/choice-malformed");
66
+ out[k] = v;
67
+ }
68
+ return out;
69
+ }
70
+ /** The optional inputs of the given kinds that are present, or the refusal naming the first malformed one. */
71
+ export function optionalInputs(inputs, ns, spec) {
72
+ const out = {};
73
+ for (const [k, kind] of Object.entries(spec)) {
74
+ const v = inputs[k];
75
+ if (v === undefined)
76
+ continue;
77
+ const ok = kind === "object" ? isObject(v) : typeof v === "string" && kind.test(v);
78
+ if (!ok)
79
+ return refuse(`${ns}/input-missing`);
80
+ out[k] = v;
81
+ }
82
+ return out;
83
+ }
@@ -0,0 +1 @@
1
+ export declare const cardMastercardViAutonomous: import("../types.js").BuyerPiece;
@@ -0,0 +1,3 @@
1
+ /** The buyer piece for `card/mastercard-vi/autonomous`: the checkout mandate for the agent's L3b. */
2
+ import { viPiece } from "./card.js";
3
+ export const cardMastercardViAutonomous = viPiece("card/mastercard-vi/autonomous", "autonomous");
@@ -0,0 +1 @@
1
+ export declare const cardMastercardViImmediate: import("../types.js").BuyerPiece;
@@ -0,0 +1,3 @@
1
+ /** The buyer piece for `card/mastercard-vi/immediate`: the checkout mandate for the user's L2. */
2
+ import { viPiece } from "./card.js";
3
+ export const cardMastercardViImmediate = viPiece("card/mastercard-vi/immediate", "immediate");
@@ -0,0 +1 @@
1
+ export declare const cardSellerReference: import("../types.js").BuyerPiece;
@@ -0,0 +1,3 @@
1
+ /** The buyer piece for `card/seller-reference`: nothing the buyer signs carries the hash, so the gate confirms only. */
2
+ import { sellerReferencePiece } from "./card.js";
3
+ export const cardSellerReference = sellerReferencePiece("card/seller-reference");
@@ -0,0 +1 @@
1
+ export declare const cardVisaTap: import("../types.js").BuyerPiece;
@@ -0,0 +1,3 @@
1
+ /** The buyer piece for `card/visa-tap`: the `lcp-hash` field for the agent's `agent-payer-auth` signature. */
2
+ import { tapPiece } from "./card.js";
3
+ export const cardVisaTap = tapPiece("card/visa-tap");
@@ -0,0 +1,7 @@
1
+ import type { BuyerPiece } from "../types.js";
2
+ /** The TAP field exactly as built, for the agent's signer to add and list in its `agent-payer-auth` signature. */
3
+ export declare function tapPiece(pairing: string): BuyerPiece;
4
+ /** The checkout mandate exactly as built, for the wallet (Immediate) or the agent (Autonomous) to sign. */
5
+ export declare function viPiece(pairing: string, mode: "immediate" | "autonomous"): BuyerPiece;
6
+ /** The plain card checkout: the gate confirms only. */
7
+ export declare function sellerReferencePiece(pairing: string): BuyerPiece;