@crediolabs/policy-synth 0.2.0 → 0.3.1

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 (249) hide show
  1. package/README.md +4 -4
  2. package/dist/adapters/interpreter/adapter.d.ts +19 -25
  3. package/dist/adapters/interpreter/adapter.js +54 -487
  4. package/dist/errors.d.ts +1 -1
  5. package/dist/index.d.ts +1 -4
  6. package/dist/index.js +1 -4
  7. package/dist/install/build-add-context-rule.d.ts +3 -19
  8. package/dist/install/build-add-context-rule.js +3 -98
  9. package/dist/install/build-install-policy.d.ts +4 -53
  10. package/dist/install/build-install-policy.js +44 -123
  11. package/dist/install/index.d.ts +0 -2
  12. package/dist/install/index.js +0 -7
  13. package/dist/predicate/decode.d.ts +1 -1
  14. package/dist/predicate/decode.js +2 -70
  15. package/dist/predicate/encode.js +45 -229
  16. package/dist/predicate/from-json.js +1 -42
  17. package/dist/record/decode.js +3 -8
  18. package/dist/record/freshness.d.ts +17 -11
  19. package/dist/record/freshness.js +28 -18
  20. package/dist/review-card/builder.d.ts +4 -3
  21. package/dist/review-card/builder.js +18 -162
  22. package/dist/review-card/cross-check.js +2 -105
  23. package/dist/review-card/render-leaf.d.ts +4 -0
  24. package/dist/review-card/render-leaf.js +47 -0
  25. package/dist/run/index.d.ts +36 -139
  26. package/dist/run/index.js +125 -437
  27. package/dist/run/schemas.d.ts +168 -1929
  28. package/dist/run/schemas.js +40 -269
  29. package/dist/{synth → simulate}/deny-cases.d.ts +4 -8
  30. package/dist/simulate/deny-cases.js +282 -0
  31. package/dist/simulate/evaluate.d.ts +18 -0
  32. package/dist/simulate/evaluate.js +271 -0
  33. package/dist/simulate/index.d.ts +4 -0
  34. package/dist/simulate/index.js +8 -0
  35. package/dist/synth/compose-from-recording.d.ts +24 -51
  36. package/dist/synth/compose-from-recording.js +120 -282
  37. package/dist/synth/index.d.ts +0 -5
  38. package/dist/synth/index.js +0 -5
  39. package/dist/synth/synthesize-from-recording.d.ts +1 -29
  40. package/dist/synth/synthesize-from-recording.js +41 -356
  41. package/dist/types.d.ts +8 -60
  42. package/dist/types.js +5 -2
  43. package/dist-cjs/adapters/interpreter/adapter.d.ts +19 -25
  44. package/dist-cjs/adapters/interpreter/adapter.js +56 -489
  45. package/dist-cjs/errors.d.ts +1 -1
  46. package/dist-cjs/index.d.ts +1 -4
  47. package/dist-cjs/index.js +1 -4
  48. package/dist-cjs/install/build-add-context-rule.d.ts +3 -19
  49. package/dist-cjs/install/build-add-context-rule.js +1 -97
  50. package/dist-cjs/install/build-install-policy.d.ts +4 -53
  51. package/dist-cjs/install/build-install-policy.js +44 -122
  52. package/dist-cjs/install/index.d.ts +0 -2
  53. package/dist-cjs/install/index.js +2 -23
  54. package/dist-cjs/predicate/decode.d.ts +1 -1
  55. package/dist-cjs/predicate/decode.js +2 -70
  56. package/dist-cjs/predicate/encode.js +45 -229
  57. package/dist-cjs/predicate/from-json.js +1 -42
  58. package/dist-cjs/record/decode.js +3 -8
  59. package/dist-cjs/record/freshness.d.ts +17 -11
  60. package/dist-cjs/record/freshness.js +28 -18
  61. package/dist-cjs/review-card/builder.d.ts +4 -3
  62. package/dist-cjs/review-card/builder.js +23 -167
  63. package/dist-cjs/review-card/cross-check.js +7 -110
  64. package/dist-cjs/review-card/render-leaf.d.ts +4 -0
  65. package/dist-cjs/review-card/render-leaf.js +52 -0
  66. package/dist-cjs/run/index.d.ts +36 -139
  67. package/dist-cjs/run/index.js +125 -444
  68. package/dist-cjs/run/schemas.d.ts +168 -1929
  69. package/dist-cjs/run/schemas.js +41 -270
  70. package/dist-cjs/{synth → simulate}/deny-cases.d.ts +4 -8
  71. package/dist-cjs/simulate/deny-cases.js +286 -0
  72. package/dist-cjs/simulate/evaluate.d.ts +18 -0
  73. package/dist-cjs/simulate/evaluate.js +274 -0
  74. package/dist-cjs/simulate/index.d.ts +4 -0
  75. package/dist-cjs/simulate/index.js +13 -0
  76. package/dist-cjs/synth/compose-from-recording.d.ts +24 -51
  77. package/dist-cjs/synth/compose-from-recording.js +120 -282
  78. package/dist-cjs/synth/index.d.ts +0 -5
  79. package/dist-cjs/synth/index.js +1 -11
  80. package/dist-cjs/synth/synthesize-from-recording.d.ts +1 -29
  81. package/dist-cjs/synth/synthesize-from-recording.js +39 -354
  82. package/dist-cjs/types.d.ts +8 -60
  83. package/dist-cjs/types.js +6 -3
  84. package/package.json +5 -5
  85. package/src/adapters/interpreter/adapter.ts +76 -572
  86. package/src/errors.ts +0 -19
  87. package/src/index.ts +1 -4
  88. package/src/install/build-add-context-rule.ts +5 -139
  89. package/src/install/build-install-policy.ts +93 -214
  90. package/src/install/index.ts +0 -34
  91. package/src/predicate/decode.ts +2 -70
  92. package/src/predicate/encode.ts +49 -261
  93. package/src/predicate/from-json.ts +1 -43
  94. package/src/record/decode.ts +3 -8
  95. package/src/record/freshness.ts +29 -18
  96. package/src/review-card/builder.ts +19 -168
  97. package/src/review-card/cross-check.ts +3 -105
  98. package/src/review-card/render-leaf.ts +48 -0
  99. package/src/run/index.ts +144 -572
  100. package/src/run/schemas.ts +42 -291
  101. package/src/simulate/deny-cases.ts +334 -0
  102. package/src/simulate/evaluate.ts +284 -0
  103. package/src/simulate/index.ts +11 -0
  104. package/src/synth/compose-from-recording.ts +148 -347
  105. package/src/synth/index.ts +0 -13
  106. package/src/synth/synthesize-from-recording.ts +43 -456
  107. package/src/types.ts +13 -49
  108. package/dist/adapters/interpreter/index.d.ts +0 -1
  109. package/dist/adapters/interpreter/index.js +0 -2
  110. package/dist/adapters/oz/adapter.d.ts +0 -20
  111. package/dist/adapters/oz/adapter.js +0 -295
  112. package/dist/adapters/oz/index.d.ts +0 -1
  113. package/dist/adapters/oz/index.js +0 -2
  114. package/dist/codegen/compile-gate.d.ts +0 -33
  115. package/dist/codegen/compile-gate.js +0 -124
  116. package/dist/codegen/index.d.ts +0 -2
  117. package/dist/codegen/index.js +0 -8
  118. package/dist/codegen/template.d.ts +0 -18
  119. package/dist/codegen/template.js +0 -148
  120. package/dist/install/authority-overlap.d.ts +0 -134
  121. package/dist/install/authority-overlap.js +0 -0
  122. package/dist/install/build-install-predicate.d.ts +0 -96
  123. package/dist/install/build-install-predicate.js +0 -444
  124. package/dist/install/build-merge-policy.d.ts +0 -70
  125. package/dist/install/build-merge-policy.js +0 -130
  126. package/dist/install/plan-merge-policy.d.ts +0 -49
  127. package/dist/install/plan-merge-policy.js +0 -86
  128. package/dist/install/read-account-rules.d.ts +0 -100
  129. package/dist/install/read-account-rules.js +0 -283
  130. package/dist/ir/index.d.ts +0 -1
  131. package/dist/ir/index.js +0 -2
  132. package/dist/ir/types.d.ts +0 -140
  133. package/dist/ir/types.js +0 -11
  134. package/dist/mandate/index.d.ts +0 -2
  135. package/dist/mandate/index.js +0 -2
  136. package/dist/mandate/to-ir.d.ts +0 -3
  137. package/dist/mandate/to-ir.js +0 -60
  138. package/dist/mandate/types.d.ts +0 -20
  139. package/dist/mandate/types.js +0 -8
  140. package/dist/seams/index.d.ts +0 -1
  141. package/dist/seams/index.js +0 -2
  142. package/dist/seams/types.d.ts +0 -66
  143. package/dist/seams/types.js +0 -11
  144. package/dist/synth/deny-cases.js +0 -562
  145. package/dist/synth/evaluate.d.ts +0 -39
  146. package/dist/synth/evaluate.js +0 -551
  147. package/dist/synth/harness.d.ts +0 -28
  148. package/dist/synth/harness.js +0 -47
  149. package/dist/synth/minimize.d.ts +0 -4
  150. package/dist/synth/minimize.js +0 -38
  151. package/dist/synth/permit-context.d.ts +0 -15
  152. package/dist/synth/permit-context.js +0 -116
  153. package/dist/synth/predicate-literals.d.ts +0 -5
  154. package/dist/synth/predicate-literals.js +0 -25
  155. package/dist/synth/synthesize-from-mandate.d.ts +0 -20
  156. package/dist/synth/synthesize-from-mandate.js +0 -59
  157. package/dist/verify/envelope.d.ts +0 -15
  158. package/dist/verify/envelope.js +0 -22
  159. package/dist/verify/index.d.ts +0 -3
  160. package/dist/verify/index.js +0 -3
  161. package/dist/verify/simulate.d.ts +0 -31
  162. package/dist/verify/simulate.js +0 -258
  163. package/dist/verify/verify.d.ts +0 -21
  164. package/dist/verify/verify.js +0 -189
  165. package/dist-cjs/adapters/interpreter/index.d.ts +0 -1
  166. package/dist-cjs/adapters/interpreter/index.js +0 -8
  167. package/dist-cjs/adapters/oz/adapter.d.ts +0 -20
  168. package/dist-cjs/adapters/oz/adapter.js +0 -300
  169. package/dist-cjs/adapters/oz/index.d.ts +0 -1
  170. package/dist-cjs/adapters/oz/index.js +0 -8
  171. package/dist-cjs/codegen/compile-gate.d.ts +0 -33
  172. package/dist-cjs/codegen/compile-gate.js +0 -128
  173. package/dist-cjs/codegen/index.d.ts +0 -2
  174. package/dist-cjs/codegen/index.js +0 -14
  175. package/dist-cjs/codegen/template.d.ts +0 -18
  176. package/dist-cjs/codegen/template.js +0 -151
  177. package/dist-cjs/install/authority-overlap.d.ts +0 -134
  178. package/dist-cjs/install/authority-overlap.js +0 -0
  179. package/dist-cjs/install/build-install-predicate.d.ts +0 -96
  180. package/dist-cjs/install/build-install-predicate.js +0 -479
  181. package/dist-cjs/install/build-merge-policy.d.ts +0 -70
  182. package/dist-cjs/install/build-merge-policy.js +0 -134
  183. package/dist-cjs/install/plan-merge-policy.d.ts +0 -49
  184. package/dist-cjs/install/plan-merge-policy.js +0 -90
  185. package/dist-cjs/install/read-account-rules.d.ts +0 -100
  186. package/dist-cjs/install/read-account-rules.js +0 -296
  187. package/dist-cjs/ir/index.d.ts +0 -1
  188. package/dist-cjs/ir/index.js +0 -3
  189. package/dist-cjs/ir/types.d.ts +0 -140
  190. package/dist-cjs/ir/types.js +0 -12
  191. package/dist-cjs/mandate/index.d.ts +0 -2
  192. package/dist-cjs/mandate/index.js +0 -6
  193. package/dist-cjs/mandate/to-ir.d.ts +0 -3
  194. package/dist-cjs/mandate/to-ir.js +0 -63
  195. package/dist-cjs/mandate/types.d.ts +0 -20
  196. package/dist-cjs/mandate/types.js +0 -9
  197. package/dist-cjs/seams/index.d.ts +0 -1
  198. package/dist-cjs/seams/index.js +0 -3
  199. package/dist-cjs/seams/types.d.ts +0 -66
  200. package/dist-cjs/seams/types.js +0 -12
  201. package/dist-cjs/synth/deny-cases.js +0 -568
  202. package/dist-cjs/synth/evaluate.d.ts +0 -39
  203. package/dist-cjs/synth/evaluate.js +0 -554
  204. package/dist-cjs/synth/harness.d.ts +0 -28
  205. package/dist-cjs/synth/harness.js +0 -50
  206. package/dist-cjs/synth/minimize.d.ts +0 -4
  207. package/dist-cjs/synth/minimize.js +0 -41
  208. package/dist-cjs/synth/permit-context.d.ts +0 -15
  209. package/dist-cjs/synth/permit-context.js +0 -119
  210. package/dist-cjs/synth/predicate-literals.d.ts +0 -5
  211. package/dist-cjs/synth/predicate-literals.js +0 -28
  212. package/dist-cjs/synth/synthesize-from-mandate.d.ts +0 -20
  213. package/dist-cjs/synth/synthesize-from-mandate.js +0 -62
  214. package/dist-cjs/verify/envelope.d.ts +0 -15
  215. package/dist-cjs/verify/envelope.js +0 -23
  216. package/dist-cjs/verify/index.d.ts +0 -3
  217. package/dist-cjs/verify/index.js +0 -8
  218. package/dist-cjs/verify/simulate.d.ts +0 -31
  219. package/dist-cjs/verify/simulate.js +0 -261
  220. package/dist-cjs/verify/verify.d.ts +0 -21
  221. package/dist-cjs/verify/verify.js +0 -192
  222. package/src/adapters/interpreter/index.ts +0 -8
  223. package/src/adapters/oz/adapter.ts +0 -376
  224. package/src/adapters/oz/index.ts +0 -9
  225. package/src/codegen/compile-gate.ts +0 -167
  226. package/src/codegen/index.ts +0 -17
  227. package/src/codegen/template.ts +0 -165
  228. package/src/install/authority-overlap.ts +0 -0
  229. package/src/install/build-merge-policy.ts +0 -219
  230. package/src/install/plan-merge-policy.ts +0 -133
  231. package/src/install/read-account-rules.ts +0 -376
  232. package/src/ir/index.ts +0 -13
  233. package/src/ir/types.ts +0 -132
  234. package/src/mandate/index.ts +0 -4
  235. package/src/mandate/to-ir.ts +0 -71
  236. package/src/mandate/types.ts +0 -21
  237. package/src/seams/index.ts +0 -11
  238. package/src/seams/types.ts +0 -81
  239. package/src/synth/deny-cases.ts +0 -663
  240. package/src/synth/evaluate.ts +0 -613
  241. package/src/synth/harness.ts +0 -68
  242. package/src/synth/minimize.ts +0 -48
  243. package/src/synth/permit-context.ts +0 -136
  244. package/src/synth/predicate-literals.ts +0 -27
  245. package/src/synth/synthesize-from-mandate.ts +0 -82
  246. package/src/verify/envelope.ts +0 -28
  247. package/src/verify/index.ts +0 -5
  248. package/src/verify/simulate.ts +0 -311
  249. package/src/verify/verify.ts +0 -243
