@avow-finance/spec 0.0.0-stage → 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 (179) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +119 -2
  3. package/dist/agent-connect.d.ts +82 -0
  4. package/dist/agent-connect.d.ts.map +1 -0
  5. package/dist/agent-connect.js +91 -0
  6. package/dist/agent-connect.js.map +1 -0
  7. package/dist/agent-session.d.ts +791 -0
  8. package/dist/agent-session.d.ts.map +1 -0
  9. package/dist/agent-session.js +176 -0
  10. package/dist/agent-session.js.map +1 -0
  11. package/dist/ap2.d.ts +79 -0
  12. package/dist/ap2.d.ts.map +1 -0
  13. package/dist/ap2.js +151 -0
  14. package/dist/ap2.js.map +1 -0
  15. package/dist/api-request.d.ts +144 -0
  16. package/dist/api-request.d.ts.map +1 -0
  17. package/dist/api-request.js +246 -0
  18. package/dist/api-request.js.map +1 -0
  19. package/dist/api.d.ts +288 -0
  20. package/dist/api.d.ts.map +1 -0
  21. package/dist/api.js +332 -0
  22. package/dist/api.js.map +1 -0
  23. package/dist/canonical.d.ts +22 -0
  24. package/dist/canonical.d.ts.map +1 -0
  25. package/dist/canonical.js +66 -0
  26. package/dist/canonical.js.map +1 -0
  27. package/dist/commitment-card.d.ts +78 -0
  28. package/dist/commitment-card.d.ts.map +1 -0
  29. package/dist/commitment-card.js +224 -0
  30. package/dist/commitment-card.js.map +1 -0
  31. package/dist/commitment.d.ts +185 -0
  32. package/dist/commitment.d.ts.map +1 -0
  33. package/dist/commitment.js +148 -0
  34. package/dist/commitment.js.map +1 -0
  35. package/dist/compute-offers.d.ts +128 -0
  36. package/dist/compute-offers.d.ts.map +1 -0
  37. package/dist/compute-offers.js +111 -0
  38. package/dist/compute-offers.js.map +1 -0
  39. package/dist/contest.d.ts +88 -0
  40. package/dist/contest.d.ts.map +1 -0
  41. package/dist/contest.js +131 -0
  42. package/dist/contest.js.map +1 -0
  43. package/dist/demo.d.ts +69 -0
  44. package/dist/demo.d.ts.map +1 -0
  45. package/dist/demo.js +152 -0
  46. package/dist/demo.js.map +1 -0
  47. package/dist/dependencies.d.ts +308 -0
  48. package/dist/dependencies.d.ts.map +1 -0
  49. package/dist/dependencies.js +133 -0
  50. package/dist/dependencies.js.map +1 -0
  51. package/dist/eip712.d.ts +1569 -0
  52. package/dist/eip712.d.ts.map +1 -0
  53. package/dist/eip712.js +550 -0
  54. package/dist/eip712.js.map +1 -0
  55. package/dist/elided-terms.d.ts +37 -0
  56. package/dist/elided-terms.d.ts.map +1 -0
  57. package/dist/elided-terms.js +48 -0
  58. package/dist/elided-terms.js.map +1 -0
  59. package/dist/erc8183.d.ts +78 -0
  60. package/dist/erc8183.d.ts.map +1 -0
  61. package/dist/erc8183.js +88 -0
  62. package/dist/erc8183.js.map +1 -0
  63. package/dist/facts.d.ts +70 -0
  64. package/dist/facts.d.ts.map +1 -0
  65. package/dist/facts.js +33 -0
  66. package/dist/facts.js.map +1 -0
  67. package/dist/gpu-reservation.d.ts +79 -0
  68. package/dist/gpu-reservation.d.ts.map +1 -0
  69. package/dist/gpu-reservation.js +135 -0
  70. package/dist/gpu-reservation.js.map +1 -0
  71. package/dist/index.d.ts +49 -0
  72. package/dist/index.d.ts.map +1 -0
  73. package/dist/index.js +49 -0
  74. package/dist/index.js.map +1 -0
  75. package/dist/job-session.d.ts +981 -0
  76. package/dist/job-session.d.ts.map +1 -0
  77. package/dist/job-session.js +170 -0
  78. package/dist/job-session.js.map +1 -0
  79. package/dist/job-verification.d.ts +244 -0
  80. package/dist/job-verification.d.ts.map +1 -0
  81. package/dist/job-verification.js +89 -0
  82. package/dist/job-verification.js.map +1 -0
  83. package/dist/job-wording.d.ts +48 -0
  84. package/dist/job-wording.d.ts.map +1 -0
  85. package/dist/job-wording.js +134 -0
  86. package/dist/job-wording.js.map +1 -0
  87. package/dist/job.d.ts +117 -0
  88. package/dist/job.d.ts.map +1 -0
  89. package/dist/job.js +166 -0
  90. package/dist/job.js.map +1 -0
  91. package/dist/json-fields.d.ts +13 -0
  92. package/dist/json-fields.d.ts.map +1 -0
  93. package/dist/json-fields.js +30 -0
  94. package/dist/json-fields.js.map +1 -0
  95. package/dist/keychain.d.ts +51 -0
  96. package/dist/keychain.d.ts.map +1 -0
  97. package/dist/keychain.js +133 -0
  98. package/dist/keychain.js.map +1 -0
  99. package/dist/mailbox.d.ts +1650 -0
  100. package/dist/mailbox.d.ts.map +1 -0
  101. package/dist/mailbox.js +87 -0
  102. package/dist/mailbox.js.map +1 -0
  103. package/dist/mandate.d.ts +53 -0
  104. package/dist/mandate.d.ts.map +1 -0
  105. package/dist/mandate.js +97 -0
  106. package/dist/mandate.js.map +1 -0
  107. package/dist/networks.d.ts +18 -0
  108. package/dist/networks.d.ts.map +1 -0
  109. package/dist/networks.js +24 -0
  110. package/dist/networks.js.map +1 -0
  111. package/dist/profiles.d.ts +31 -0
  112. package/dist/profiles.d.ts.map +1 -0
  113. package/dist/profiles.js +33 -0
  114. package/dist/profiles.js.map +1 -0
  115. package/dist/rail.d.ts +48 -0
  116. package/dist/rail.d.ts.map +1 -0
  117. package/dist/rail.js +28 -0
  118. package/dist/rail.js.map +1 -0
  119. package/dist/reasons.d.ts +173 -0
  120. package/dist/reasons.d.ts.map +1 -0
  121. package/dist/reasons.js +174 -0
  122. package/dist/reasons.js.map +1 -0
  123. package/dist/reference-link.d.ts +23 -0
  124. package/dist/reference-link.d.ts.map +1 -0
  125. package/dist/reference-link.js +56 -0
  126. package/dist/reference-link.js.map +1 -0
  127. package/dist/references.d.ts +125 -0
  128. package/dist/references.d.ts.map +1 -0
  129. package/dist/references.js +108 -0
  130. package/dist/references.js.map +1 -0
  131. package/dist/replay.d.ts +30 -0
  132. package/dist/replay.d.ts.map +1 -0
  133. package/dist/replay.js +27 -0
  134. package/dist/replay.js.map +1 -0
  135. package/dist/sandbox-registration.d.ts +200 -0
  136. package/dist/sandbox-registration.d.ts.map +1 -0
  137. package/dist/sandbox-registration.js +172 -0
  138. package/dist/sandbox-registration.js.map +1 -0
  139. package/dist/sandbox.d.ts +3478 -0
  140. package/dist/sandbox.d.ts.map +1 -0
  141. package/dist/sandbox.js +316 -0
  142. package/dist/sandbox.js.map +1 -0
  143. package/dist/session-fields.d.ts +203 -0
  144. package/dist/session-fields.d.ts.map +1 -0
  145. package/dist/session-fields.js +43 -0
  146. package/dist/session-fields.js.map +1 -0
  147. package/dist/supplier-adapter.d.ts +65 -0
  148. package/dist/supplier-adapter.d.ts.map +1 -0
  149. package/dist/supplier-adapter.js +91 -0
  150. package/dist/supplier-adapter.js.map +1 -0
  151. package/dist/terms-v1.d.ts +74 -0
  152. package/dist/terms-v1.d.ts.map +1 -0
  153. package/dist/terms-v1.js +156 -0
  154. package/dist/terms-v1.js.map +1 -0
  155. package/dist/terms.d.ts +341 -0
  156. package/dist/terms.d.ts.map +1 -0
  157. package/dist/terms.js +715 -0
  158. package/dist/terms.js.map +1 -0
  159. package/dist/test-customer.d.ts +1525 -0
  160. package/dist/test-customer.d.ts.map +1 -0
  161. package/dist/test-customer.js +260 -0
  162. package/dist/test-customer.js.map +1 -0
  163. package/dist/types.d.ts +272 -0
  164. package/dist/types.d.ts.map +1 -0
  165. package/dist/types.js +32 -0
  166. package/dist/types.js.map +1 -0
  167. package/dist/version.d.ts +51 -0
  168. package/dist/version.d.ts.map +1 -0
  169. package/dist/version.js +66 -0
  170. package/dist/version.js.map +1 -0
  171. package/dist/wire.d.ts +2698 -0
  172. package/dist/wire.d.ts.map +1 -0
  173. package/dist/wire.js +678 -0
  174. package/dist/wire.js.map +1 -0
  175. package/package.json +37 -3
  176. package/vectors/api-request-v1.json +53 -0
  177. package/vectors/contest-statement-v1.json +42 -0
  178. package/vectors/terms-v2.json +398 -0
  179. package/vectors/terms-v3.json +2103 -0
