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