@@ -1,189 +0,0 @@
1
- // src/verify/verify.ts - the static minimality check for `verify_policy`.
2
- //
3
- // `verifyPolicy` proves the policy is MINIMAL: no top-level conjunct is
4
- // load-bearing-free. It is the static sibling of `simulatePolicy` and emits
5
- // `VERIFICATION_FAILED` (not `SIMULATION_ERROR`) on failure. The boundary is
6
- // pinned:
7
- //
8
- // - `VERIFICATION_FAILED` = STATIC minimality check failed. The policy is
9
- // structurally over-broad: a constraint could be dropped without losing
10
- // a deny-case. Surfaced by `verifyPolicy`. Runtime evaluation is not
11
- // part of this check; the policy may evaluate to a permit/deny just
12
- // fine, the failure is shape-only.
13
- //
14
- // - `SIMULATION_ERROR` = RUNTIME evaluation failed (see simulate.ts).
15
- // This module never emits SIMULATION_ERROR. A minimality failure is
16
- // never a simulation error and vice-versa.
17
- //
18
- // Algorithm:
19
- // 1. Build the permit EvalContext from `permitTx` (mirror of the
20
- // orchestrator's helper so verify is self-contained).
21
- // 2. Run `minimize(predicate, permitCtx)` to strip load-bearing-free
22
- // top-level conjuncts (only `and` predicates are minimisable; other
23
- // shapes are returned unchanged by `minimize`).
24
- // 3. If the minimised tree has fewer top-level conjuncts than the input,
25
- // return `VERIFICATION_FAILED` listing the dropped conjuncts by their
26
- // structural fingerprint.
27
- // 4. Otherwise `{ ok: true }`.
28
- //
29
- // Determinism: same `(predicate, permitTx)` -> byte-identical verdict.
30
- import { minimize } from "../synth/minimize.js";
31
- import { MAX_SCVAL_CLONE_DEPTH } from "../types.js";
32
- /** Run the static minimality check on a proposed predicate + recorded tx.
33
- * Returns `{ ok: true }` when the predicate is minimal (every top-level
34
- * conjunct carries load) and `VERIFICATION_FAILED` when a conjunct could
35
- * be dropped without losing a deny-case. The dropped conjuncts are
36
- * reported in `details.droppedConstraints` so the caller can render a
37
- * review-card warning. */
38
- export function verifyPolicy(predicate, permitTx, opts = {}) {
39
- const topLevel = permitTx.invocations[0];
40
- if (!topLevel) {
41
- return {
42
- ok: false,
43
- error: verificationFailed('recorded transaction has no top-level invocation to verify against', { droppedConstraints: [] }),
44
- };
45
- }
46
- let permitCtx;
47
- try {
48
- permitCtx = buildPermitContextForVerify(permitTx, topLevel, opts);
49
- }
50
- catch (e) {
51
- return {
52
- ok: false,
53
- error: verificationFailed(`could not build permit evaluation context: ${e.message}`, { droppedConstraints: [] }),
54
- };
55
- }
56
- // `minimize` only reduces `and` predicates; other shapes are returned
57
- // unchanged. A non-`and` predicate therefore trivially passes the static
58
- // minimality check (its top-level structure carries no removable
59
- // conjuncts). The runtime harness in `simulatePolicy` covers the
60
- // OR / NOT / comparison shapes.
61
- const minimised = minimize(predicate, permitCtx);
62
- // Drop count: only meaningful for `and`. For other shapes we already
63
- // returned the input unchanged; report ok.
64
- if (predicate.op !== 'and' || minimised.op !== 'and') {
65
- if (!structuralEqual(predicate, minimised)) {
66
- return {
67
- ok: false,
68
- error: verificationFailed('minimizer returned a structurally different tree for a non-and predicate', { droppedConstraints: [fingerprint(minimised)] }),
69
- };
70
- }
71
- return { ok: true, data: true };
72
- }
73
- const inputChildren = predicate.children;
74
- const minimisedChildren = minimised.children;
75
- if (minimisedChildren.length >= inputChildren.length) {
76
- return { ok: true, data: true };
77
- }
78
- // Over-broad: identify the dropped conjuncts by structural fingerprint
79
- // (so the review card can quote exactly which constraint was redundant).
80
- // We use a multiset comparison because two structurally identical
81
- // conjuncts (e.g. a duplicate `call_fn == transfer`) collapse to the
82
- // same fingerprint - the dropped item is the one whose fingerprint
83
- // count drops between input and minimised.
84
- const inputCounts = fingerprintCounts(inputChildren);
85
- const minimisedCounts = fingerprintCounts(minimisedChildren);
86
- const dropped = [];
87
- for (const [fp, count] of inputCounts) {
88
- const kept = minimisedCounts.get(fp) ?? 0;
89
- for (let i = 0; i < count - kept; i++)
90
- dropped.push(fp);
91
- }
92
- return {
93
- ok: false,
94
- error: verificationFailed(`policy is structurally over-broad: ${dropped.length} redundant conjunct(s) can be dropped without losing a deny case`, { droppedConstraints: dropped }),
95
- };
96
- }
97
- function buildPermitContextForVerify(tx, topLevel, opts) {
98
- const amountByToken = {};
99
- const totals = new Map();
100
- for (const m of tx.tokenMovements) {
101
- const current = totals.get(m.token) ?? 0n;
102
- totals.set(m.token, current + BigInt(m.amount));
103
- }
104
- for (const [token, total] of totals) {
105
- amountByToken[token] = total.toString();
106
- }
107
- const oraclePriceByAsset = {};
108
- if (opts.oraclePricesByAsset) {
109
- for (const [asset, entry] of Object.entries(opts.oraclePricesByAsset)) {
110
- oraclePriceByAsset[asset] = entry;
111
- }
112
- }
113
- const ctx = {
114
- contract: topLevel.contract,
115
- fn: topLevel.fn,
116
- args: topLevel.args.map(cloneScVal),
117
- atLedger: tx.ledgerSequence,
118
- nowSeconds: tx.fetchedAt,
119
- amountByToken,
120
- windowSpentByToken: {},
121
- invocationCountByWindow: {},
122
- oraclePriceByAsset,
123
- };
124
- if (opts.validUntilLedger !== undefined) {
125
- ctx.validUntilLedger = opts.validUntilLedger;
126
- }
127
- return ctx;
128
- }
129
- function cloneScVal(value, depth = 0) {
130
- // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
131
- // payload cannot RangeError the JS stack during context building. Over-depth
132
- // throws a ToolError-shaped error that the verifier's existing try/catch
133
- // converts to a structured `{ok:false, error}` (not a thrown RangeError).
134
- if (value.type === 'vec') {
135
- if (depth >= MAX_SCVAL_CLONE_DEPTH) {
136
- throw cloneDepthError(value);
137
- }
138
- return { type: 'vec', value: value.value.map((v) => cloneScVal(v, depth + 1)) };
139
- }
140
- return { ...value };
141
- }
142
- function cloneDepthError(value) {
143
- const err = new Error(`ScVal clone depth exceeds MAX_SCVAL_CLONE_DEPTH (${MAX_SCVAL_CLONE_DEPTH})`);
144
- err.code = 'VERIFICATION_FAILED';
145
- err.severity = 'error';
146
- err.retryable = false;
147
- err.depthContext = value.type;
148
- throw err;
149
- }
150
- function fingerprint(node) {
151
- return JSON.stringify(node, replacer);
152
- }
153
- /** Multiset fingerprint counts for a list of conjuncts. Two structurally
154
- * identical conjuncts (e.g. a duplicate `call_fn == transfer`) each
155
- * contribute their own count. The minimiser may drop one of them; we
156
- * surface exactly the surplus via the count difference. */
157
- function fingerprintCounts(children) {
158
- const counts = new Map();
159
- for (const child of children) {
160
- const fp = fingerprint(child);
161
- counts.set(fp, (counts.get(fp) ?? 0) + 1);
162
- }
163
- return counts;
164
- }
165
- /** Deterministic JSON key order for fingerprinting. Object keys are sorted
166
- * recursively so the same shape produces the same string. */
167
- function replacer(_key, value) {
168
- if (value && typeof value === 'object' && !Array.isArray(value)) {
169
- const obj = value;
170
- const sorted = {};
171
- for (const k of Object.keys(obj).sort()) {
172
- sorted[k] = obj[k];
173
- }
174
- return sorted;
175
- }
176
- return value;
177
- }
178
- function structuralEqual(a, b) {
179
- return fingerprint(a) === fingerprint(b);
180
- }
181
- function verificationFailed(message, details) {
182
- return {
183
- code: 'VERIFICATION_FAILED',
184
- message,
185
- severity: 'error',
186
- retryable: false,
187
- details,
188
- };
189
- }
@@ -1 +0,0 @@
1
- export { createInterpreterAdapter, type InterpreterAdapterConfig, ORACLE_DEFAULTS, PLACEHOLDER_INTERPRETER_ADDRESS, } from './adapter.ts';
@@ -1,8 +0,0 @@
1
- "use strict";
2
- // src/adapters/interpreter/index.ts - re-export the interpreter-policy CustodyAdapter.
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.PLACEHOLDER_INTERPRETER_ADDRESS = exports.ORACLE_DEFAULTS = exports.createInterpreterAdapter = void 0;
5
- var adapter_ts_1 = require("./adapter.js");
6
- Object.defineProperty(exports, "createInterpreterAdapter", { enumerable: true, get: function () { return adapter_ts_1.createInterpreterAdapter; } });
7
- Object.defineProperty(exports, "ORACLE_DEFAULTS", { enumerable: true, get: function () { return adapter_ts_1.ORACLE_DEFAULTS; } });
8
- Object.defineProperty(exports, "PLACEHOLDER_INTERPRETER_ADDRESS", { enumerable: true, get: function () { return adapter_ts_1.PLACEHOLDER_INTERPRETER_ADDRESS; } });
@@ -1,20 +0,0 @@
1
- import type { CustodyAdapter } from '../../seams/types.ts';
2
- import type { Network } from '../../types.ts';
3
- /** OZ built-in policy contract instance addresses, per primitive. */
4
- export interface OzPrimitiveInstances {
5
- spending_limit: string;
6
- simple_threshold: string;
7
- weighted_threshold: string;
8
- }
9
- /** Per-network config for the OZ adapter. */
10
- export interface OzAdapterConfig {
11
- network: Network;
12
- instances: OzPrimitiveInstances;
13
- }
14
- /** [VERIFY] NOT real deployed addresses. The OZ built-in policy instances are
15
- * per-network deploy artifacts we do not have yet; install is a later phase.
16
- * Injected so the adapter never invents a Stellar contract address. */
17
- export declare const PLACEHOLDER_OZ_INSTANCES: OzPrimitiveInstances;
18
- /** Week-1 OZ adapter config with placeholder instance addresses. */
19
- export declare function placeholderOzConfig(network: Network): OzAdapterConfig;
20
- export declare function createOzAdapter(config: OzAdapterConfig): CustodyAdapter;
@@ -1,300 +0,0 @@
1
- "use strict";
2
- // src/adapters/oz/adapter.ts - the OZ Accounts CustodyAdapter.
3
- //
4
- // Compiles a PolicyIR to an OZ `ProposedPolicy` using OZ built-in policy
5
- // primitives. Only the constructs OZ can express natively are lowered:
6
- // scope.contract -> ContextRuleType.call_contract (else default)
7
- // expiry.validUntilLedger -> ContextRuleDraft.validUntilLedger
8
- // window_spent(t,w) <= L -> `spending_limit` primitive
9
- // approval.threshold -> `simple_threshold` / `weighted_threshold`
10
- // Anything needing a capability this backend lacks (oracle price, invocation
11
- // count, per-arg comparison/allowlist, guard, nested boolean predicate) is NOT
12
- // emitted: it is named in `uncovered` and `covered` is set false. Nothing is
13
- // silently dropped.
14
- //
15
- // OZ built-in policy instance addresses are per-network deploy artifacts we do
16
- // not have yet (install is a later phase). They are injected via config; week-1
17
- // ships a clearly-labelled [VERIFY] placeholder so nothing invents an address.
18
- Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.PLACEHOLDER_OZ_INSTANCES = void 0;
20
- exports.placeholderOzConfig = placeholderOzConfig;
21
- exports.createOzAdapter = createOzAdapter;
22
- const types_ts_1 = require("../../types.js");
23
- /** [VERIFY] NOT real deployed addresses. The OZ built-in policy instances are
24
- * per-network deploy artifacts we do not have yet; install is a later phase.
25
- * Injected so the adapter never invents a Stellar contract address. */
26
- exports.PLACEHOLDER_OZ_INSTANCES = {
27
- spending_limit: 'VERIFY-oz-spending-limit-instance-address',
28
- simple_threshold: 'VERIFY-oz-simple-threshold-instance-address',
29
- weighted_threshold: 'VERIFY-oz-weighted-threshold-instance-address',
30
- };
31
- /** Week-1 OZ adapter config with placeholder instance addresses. */
32
- function placeholderOzConfig(network) {
33
- return { network, instances: exports.PLACEHOLDER_OZ_INSTANCES };
34
- }
35
- /** Parse confidence for a deterministic (non-decoded) input: full (1.0). A
36
- * mandate needs no decoding, so the gate is not applicable. */
37
- const FULL_PARSE_CONFIDENCE = {
38
- overall: 1,
39
- knownContracts: [],
40
- unknownContracts: [],
41
- opaqueScVals: [],
42
- thresholdUsed: 1,
43
- };
44
- const CAPABILITIES = {
45
- supportsSpendWindow: true,
46
- supportsThreshold: true,
47
- supportsTimeExpiry: true,
48
- supportsOraclePrice: false,
49
- supportsInvocationCount: false,
50
- supportsGeneralPredicate: false,
51
- };
52
- function createOzAdapter(config) {
53
- return {
54
- name: 'oz-accounts',
55
- mode: 'enforce',
56
- capabilities: () => ({ ...CAPABILITIES }),
57
- compile: (ir) => compile(ir, config),
58
- simulate: () => simulateStub(),
59
- export: (ir) => canonicalStringify(ir),
60
- };
61
- }
62
- function compile(ir, config) {
63
- const uncovered = [];
64
- const firstRule = ir.rules[0];
65
- if (!firstRule) {
66
- return { covered: false, uncovered: ['empty PolicyIR (no rules to compile)'] };
67
- }
68
- if (ir.rules.length > 1) {
69
- uncovered.push(`multi-rule PolicyIR: ${ir.rules.length - 1} rule(s) beyond the first are not compiled (a ProposedPolicy carries a single context rule in this slice)`);
70
- }
71
- const lowered = lowerRule(firstRule, config);
72
- uncovered.push(...lowered.uncovered);
73
- const result = { covered: uncovered.length === 0, uncovered };
74
- if (!lowered.capExceeded) {
75
- const proposed = {
76
- contextRule: lowered.contextRule,
77
- policyDocuments: [],
78
- policyRefs: lowered.policyRefs,
79
- parseConfidence: { ...FULL_PARSE_CONFIDENCE },
80
- warnings: [],
81
- ambiguities: [],
82
- };
83
- result.proposed = proposed;
84
- }
85
- return result;
86
- }
87
- function lowerRule(rule, config) {
88
- const uncovered = [];
89
- const policyRefs = [];
90
- // scope -> context rule type. OZ scopes by contract (CallContract); a
91
- // method-level restriction is flagged as not covered because CallContract
92
- // alone permits other methods on the same contract (e.g. an unbounded approve
93
- // alongside a capped transfer).
94
- const contextRuleType = rule.scope.contract !== undefined
95
- ? { kind: 'call_contract', contract: rule.scope.contract }
96
- : { kind: 'default' };
97
- if (rule.scope.method !== undefined && rule.scope.contract !== undefined) {
98
- uncovered.push(`per-method scoping to \`${rule.scope.method}\` (OZ CallContract scopes by contract only; requires the interpreter predicate)`);
99
- }
100
- if (rule.scope.chainId !== undefined) {
101
- uncovered.push(`chainId \`${rule.scope.chainId}\` not bindable by the Stellar OZ adapter (network is per-context, not per-rule)`);
102
- }
103
- if (rule.roles.length > 0) {
104
- uncovered.push(`roles [${rule.roles.join(', ')}] dropped (role-to-signer mapping is a later phase; OZ signers carry addresses, not role names)`);
105
- }
106
- // expiry -> validUntilLedger. Unix-timestamp expiry cannot be expressed by an
107
- // OZ context rule (it expires by ledger sequence), so flag it.
108
- let validUntilLedger = null;
109
- if (rule.expiry) {
110
- if (rule.expiry.validUntilLedger !== undefined) {
111
- validUntilLedger = rule.expiry.validUntilLedger;
112
- }
113
- else if (rule.expiry.validUntilUnixSeconds !== undefined) {
114
- uncovered.push('time expiry given as a unix timestamp (OZ context rules expire by ledger sequence; supply expiry.validUntilLedger)');
115
- }
116
- }
117
- // guard -> not covered (applicability predicates are not an OZ built-in).
118
- if (rule.guard) {
119
- uncovered.push(`guard: ${describeCondition(rule.guard)}`);
120
- }
121
- // constraints -> spending_limit where they match; else not covered. The OZ
122
- // spending_limit takes `{ spending_limit: i128, period_ledgers: u32 }` and
123
- // has NO token param: it only accepts a CallContract context rule
124
- // (OnlyCallContractAllowed) and limits transfers of that context's contract,
125
- // so the spent token must equal the scope contract, and the window is a
126
- // ledger count (~5s/ledger), not seconds.
127
- for (const c of rule.constraints) {
128
- const spend = matchSpendingLimit(c);
129
- if (!spend) {
130
- uncovered.push(describeCondition(c));
131
- continue;
132
- }
133
- if (contextRuleType.kind !== 'call_contract' || spend.token !== contextRuleType.contract) {
134
- uncovered.push(`spending_limit on token ${spend.token} needs a CallContract context scoped to that token (OZ pins the limit to the context contract, not a token param)`);
135
- continue;
136
- }
137
- policyRefs.push({
138
- kind: 'oz_builtin',
139
- primitive: {
140
- primitive: 'spending_limit',
141
- params: {
142
- spending_limit: spend.limit,
143
- period_ledgers: secondsToLedgers(spend.windowSeconds),
144
- },
145
- },
146
- instanceAddress: config.instances.spending_limit,
147
- });
148
- }
149
- // approval.threshold -> simple/weighted threshold primitive. A threshold < 1
150
- // is not a real M-of-N gate (0 approvals authorises everything), so refuse to
151
- // emit a no-op primitive and flag it as not covered.
152
- if (rule.approval) {
153
- if (!Number.isInteger(rule.approval.threshold) || rule.approval.threshold < 1) {
154
- uncovered.push(`approval threshold ${rule.approval.threshold} is not a positive integer (a 0 or negative threshold is not an M-of-N gate)`);
155
- }
156
- else {
157
- const weights = rule.approval.weights;
158
- if (weights && Object.keys(weights).length > 0) {
159
- policyRefs.push({
160
- kind: 'oz_builtin',
161
- primitive: {
162
- primitive: 'weighted_threshold',
163
- params: { threshold: rule.approval.threshold, weights },
164
- },
165
- instanceAddress: config.instances.weighted_threshold,
166
- });
167
- }
168
- else {
169
- policyRefs.push({
170
- kind: 'oz_builtin',
171
- primitive: {
172
- primitive: 'simple_threshold',
173
- params: { threshold: rule.approval.threshold },
174
- },
175
- instanceAddress: config.instances.simple_threshold,
176
- });
177
- }
178
- }
179
- }
180
- const capExceeded = policyRefs.length > types_ts_1.OZ_LIMITS.maxPoliciesPerRule;
181
- if (capExceeded) {
182
- uncovered.push(`policy count ${policyRefs.length} exceeds OZ maxPoliciesPerRule (${types_ts_1.OZ_LIMITS.maxPoliciesPerRule})`);
183
- }
184
- const contextRule = {
185
- contextRuleType,
186
- name: contextRuleType.kind === 'call_contract'
187
- ? `call_contract:${contextRuleType.contract}`
188
- : 'default',
189
- validUntilLedger,
190
- signers: [],
191
- policies: policyRefs,
192
- };
193
- return { contextRule, policyRefs, uncovered, capExceeded };
194
- }
195
- /** Convert a spend window in seconds to OZ `period_ledgers` (u32, >= 1).
196
- * Stellar targets a ~5s ledger close time. */
197
- function secondsToLedgers(windowSeconds) {
198
- return Math.max(1, Math.round(windowSeconds / types_ts_1.SOROBAN_LIMITS.secondsPerLedger));
199
- }
200
- /** Match the `window_spent(token, window) <= limit` compare that lowers to the
201
- * OZ `spending_limit` primitive. Only `lte` matches (the spend-cap semantic). */
202
- function matchSpendingLimit(c) {
203
- if (c.op !== 'compare')
204
- return null;
205
- const { selector, operator, value } = c.compare;
206
- if (selector.kind !== 'window_spent' || operator !== 'lte')
207
- return null;
208
- return { token: selector.token, limit: value, windowSeconds: selector.windowSeconds };
209
- }
210
- /** Human-readable descriptor for a construct the OZ built-in-primitive backend
211
- * cannot express, used to populate `uncovered`. */
212
- function describeCondition(cond) {
213
- switch (cond.op) {
214
- case 'slippage_floor':
215
- // OZ primitives bound a value against a constant; this bounds one call
216
- // argument against another, which none of them can express.
217
- return `slippage floor on arg[${cond.outArgIndex}] (OZ built-ins cannot bound one argument against another)`;
218
- case 'in':
219
- return `value allowlist on ${describeSelector(cond.selector)} (arg allowlist)`;
220
- case 'eq_seq':
221
- return `exact ordered sequence on ${describeSelector(cond.selector)} (OZ built-ins cannot express an exact vector)`;
222
- case 'not':
223
- return 'negated condition (predicate DSL)';
224
- case 'and':
225
- case 'or':
226
- return `nested ${cond.op} condition (predicate DSL)`;
227
- case 'compare': {
228
- const s = cond.compare.selector;
229
- switch (s.kind) {
230
- case 'oracle_price':
231
- return `oracle price condition on ${s.asset} (oracle price not supported in week-1)`;
232
- case 'invocation_count':
233
- return `invocation-count window (${s.windowSeconds}s) condition (not supported in week-1)`;
234
- case 'window_spent':
235
- return `spend-window comparison with operator '${cond.compare.operator}' (only 'lte' lowers to spending_limit)`;
236
- case 'amount':
237
- return `per-call amount comparison on ${s.token} (predicate DSL)`;
238
- case 'arg':
239
- return `argument comparison on arg ${s.argIndex} (predicate DSL)`;
240
- case 'arg_len':
241
- return `vec length comparison on arg ${s.argIndex} (predicate DSL)`;
242
- case 'arg_field':
243
- return `map field comparison on arg ${s.argIndex}.${s.field} (predicate DSL)`;
244
- case 'calldata':
245
- return 'EVM calldata comparison (predicate DSL)';
246
- case 'value':
247
- return 'tx.value comparison (predicate DSL)';
248
- case 'now':
249
- case 'valid_until':
250
- return 'time comparison (predicate DSL)';
251
- }
252
- }
253
- }
254
- }
255
- function describeSelector(s) {
256
- switch (s.kind) {
257
- case 'arg':
258
- return `arg ${s.argIndex}`;
259
- case 'arg_len':
260
- return `arg_len(${s.argIndex})`;
261
- case 'arg_field':
262
- return `arg_field(${s.argIndex}, ${s.element}, ${s.field})`;
263
- case 'amount':
264
- return `amount(${s.token})`;
265
- case 'window_spent':
266
- return `window_spent(${s.token})`;
267
- case 'oracle_price':
268
- return `oracle_price(${s.asset})`;
269
- case 'invocation_count':
270
- return `invocation_count(${s.windowSeconds}s)`;
271
- case 'calldata':
272
- return `calldata[${s.offset}:${s.offset + s.length}]`;
273
- default:
274
- return s.kind;
275
- }
276
- }
277
- function simulateStub() {
278
- return {
279
- backend: 'ts-model',
280
- permitted: null,
281
- evaluations: [],
282
- notes: ['stub: real permit/deny semantics wiring is a later phase'],
283
- };
284
- }
285
- /** Canonical JSON with recursively sorted object keys (stable across runs). */
286
- function canonicalStringify(value) {
287
- return JSON.stringify(sortKeys(value));
288
- }
289
- function sortKeys(value) {
290
- if (Array.isArray(value))
291
- return value.map(sortKeys);
292
- if (value && typeof value === 'object') {
293
- const out = {};
294
- for (const key of Object.keys(value).sort()) {
295
- out[key] = sortKeys(value[key]);
296
- }
297
- return out;
298
- }
299
- return value;
300
- }
@@ -1 +0,0 @@
1
- export { createOzAdapter, type OzAdapterConfig, type OzPrimitiveInstances, PLACEHOLDER_OZ_INSTANCES, placeholderOzConfig, } from './adapter.ts';
@@ -1,8 +0,0 @@
1
- "use strict";
2
- // src/adapters/oz/index.ts - re-export the OZ Accounts CustodyAdapter.
3
- Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.placeholderOzConfig = exports.PLACEHOLDER_OZ_INSTANCES = exports.createOzAdapter = void 0;
5
- var adapter_ts_1 = require("./adapter.js");
6
- Object.defineProperty(exports, "createOzAdapter", { enumerable: true, get: function () { return adapter_ts_1.createOzAdapter; } });
7
- Object.defineProperty(exports, "PLACEHOLDER_OZ_INSTANCES", { enumerable: true, get: function () { return adapter_ts_1.PLACEHOLDER_OZ_INSTANCES; } });
8
- Object.defineProperty(exports, "placeholderOzConfig", { enumerable: true, get: function () { return adapter_ts_1.placeholderOzConfig; } });
@@ -1,33 +0,0 @@
1
- export type CompileGateResult = {
2
- code: 'COMPILE_OK';
3
- } | {
4
- code: 'COMPILE_GATE_FAILED';
5
- stderr: string;
6
- } | {
7
- code: 'SKIPPED';
8
- reason: string;
9
- };
10
- export interface CompileGateOpts {
11
- /** Caller-controlled abort signal; aborting before toolchain probe resolves
12
- * the gate to `SKIPPED` rather than starting a cargo invocation. */
13
- signal?: AbortSignal;
14
- /** Override the `cargo` binary (mostly for tests). */
15
- cargoBin?: string;
16
- /** Override the target directory (mostly for tests). */
17
- tempDir?: string;
18
- }
19
- /** Probe the host for the Rust toolchain the gate requires. We require BOTH
20
- * `cargo` AND `stellar` (the Soroban CLI) because a real gate run invokes
21
- * `stellar contract build`; absent either, the gate returns `SKIPPED`. */
22
- export declare function hasRustToolchain(): Promise<boolean>;
23
- /** Compile-check a Rust source string against the pinned Soroban SDK.
24
- *
25
- * - Toolchain absent -> `{ code: 'SKIPPED', reason }` (NOT a failure).
26
- * - Toolchain present, source compiles -> `{ code: 'COMPILE_OK' }`.
27
- * - Toolchain present, source broken -> `{ code: 'COMPILE_GATE_FAILED', stderr }`.
28
- *
29
- * The gate writes the source to a temporary crate and runs `cargo check`
30
- * against it; the crate is cleaned up whether or not compilation succeeds.
31
- * The caller is expected to surface `COMPILE_GATE_FAILED.stderr` to the
32
- * user (the LLM agent) so the user can iterate. */
33
- export declare function compileCheck(rustSource: string, opts?: CompileGateOpts): Promise<CompileGateResult>;