package/dist/terms.js ADDED
@@ -0,0 +1,715 @@
1
+ import { hkdf } from '@noble/hashes/hkdf.js';
2
+ import { sha256 } from '@noble/hashes/sha2.js';
3
+ import { bytesToHex, encodeAbiParameters, hexToBytes, isAddress, isHex, keccak256, size, stringToBytes, zeroAddress, } from 'viem';
4
+ import { canonicalJson } from './canonical.js';
5
+ import { DEPENDENCY_CHECKS, dependenciesProblem, isChainedTerms, } from './dependencies.js';
6
+ import { APPROVAL_TYPES, CHARGE_KINDS, } from './eip712.js';
7
+ import { validateGpuReservation } from './gpu-reservation.js';
8
+ import { JOB_CATEGORY, validateJob } from './job.js';
9
+ import { toTokenUnits } from './rail.js';
10
+ import { isTermsV1, termsChargesV1, termsHashV1, validateTermsV1, } from './terms-v1.js';
11
+ import { AMOUNT_DECIMALS, CHAINED_TERMS_VERSION, DEPENDENCY_CHECKS_ALLOWED, TEMPLATE_IDS, TERMS_VERSION, } from './types.js';
12
+ /** The five sections of version 2 terms, in the order the terms hash takes their hashes. */
13
+ export const TERMS_SECTIONS = [
14
+ 'subject',
15
+ 'consideration',
16
+ 'remedies',
17
+ 'resolution',
18
+ 'backing',
19
+ ];
20
+ /** The six sections of version 3 terms, version 2's five and then `dependencies`, in hash order. */
21
+ export const CHAINED_TERMS_SECTIONS = [...TERMS_SECTIONS, 'dependencies'];
22
+ /** The label a version 2 terms hash starts from. No other Avow hash uses it. */
23
+ export const TERMS_LABEL = 'avow:terms:v2';
24
+ /** The label a version 3 terms hash starts from. No other Avow hash uses it. */
25
+ export const CHAINED_TERMS_LABEL = 'avow:terms:v3';
26
+ /**
27
+ * The label of the version that brought in a section. Version 3 hashes version 2's five sections
28
+ * exactly as version 2 does, and only `dependencies` starts from its own label.
29
+ */
30
+ const introducedBy = (section) => section === 'dependencies' ? CHAINED_TERMS_LABEL : TERMS_LABEL;
31
+ /**
32
+ * The label a section's hash starts from, such as `avow:terms:v2:remedies`, or
33
+ * `avow:terms:v3:dependencies` for the section version 3 adds.
34
+ */
35
+ export function sectionLabel(section) {
36
+ return `${introducedBy(section)}:${section}`;
37
+ }
38
+ /**
39
+ * The HKDF info that derives a section's salt, such as `avow:terms:v2:salt:remedies`, or
40
+ * `avow:terms:v3:salt:dependencies` for the section version 3 adds.
41
+ */
42
+ export function sectionSaltLabel(section) {
43
+ return `${introducedBy(section)}:salt:${section}`;
44
+ }
45
+ export function termsHeader(t) {
46
+ const header = { template: t.template, currency: t.currency, amountDecimals: t.amountDecimals };
47
+ return t.version === CHAINED_TERMS_VERSION
48
+ ? { version: t.version, ...header, dependencyCheck: t.dependencyCheck }
49
+ : { version: t.version, ...header };
50
+ }
51
+ /** The names of the sections terms of this version hold, in hash order. */
52
+ function sectionNames(t) {
53
+ return isChainedTerms(t) ? CHAINED_TERMS_SECTIONS : TERMS_SECTIONS;
54
+ }
55
+ export function termsSections(t) {
56
+ const five = {
57
+ subject: t.subject,
58
+ consideration: t.consideration,
59
+ remedies: t.remedies,
60
+ resolution: t.resolution,
61
+ backing: t.backing,
62
+ };
63
+ return isChainedTerms(t) ? { ...five, dependencies: t.dependencies } : five;
64
+ }
65
+ /** The fields version 2 terms hold at the top level, the header's four and the five sections. */
66
+ const TERMS_FIELDS = [
67
+ 'version',
68
+ 'template',
69
+ 'currency',
70
+ 'amountDecimals',
71
+ ...TERMS_SECTIONS,
72
+ ];
73
+ /**
74
+ * The fields version 3 terms hold at the top level, version 2's, the header's setting for who
75
+ * checks the bookings relied on, and the dependencies section.
76
+ */
77
+ const CHAINED_TERMS_FIELDS = [...TERMS_FIELDS, 'dependencyCheck', 'dependencies'];
78
+ /** The top-level fields of each version this code hashes in sections. */
79
+ const FIELDS_BY_VERSION = new Map([
80
+ [TERMS_VERSION, TERMS_FIELDS],
81
+ [CHAINED_TERMS_VERSION, CHAINED_TERMS_FIELDS],
82
+ ]);
83
+ /** The versions that hash their terms in sections, so a section of them can be shown on its own. */
84
+ export const SECTIONED_TERMS_VERSIONS = [...FIELDS_BY_VERSION.keys()];
85
+ const isPlainObject = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
86
+ /** The label an elided dependencies section carries, the one its hash starts from. */
87
+ export const DEPENDENCIES_LABEL = sectionLabel('dependencies');
88
+ /**
89
+ * Whether a value stands in for a section by its digest. A reader that needs the section in clear
90
+ * refuses one with `dependency.elided`, and never reads it as a section with nothing in it.
91
+ */
92
+ export function isElidedSection(value) {
93
+ return isPlainObject(value) && 'digest' in value;
94
+ }
95
+ /**
96
+ * What keeps sectioned terms of one of these versions from being hashed, or null when nothing
97
+ * does. Version 1 terms, which have no `version` key, pass when `withV1` says they may.
98
+ */
99
+ function shapeProblem(terms, versions, withV1) {
100
+ if (!isPlainObject(terms))
101
+ return 'terms.invalid';
102
+ if (isTermsV1(terms))
103
+ return withV1 ? null : 'terms.version_unknown';
104
+ const expected = versions.includes(terms.version) ? FIELDS_BY_VERSION.get(terms.version) : null;
105
+ if (!expected)
106
+ return 'terms.version_unknown';
107
+ const chained = terms.version === CHAINED_TERMS_VERSION;
108
+ // Before the fields are counted, so the buyer's whole view gets this reason too.
109
+ if (chained && isElidedSection(terms.dependencies))
110
+ return 'dependency.elided';
111
+ const fields = Object.keys(terms).filter((k) => terms[k] !== undefined);
112
+ if (expected.some((f) => !fields.includes(f)))
113
+ return 'terms.incomplete';
114
+ if (fields.length !== expected.length)
115
+ return 'terms.invalid';
116
+ if (!TERMS_SECTIONS.every((section) => isPlainObject(terms[section])))
117
+ return 'terms.invalid';
118
+ if (chained && !Array.isArray(terms.dependencies))
119
+ return 'terms.invalid';
120
+ if (chained && !DEPENDENCY_CHECKS.includes(terms.dependencyCheck)) {
121
+ return 'terms.invalid';
122
+ }
123
+ try {
124
+ canonicalJson(terms);
125
+ }
126
+ catch {
127
+ return 'terms.invalid';
128
+ }
129
+ return null;
130
+ }
131
+ /**
132
+ * What keeps terms from being hashed, or null when nothing does. Version 2 terms hold exactly
133
+ * their version, the header's other three fields and the five sections, each section an object,
134
+ * and every value has to be one canonical JSON can write. The terms hash covers only the header
135
+ * and the sections, so a field beside them is refused rather than left out of the hash. A field
136
+ * or section left out is `terms.incomplete`, another version is `terms.version_unknown` and
137
+ * anything else is `terms.invalid`. Terms with no `version` key are version 1, and any other field
138
+ * set to undefined counts as left out, as JSON leaves it out. Version 1 terms hash every field they
139
+ * hold, so `validateTerms` checks them on its own.
140
+ *
141
+ * Version 3 terms are refused as a version this reads, as are their checks, since a booking that
142
+ * relies on others is sound only once those bookings are read. `chainedTermsShapeProblem` reads
143
+ * version 3 alone, for a path that also runs that check.
144
+ */
145
+ export function termsShapeProblem(terms) {
146
+ return shapeProblem(terms, [TERMS_VERSION], true);
147
+ }
148
+ /**
149
+ * What keeps version 3 terms from being hashed, or null when nothing does. They hold version 2's
150
+ * fields, a `dependencyCheck` of `buyer` or `avow`, and the dependencies section, which is a list.
151
+ * Terms carrying that section only as its digest are `dependency.elided`, since these are the
152
+ * terms in full, and every other version is `terms.version_unknown`.
153
+ */
154
+ export function chainedTermsShapeProblem(terms) {
155
+ return shapeProblem(terms, [CHAINED_TERMS_VERSION], false);
156
+ }
157
+ /** Throws on terms that can't be hashed, of version 1, 2 or 3. */
158
+ function assertShape(terms) {
159
+ const problem = shapeProblem(terms, SECTIONED_TERMS_VERSIONS, true);
160
+ if (problem)
161
+ throw new TypeError(`These terms can't be hashed (${problem})`);
162
+ }
163
+ function checkSalt(salt) {
164
+ if (!isHex(salt) || size(salt) !== 32)
165
+ throw new TypeError('The salt must be 32 bytes');
166
+ if (/^0x0{64}$/.test(salt))
167
+ throw new TypeError('The salt must be random, and all zeros is not');
168
+ }
169
+ /**
170
+ * A section's salt. It's HKDF-SHA256 (RFC 5869) with the commitment's 32-byte salt as the input
171
+ * keying material, no HKDF salt, the UTF-8 bytes of the section's salt label as the info, and 32
172
+ * bytes of output. The label is `avow:terms:v2:salt:<section>`, or
173
+ * `avow:terms:v3:salt:dependencies` for the section version 3 adds. Showing one section's salt
174
+ * reveals no other section's salt and not the commitment's.
175
+ */
176
+ export function sectionSalt(salt, section) {
177
+ checkSalt(salt);
178
+ const info = stringToBytes(sectionSaltLabel(section));
179
+ return bytesToHex(hkdf(sha256, hexToBytes(salt), undefined, info, 32));
180
+ }
181
+ /** An object with these string fields in lower case, and anything else as it is. */
182
+ function lowerFields(content, fields) {
183
+ if (content === null || typeof content !== 'object' || Array.isArray(content))
184
+ return content;
185
+ const lowered = { ...content };
186
+ for (const f of fields) {
187
+ const value = lowered[f];
188
+ if (typeof value === 'string')
189
+ lowered[f] = value.toLowerCase();
190
+ }
191
+ return lowered;
192
+ }
193
+ /**
194
+ * A section as it's hashed. The arbiter's address is lower case, and so are each dependency's
195
+ * lock, commitment id and terms hash, so letter case can't change the hash.
196
+ */
197
+ function hashedForm(section, content) {
198
+ if (section === 'resolution')
199
+ return lowerFields(content, ['arbiter']);
200
+ if (section !== 'dependencies' || !Array.isArray(content))
201
+ return content;
202
+ return content.map((entry) => {
203
+ if (entry === null || typeof entry !== 'object' || !('on' in entry))
204
+ return entry;
205
+ return { ...entry, on: lowerFields(entry.on, ['lock', 'commitmentId', 'termsHash']) };
206
+ });
207
+ }
208
+ /**
209
+ * A section's hash: keccak256 of the ABI encoding of the section's label, such as
210
+ * `avow:terms:v2:<section>` or `avow:terms:v3:dependencies`, the section's own salt as bytes32,
211
+ * and the section's canonical JSON as a string.
212
+ */
213
+ export function sectionHash(section, content, ownSalt) {
214
+ if (!isHex(ownSalt) || size(ownSalt) !== 32)
215
+ throw new TypeError('A section salt must be 32 bytes');
216
+ return keccak256(encodeAbiParameters([{ type: 'string' }, { type: 'bytes32' }, { type: 'string' }], [sectionLabel(section), ownSalt, canonicalJson(hashedForm(section, content))]));
217
+ }
218
+ /**
219
+ * The terms hash from the header and the section hashes: keccak256 of the ABI encoding of the
220
+ * string `avow:terms:v2`, the header's canonical JSON as a string, and the hashes of subject,
221
+ * consideration, remedies, resolution and backing as five bytes32, in that order.
222
+ */
223
+ export function termsHashFromSections(header, hashes) {
224
+ return keccak256(encodeAbiParameters([
225
+ { type: 'string' },
226
+ { type: 'string' },
227
+ { type: 'bytes32' },
228
+ { type: 'bytes32' },
229
+ { type: 'bytes32' },
230
+ { type: 'bytes32' },
231
+ { type: 'bytes32' },
232
+ ], [
233
+ TERMS_LABEL,
234
+ canonicalJson(header),
235
+ hashes.subject,
236
+ hashes.consideration,
237
+ hashes.remedies,
238
+ hashes.resolution,
239
+ hashes.backing,
240
+ ]));
241
+ }
242
+ /**
243
+ * The version 3 terms hash from the header and the section hashes: keccak256 of the ABI encoding
244
+ * of the string `avow:terms:v3`, the header's canonical JSON as a string, and the hashes of
245
+ * subject, consideration, remedies, resolution, backing and dependencies as six bytes32, in that
246
+ * order.
247
+ */
248
+ export function chainedTermsHashFromSections(header, hashes) {
249
+ return keccak256(encodeAbiParameters([
250
+ { type: 'string' },
251
+ { type: 'string' },
252
+ ...CHAINED_TERMS_SECTIONS.map(() => ({ type: 'bytes32' })),
253
+ ], [CHAINED_TERMS_LABEL, canonicalJson(header), ...CHAINED_TERMS_SECTIONS.map((s) => hashes[s])]));
254
+ }
255
+ export function sectionHashes(t, salt) {
256
+ const sections = termsSections(t);
257
+ const hashes = {};
258
+ for (const s of sectionNames(t))
259
+ hashes[s] = sectionHash(s, sections[s], sectionSalt(salt, s));
260
+ return hashes;
261
+ }
262
+ /**
263
+ * The salted terms hash the lock stores and every signed message names. Version 2 and version 3
264
+ * terms hash their header and sections as above. Version 1 terms keep the hash they were signed
265
+ * under. Throws on version 1 or 2 terms `termsShapeProblem` refuses and on version 3 terms
266
+ * `chainedTermsShapeProblem` refuses, so no field ever sits outside the hash.
267
+ */
268
+ export function termsHash(terms, salt) {
269
+ assertShape(terms);
270
+ if (isTermsV1(terms))
271
+ return termsHashV1(terms, salt);
272
+ if (isChainedTerms(terms)) {
273
+ return chainedTermsHashFromSections(termsHeader(terms), sectionHashes(terms, salt));
274
+ }
275
+ return termsHashFromSections(termsHeader(terms), sectionHashes(terms, salt));
276
+ }
277
+ export function discloseSection(terms, salt, section) {
278
+ assertShape(terms);
279
+ if (isTermsV1(terms))
280
+ throw new TypeError('Version 1 terms have no sections to show');
281
+ const names = sectionNames(terms);
282
+ if (!names.includes(section))
283
+ throw new TypeError(`These terms have no ${section} section`);
284
+ const hashes = sectionHashes(terms, salt);
285
+ const others = {};
286
+ for (const s of names) {
287
+ const hash = hashes[s];
288
+ if (s !== section && hash !== undefined)
289
+ others[s] = hash;
290
+ }
291
+ return {
292
+ header: termsHeader(terms),
293
+ section,
294
+ content: termsSections(terms)[section],
295
+ salt: sectionSalt(salt, section),
296
+ others,
297
+ };
298
+ }
299
+ /**
300
+ * Checks a shown section against the terms hash a lock or a signed message holds. It needs only
301
+ * the section, its own salt and the hashes of the other sections its header's version holds.
302
+ * `parseSectionDisclosure` checks the section's shape before a reader relies on what it says.
303
+ */
304
+ export function checkSectionDisclosure(d, expected) {
305
+ const chained = d.header.version === CHAINED_TERMS_VERSION;
306
+ if (!chained && d.header.version !== TERMS_VERSION)
307
+ return 'terms.version_unknown';
308
+ if (!TEMPLATE_IDS.includes(d.header.template)) {
309
+ return 'terms.template_unknown';
310
+ }
311
+ const names = chained ? CHAINED_TERMS_SECTIONS : TERMS_SECTIONS;
312
+ if (!names.includes(d.section))
313
+ return 'terms.invalid';
314
+ for (const s of names) {
315
+ const present = d.others[s] !== undefined;
316
+ if (present === (s === d.section))
317
+ return 'terms.invalid';
318
+ }
319
+ const hashes = {
320
+ ...d.others,
321
+ [d.section]: sectionHash(d.section, d.content, d.salt),
322
+ };
323
+ const actual = chained
324
+ ? chainedTermsHashFromSections(d.header, hashes)
325
+ : termsHashFromSections(d.header, hashes);
326
+ return actual.toLowerCase() === expected.toLowerCase() ? null : 'terms.hash_mismatch';
327
+ }
328
+ /** Each template's own rules, which run after the core's. */
329
+ const TEMPLATE_RULES = {
330
+ 'gpu-reservation/1': (t) => validateGpuReservation(t),
331
+ 'job/1': (t) => validateJob(t),
332
+ };
333
+ /**
334
+ * The one mandate category each template's bookings fall under, or null when the request names
335
+ * its own. The build fails when a template is missing here.
336
+ */
337
+ const TEMPLATE_CATEGORIES = {
338
+ 'gpu-reservation/1': null,
339
+ 'job/1': JOB_CATEGORY,
340
+ };
341
+ /**
342
+ * Why terms can't be booked under this mandate category, or null when they can. A template with
343
+ * a category of its own, such as a job's, takes only that one, and any other is
344
+ * `terms.category_mismatch`.
345
+ */
346
+ export function templateCategoryProblem(terms, category) {
347
+ if (!Object.hasOwn(TEMPLATE_CATEGORIES, terms.template))
348
+ return null;
349
+ const fixed = TEMPLATE_CATEGORIES[terms.template];
350
+ return fixed === null || fixed === category ? null : 'terms.category_mismatch';
351
+ }
352
+ /**
353
+ * Whether a template's bookings always rely on another booking, so they commit only under version
354
+ * 3, which names it. The build fails when a template is missing here.
355
+ */
356
+ const RELIES_ON_A_BOOKING = {
357
+ 'gpu-reservation/1': false,
358
+ 'job/1': true,
359
+ };
360
+ /** Charges come in the order of the lock's codes, at most one of each kind, each with an amount. */
361
+ function checkCharges(charges) {
362
+ if (charges.length === 0 || charges.length > 4)
363
+ return 'terms.charges_invalid';
364
+ let last = -1;
365
+ for (const c of charges) {
366
+ // Only the table's own kinds count, never a name every object inherits such as `constructor`.
367
+ if (!Object.hasOwn(CHARGE_KINDS, c.kind))
368
+ return 'terms.charges_invalid';
369
+ const code = CHARGE_KINDS[c.kind];
370
+ if (code <= last || c.amount <= 0n)
371
+ return 'terms.charges_invalid';
372
+ last = code;
373
+ }
374
+ return null;
375
+ }
376
+ /**
377
+ * Checks terms on their own, before any mandate, and returns null when they're sound. Version 1
378
+ * terms keep the checks they were made under. Version 2 terms pass the core's checks of what a
379
+ * lock enforces, then their template's rules. A template whose bookings always rely on another,
380
+ * such as a job, is refused as `dependency.required`. The core refuses a backing, side or charge a lock
381
+ * can't enforce, and a template it doesn't know. Version 3 terms are refused as a version this
382
+ * reads, and `validateChainedTerms` checks them.
383
+ */
384
+ export function validateTerms(terms, profile) {
385
+ const shape = termsShapeProblem(terms);
386
+ if (shape)
387
+ return shape;
388
+ if (isTermsV1(terms))
389
+ return validateTermsV1(terms, profile);
390
+ // A job names the compute it runs on, so job terms that name no booking never commit.
391
+ if (Object.hasOwn(RELIES_ON_A_BOOKING, terms.template) && RELIES_ON_A_BOOKING[terms.template]) {
392
+ return 'dependency.required';
393
+ }
394
+ return sectionRulesProblem(terms, profile);
395
+ }
396
+ /**
397
+ * Checks version 3 terms on their own and returns null when they're sound. They pass every check
398
+ * the version 2 terms they make pass, and their dependencies section passes
399
+ * `dependenciesProblem`. Whether each booking relied on stands is for a check that reads its lock,
400
+ * so a caller that commits to these terms runs that check too.
401
+ */
402
+ export function validateChainedTerms(terms, profile) {
403
+ const shape = chainedTermsShapeProblem(terms);
404
+ if (shape)
405
+ return shape;
406
+ return (dependencyCheckProblem(terms) ??
407
+ sectionRulesProblem(plainTermsOf(terms), profile) ??
408
+ dependenciesProblem(terms.dependencies));
409
+ }
410
+ /**
411
+ * Why version 3 terms can't use the setting they name for who checks their bookings, or null when
412
+ * they can. A setting the template doesn't allow is `terms.template_invalid`.
413
+ */
414
+ export function dependencyCheckProblem(terms) {
415
+ const allowed = Object.hasOwn(DEPENDENCY_CHECKS_ALLOWED, terms.template)
416
+ ? DEPENDENCY_CHECKS_ALLOWED[terms.template]
417
+ : [];
418
+ return allowed.includes(terms.dependencyCheck) ? null : 'terms.template_invalid';
419
+ }
420
+ /**
421
+ * The version 2 terms that say what these version 3 terms say, without the bookings they rely on
422
+ * or who checks them. They pass the same checks and make the lock enforce the same values, and
423
+ * their terms hash differs, so they never stand for the version 3 terms in a signed message.
424
+ */
425
+ export function plainTermsOf(terms) {
426
+ const { dependencies: _, dependencyCheck: __, ...plain } = terms;
427
+ return { ...plain, version: TERMS_VERSION };
428
+ }
429
+ /** The core's checks of version 2 terms, then their template's rules. */
430
+ function sectionRulesProblem(terms, profile) {
431
+ if (!Object.hasOwn(TEMPLATE_RULES, terms.template))
432
+ return 'terms.template_unknown';
433
+ // The table gives each template the rules for its own terms, and the key is this terms' template.
434
+ const rules = TEMPLATE_RULES[terms.template];
435
+ if (terms.amountDecimals !== AMOUNT_DECIMALS)
436
+ return 'terms.invalid';
437
+ const { remedies: r, resolution: res, backing: b } = terms;
438
+ if (b.kind !== 'reserve' || b.side !== 'buyer') {
439
+ return 'terms.backing_unsupported';
440
+ }
441
+ const chargesProblem = checkCharges(r.charges);
442
+ if (chargesProblem)
443
+ return chargesProblem;
444
+ const largest = r.charges.reduce((most, c) => (c.amount > most ? c.amount : most), 0n);
445
+ if (b.amount !== largest)
446
+ return 'terms.reserve_mismatch';
447
+ // Every charge needs a moment it can be reported in, before the deadline and the reserve's
448
+ // release.
449
+ const inOrder = r.acceptBy < r.chargeDeadline &&
450
+ r.freeCancelBy < r.chargeDeadline &&
451
+ r.charges.every((c) => c.earliest < r.chargeDeadline) &&
452
+ r.chargeDeadline <= b.releaseDate;
453
+ if (!inOrder)
454
+ return 'terms.deadlines_out_of_order';
455
+ if (res.contestWindow < profile.minContestWindow)
456
+ return 'terms.contest_window_short';
457
+ const share = res.day90SupplierShareBps;
458
+ if (typeof res.arbiter !== 'string' ||
459
+ !isAddress(res.arbiter, { strict: false }) ||
460
+ res.arbiter.toLowerCase() === zeroAddress ||
461
+ !Number.isInteger(share) ||
462
+ share < 0 ||
463
+ share > 10_000) {
464
+ return 'terms.dispute_invalid';
465
+ }
466
+ return rules(terms);
467
+ }
468
+ /**
469
+ * What the lock enforces of these terms. Version 3 terms are read as the version 2 terms they
470
+ * make, since the lock knows nothing of the bookings they rely on.
471
+ */
472
+ export function enforceableTerms(given) {
473
+ const terms = isChainedTerms(given) ? plainTermsOf(given) : given;
474
+ if (isTermsV1(terms)) {
475
+ const charges = [];
476
+ if (terms.lateCancellation > 0n) {
477
+ charges.push({
478
+ kind: 'lateCancellation',
479
+ amount: terms.lateCancellation,
480
+ earliest: terms.freeCancelBy,
481
+ });
482
+ }
483
+ if (terms.noShow > 0n) {
484
+ charges.push({
485
+ kind: 'noShow',
486
+ amount: terms.noShow,
487
+ earliest: terms.windowStart + terms.gracePeriod,
488
+ });
489
+ }
490
+ return {
491
+ currency: terms.currency,
492
+ side: 'buyer',
493
+ reserve: terms.reserve,
494
+ acceptBy: terms.acceptBy,
495
+ freeCancelBy: terms.freeCancelBy,
496
+ chargeDeadline: terms.chargeDeadline,
497
+ releaseDate: terms.releaseDate,
498
+ contestWindow: terms.contestWindow,
499
+ charges,
500
+ arbiter: terms.dispute.arbiter,
501
+ day90SupplierShareBps: terms.dispute.day90SupplierShareBps,
502
+ };
503
+ }
504
+ return {
505
+ currency: terms.currency,
506
+ side: terms.backing.side,
507
+ reserve: terms.backing.amount,
508
+ acceptBy: terms.remedies.acceptBy,
509
+ freeCancelBy: terms.remedies.freeCancelBy,
510
+ chargeDeadline: terms.remedies.chargeDeadline,
511
+ releaseDate: terms.backing.releaseDate,
512
+ contestWindow: terms.resolution.contestWindow,
513
+ charges: terms.remedies.charges.map((c) => ({ ...c })),
514
+ arbiter: terms.resolution.arbiter,
515
+ day90SupplierShareBps: terms.resolution.day90SupplierShareBps,
516
+ };
517
+ }
518
+ /**
519
+ * The enforceable fields in a token's base units, as Avow's approval carries them and the lock
520
+ * stores them. Throws when an amount can't be paid exactly in a token with these decimals.
521
+ */
522
+ export function lockTerms(given, decimals) {
523
+ const terms = isChainedTerms(given) ? plainTermsOf(given) : given;
524
+ const e = enforceableTerms(terms);
525
+ const units = (micros) => toTokenUnits(micros, decimals);
526
+ return {
527
+ side: e.side,
528
+ amount: units(e.reserve),
529
+ freeCancelBy: e.freeCancelBy,
530
+ acceptBy: e.acceptBy,
531
+ chargeDeadline: e.chargeDeadline,
532
+ releaseDate: e.releaseDate,
533
+ contestWindow: e.contestWindow,
534
+ charges: isTermsV1(terms)
535
+ ? termsChargesV1(terms, decimals)
536
+ : e.charges.map((c) => ({ kind: c.kind, most: units(c.amount), earliest: c.earliest })),
537
+ day90SupplierShareBps: e.day90SupplierShareBps,
538
+ arbiter: e.arbiter,
539
+ };
540
+ }
541
+ /**
542
+ * The charges a commitment under these terms carries, as Avow's approval names them. Version 1
543
+ * terms keep the function they were read with, which needs neither the dispute block nor a reserve
544
+ * the token can hold.
545
+ */
546
+ export function termsCharges(terms, decimals) {
547
+ if (isTermsV1(terms))
548
+ return termsChargesV1(terms, decimals);
549
+ return lockTerms(terms, decimals).charges;
550
+ }
551
+ /**
552
+ * Every field of `LockTerms`, the values a lock enforces for a commitment, in the order Avow's
553
+ * approval carries them. The build fails when `LockTerms` gains a field this list leaves out, and
554
+ * every comparison of lock-enforced values runs through `lockTermsDifferences`, so a new field is
555
+ * compared everywhere at once.
556
+ */
557
+ export const LOCK_TERMS_FIELDS = [
558
+ 'side',
559
+ 'amount',
560
+ 'freeCancelBy',
561
+ 'acceptBy',
562
+ 'chargeDeadline',
563
+ 'releaseDate',
564
+ 'contestWindow',
565
+ 'charges',
566
+ 'day90SupplierShareBps',
567
+ 'arbiter',
568
+ ];
569
+ // The list names every field of `LockTerms` and nothing else.
570
+ const _everyLockTermsField = true;
571
+ void _everyLockTermsField;
572
+ /**
573
+ * The lock-enforced fields a lock's record of one side of a commitment holds: every field but
574
+ * `side`. The lock files each record under its side, so a record names its side by where it's
575
+ * read from rather than in a field.
576
+ */
577
+ export const LOCK_RECORD_FIELDS = LOCK_TERMS_FIELDS.filter((f) => f !== 'side');
578
+ /**
579
+ * The lock-enforced fields Avow's supplier authorization carries: the reserve and three deadlines.
580
+ * Its EIP-712 type fixes them, and the build fails when that type and this list disagree about
581
+ * which lock-enforced fields it holds.
582
+ */
583
+ export const AUTHORIZATION_TERMS_FIELDS = [
584
+ 'amount',
585
+ 'acceptBy',
586
+ 'chargeDeadline',
587
+ 'releaseDate',
588
+ ];
589
+ const _authorizationTermsFields = true;
590
+ void _authorizationTermsFields;
591
+ /** Two addresses in any letter case. Anything that isn't an address is never equal. */
592
+ function sameAddress(a, b) {
593
+ return (isAddress(a, { strict: false }) &&
594
+ isAddress(b, { strict: false }) &&
595
+ a.toLowerCase() === b.toLowerCase());
596
+ }
597
+ const CHARGE_FIELD_NAMES = APPROVAL_TYPES.Charge.map((f) => f.name);
598
+ /**
599
+ * Whether two lists of charges are the same: the same kinds in the same order, each equal in
600
+ * every field the signed `Charge` type holds.
601
+ */
602
+ export function sameCharges(a, b) {
603
+ return (a.length === b.length &&
604
+ a.every((c, i) => {
605
+ const d = b[i];
606
+ return d !== undefined && CHARGE_FIELD_NAMES.every((name) => c[name] === d[name]);
607
+ }));
608
+ }
609
+ /** How each lock-enforced field compares. The build fails when a field has no entry. */
610
+ const FIELD_EQUALS = {
611
+ side: (a, b) => a === b,
612
+ amount: (a, b) => a === b,
613
+ freeCancelBy: (a, b) => a === b,
614
+ acceptBy: (a, b) => a === b,
615
+ chargeDeadline: (a, b) => a === b,
616
+ releaseDate: (a, b) => a === b,
617
+ contestWindow: (a, b) => a === b,
618
+ charges: sameCharges,
619
+ day90SupplierShareBps: (a, b) => a === b,
620
+ arbiter: sameAddress,
621
+ };
622
+ /**
623
+ * The fields where `actual` differs from `expected`, among `fields` and in their order, or an empty
624
+ * list when they agree. Amounts, times and the day-90 share compare exactly, the arbiter in any
625
+ * letter case, and charges kind by kind in order. Every check of lock-enforced values uses this,
626
+ * with `LOCK_TERMS_FIELDS`, `LOCK_RECORD_FIELDS` or `AUTHORIZATION_TERMS_FIELDS` as the fields.
627
+ */
628
+ export function lockTermsDifferences(actual, expected, fields) {
629
+ return fields.filter((f) => {
630
+ const equals = FIELD_EQUALS[f];
631
+ return !equals(actual[f], expected[f]);
632
+ });
633
+ }
634
+ /** Charges in the order of the lock's codes for their kinds. */
635
+ const inChargeCodeOrder = (charges) => [...charges].sort((x, y) => CHARGE_KINDS[x.kind] - CHARGE_KINDS[y.kind]);
636
+ /**
637
+ * The fields where a lock's record of one side of a commitment differs from the values expected of
638
+ * it, among `LOCK_RECORD_FIELDS`. The lock stores charges by kind, so their order means nothing to
639
+ * it, and both sides' charges are put in the order of the lock's codes before they're compared.
640
+ */
641
+ export function lockRecordDifferences(record, expected) {
642
+ return lockTermsDifferences({ ...record, charges: inChargeCodeOrder(record.charges) }, { ...expected, charges: inChargeCodeOrder(expected.charges) }, LOCK_RECORD_FIELDS);
643
+ }
644
+ /**
645
+ * The reason `approvalTermsProblem` gives for each field. The fields come in the order of
646
+ * `LOCK_TERMS_FIELDS`, so a difference in the side, the amount, a deadline or the contest window
647
+ * outranks one in the charges, which outranks one in the dispute terms.
648
+ */
649
+ const APPROVAL_FIELD_REASONS = {
650
+ side: 'approval.terms_mismatch',
651
+ amount: 'approval.terms_mismatch',
652
+ freeCancelBy: 'approval.terms_mismatch',
653
+ acceptBy: 'approval.terms_mismatch',
654
+ chargeDeadline: 'approval.terms_mismatch',
655
+ releaseDate: 'approval.terms_mismatch',
656
+ contestWindow: 'approval.terms_mismatch',
657
+ charges: 'approval.charges_mismatch',
658
+ day90SupplierShareBps: 'approval.dispute_mismatch',
659
+ arbiter: 'approval.dispute_mismatch',
660
+ };
661
+ /**
662
+ * Checks that an approval carries exactly what the signed terms map to, and the terms hash both
663
+ * businesses signed. The API runs it before it signs an approval, and a supplier's verifier runs
664
+ * it before it accepts one, so an approval can't make a lock enforce anything the terms don't say.
665
+ * Returns the first difference, or null.
666
+ */
667
+ export function approvalTermsProblem(approval, expected) {
668
+ if (approval.termsHash.toLowerCase() !== expected.termsHash.toLowerCase()) {
669
+ return 'approval.terms_mismatch';
670
+ }
671
+ const [first] = lockTermsDifferences(approval, expected.lock, LOCK_TERMS_FIELDS);
672
+ return first ? APPROVAL_FIELD_REASONS[first] : null;
673
+ }
674
+ /**
675
+ * Checks that an approval names the supplier's own account, which consents to releases, its
676
+ * signing key, which accepts the reserve and reports charges, and its payout address. Returns
677
+ * `approval.parties_mismatch` when any of them differs, or null.
678
+ */
679
+ export function approvalPartiesProblem(approval, parties) {
680
+ const named = sameAddress(approval.supplier, parties.account) &&
681
+ sameAddress(approval.supplierSigner, parties.signingKey) &&
682
+ sameAddress(approval.payee, parties.payee);
683
+ return named ? null : 'approval.parties_mismatch';
684
+ }
685
+ /**
686
+ * Checks that an approval names the token the buyer's lock holds reserves in. Returns
687
+ * `approval.terms_mismatch` when it names another, or null.
688
+ */
689
+ export function approvalTokenProblem(approval, token) {
690
+ return sameAddress(approval.token, token) ? null : 'approval.terms_mismatch';
691
+ }
692
+ /**
693
+ * A mandate's two caps in a token's base units, as Avow's approval carries them and the lock
694
+ * enforces them. Throws when a cap can't be paid exactly in a token with these decimals.
695
+ */
696
+ export function approvalCaps(mandate, decimals) {
697
+ return {
698
+ capPerCommitment: toTokenUnits(mandate.capPerCommitment, decimals),
699
+ capOpenReserves: toTokenUnits(mandate.capOpenReserves, decimals),
700
+ };
701
+ }
702
+ /**
703
+ * Checks that an approval names the buyer's mandate, that mandate's two caps and a funding key the
704
+ * caller allows. The lock enforces the caps and checks the key that funds the reserve against the
705
+ * one the approval names, so other values would let through a reserve the mandate doesn't allow.
706
+ * Returns `approval.mandate_mismatch` when any of them differs, or null.
707
+ */
708
+ export function approvalMandateProblem(approval, expected) {
709
+ const named = approval.mandateHash.toLowerCase() === expected.mandateHash.toLowerCase() &&
710
+ approval.capPerCommitment === expected.caps.capPerCommitment &&
711
+ approval.capOpenReserves === expected.caps.capOpenReserves &&
712
+ expected.fundingKeys.some((k) => sameAddress(approval.fundingKey, k));
713
+ return named ? null : 'approval.mandate_mismatch';
714
+ }
715
+ //# sourceMappingURL=terms.js.map