@crediolabs/policy-synth 0.1.10 → 0.1.11

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 (81) hide show
  1. package/dist/adapters/interpreter/adapter.js +62 -11
  2. package/dist/errors.d.ts +1 -1
  3. package/dist/install/build-add-context-rule.d.ts +48 -0
  4. package/dist/install/build-add-context-rule.js +304 -0
  5. package/dist/ir/types.d.ts +4 -0
  6. package/dist/predicate/decode.d.ts +11 -0
  7. package/dist/predicate/decode.js +234 -0
  8. package/dist/predicate/encode.js +79 -14
  9. package/dist/predicate/from-json.d.ts +4 -0
  10. package/dist/predicate/from-json.js +113 -0
  11. package/dist/predicate/index.d.ts +2 -0
  12. package/dist/predicate/index.js +5 -1
  13. package/dist/registry/identify.js +21 -2
  14. package/dist/registry/protocols.d.ts +50 -1
  15. package/dist/registry/protocols.js +88 -0
  16. package/dist/review-card/builder.d.ts +13 -0
  17. package/dist/review-card/builder.js +31 -5
  18. package/dist/review-card/cross-check.js +12 -3
  19. package/dist/review-card/index.d.ts +1 -1
  20. package/dist/review-card/index.js +1 -1
  21. package/dist/run/schemas.d.ts +4 -4
  22. package/dist/synth/compose-from-recording.d.ts +4 -0
  23. package/dist/synth/compose-from-recording.js +34 -8
  24. package/dist/synth/deny-cases.d.ts +4 -1
  25. package/dist/synth/deny-cases.js +3 -1
  26. package/dist/synth/evaluate.js +130 -3
  27. package/dist/synth/permit-context.d.ts +15 -0
  28. package/dist/synth/permit-context.js +116 -0
  29. package/dist/synth/synthesize-from-recording.js +14 -2
  30. package/dist/types.d.ts +9 -0
  31. package/dist-cjs/adapters/interpreter/adapter.js +62 -11
  32. package/dist-cjs/errors.d.ts +1 -1
  33. package/dist-cjs/install/build-add-context-rule.d.ts +48 -0
  34. package/dist-cjs/install/build-add-context-rule.js +308 -0
  35. package/dist-cjs/ir/types.d.ts +4 -0
  36. package/dist-cjs/predicate/decode.d.ts +11 -0
  37. package/dist-cjs/predicate/decode.js +239 -0
  38. package/dist-cjs/predicate/encode.js +79 -14
  39. package/dist-cjs/predicate/from-json.d.ts +4 -0
  40. package/dist-cjs/predicate/from-json.js +116 -0
  41. package/dist-cjs/predicate/index.d.ts +2 -0
  42. package/dist-cjs/predicate/index.js +10 -2
  43. package/dist-cjs/registry/identify.js +20 -1
  44. package/dist-cjs/registry/protocols.d.ts +50 -1
  45. package/dist-cjs/registry/protocols.js +89 -1
  46. package/dist-cjs/review-card/builder.d.ts +13 -0
  47. package/dist-cjs/review-card/builder.js +32 -5
  48. package/dist-cjs/review-card/cross-check.js +12 -3
  49. package/dist-cjs/review-card/index.d.ts +1 -1
  50. package/dist-cjs/review-card/index.js +2 -1
  51. package/dist-cjs/run/schemas.d.ts +4 -4
  52. package/dist-cjs/synth/compose-from-recording.d.ts +4 -0
  53. package/dist-cjs/synth/compose-from-recording.js +34 -8
  54. package/dist-cjs/synth/deny-cases.d.ts +4 -1
  55. package/dist-cjs/synth/deny-cases.js +3 -0
  56. package/dist-cjs/synth/evaluate.js +130 -3
  57. package/dist-cjs/synth/permit-context.d.ts +15 -0
  58. package/dist-cjs/synth/permit-context.js +119 -0
  59. package/dist-cjs/synth/synthesize-from-recording.js +14 -2
  60. package/dist-cjs/types.d.ts +9 -0
  61. package/package.json +5 -2
  62. package/src/adapters/interpreter/adapter.ts +72 -11
  63. package/src/contracts/policy-template/OZ_POLICY_TRAIT.md +28 -3
  64. package/src/errors.ts +13 -0
  65. package/src/install/build-add-context-rule.ts +429 -0
  66. package/src/ir/types.ts +4 -0
  67. package/src/predicate/decode.ts +242 -0
  68. package/src/predicate/encode.ts +110 -13
  69. package/src/predicate/from-json.ts +124 -0
  70. package/src/predicate/index.ts +5 -1
  71. package/src/registry/identify.ts +22 -2
  72. package/src/registry/protocols.ts +90 -1
  73. package/src/review-card/builder.ts +31 -5
  74. package/src/review-card/cross-check.ts +12 -3
  75. package/src/review-card/index.ts +1 -0
  76. package/src/synth/compose-from-recording.ts +46 -7
  77. package/src/synth/deny-cases.ts +3 -1
  78. package/src/synth/evaluate.ts +131 -3
  79. package/src/synth/permit-context.ts +137 -0
  80. package/src/synth/synthesize-from-recording.ts +13 -2
  81. package/src/types.ts +12 -0
@@ -18,7 +18,7 @@
18
18
  // fails closed: a method call whose decoded args do NOT match the ABI
19
19
  // signature is treated as unknown.
20
20
  Object.defineProperty(exports, "__esModule", { value: true });
21
- exports.PROTOCOL_ABIS = exports.SOROSWAP_ABI = exports.BLEND_ABI = exports.SEP41_ABI = void 0;
21
+ exports.PROTOCOL_ABIS = exports.OZ_ACCOUNT_ABI = exports.SOROSWAP_ABI = exports.BLEND_ABI = exports.SEP41_ABI = void 0;
22
22
  exports.getAbi = getAbi;
23
23
  /** SEP-41 token interface - pinned from the SEP-41 spec (any token). */
24
24
  exports.SEP41_ABI = {
@@ -143,10 +143,98 @@ exports.SOROSWAP_ABI = {
143
143
  ],
144
144
  },
145
145
  };
146
+ /** OpenZeppelin smart-account ABI subset.
147
+ *
148
+ * Why this lives in the recogniser: every user's smart account has a
149
+ * different C-address, so a per-deployment pin would never cover them.
150
+ * What is the same across every OpenZeppelin multisig account is the
151
+ * small set of public context-rule entrypoints. A recording that
152
+ * invokes `batch_add_signer(u32, vec<signer>)` on an arbitrary contract
153
+ * is overwhelmingly likely to be calling the user's own OpenZeppelin
154
+ * smart account (the canonical reason this product exists); we
155
+ * recognise that pattern by interface, the same way SEP-41 is
156
+ * recognised by interface.
157
+ *
158
+ * SECURITY PROPERTY (load-bearing):
159
+ * - Recognition claims the call TARGETS a particular protocol. We
160
+ * only claim `oz_account` when the (fn, args) shape uniquely matches
161
+ * one of the three entrypoints below AND the call looks like a real
162
+ * context-rule operation. The match is exact: off-by-one arg count,
163
+ * off-by-one arg type, or a method name close-but-wrong returns null
164
+ * (fail-closed). A contract that incidentally happens to expose a
165
+ * single matching fn is not sufficient - the recorder requires ALL
166
+ * invocations to individually match, so a hostile contract with
167
+ * exactly one matching fn would still contribute to the unknown
168
+ * bucket for any other calls.
169
+ * - We do NOT claim `oz_account` for unknown calls, for arg-shape
170
+ * mismatches, or for calls where the recorder could not pin down
171
+ * the (fn, args) shape. The freshness gate then runs at the same
172
+ * 1.0 threshold - lowering the gate for unknown protocols remains
173
+ * a separate, opt-in production override (see RecordInput below).
174
+ *
175
+ * ABI source: packages/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
176
+ * pinned from the OpenZeppelin Reloaded `multisig_account_example`
177
+ * contract (commit ef82b65, fetched 2026-07-28).
178
+ *
179
+ * SCOPE NOTE: this ABI only covers the three entrypoints whose args
180
+ * map cleanly onto the normalised `AbiArgType` vocabulary (u32, vec,
181
+ * ...). `add_context_rule` - the install path - takes `(Symbol,
182
+ * String, Option<u32>, Vec<SignerKey>, Map<Address, Val>)`. The
183
+ * `String`, `Option<u32>` (`scvVoid`), and `Map<...>` arg types are
184
+ * not in the AbiArgType set today (the recogniser's `argsMatchAbi`
185
+ * helper rejects `other` deliberately so a close-but-wrong call does
186
+ * not slip through). Excluding `add_context_rule` is the right
187
+ * trade-off for now - it never blocks OZ smart-account recognition,
188
+ * because the install tx always follows a recognised
189
+ * `batch_add_signer` (the demo's first-pass tx), so the
190
+ * contract still ends up in `knownContracts`. Updating the Arg type
191
+ * vocabulary to cover these shapes is a separate concern (and would
192
+ * also lift the SEP-41 / Blend recognition in the same change).
193
+ */
194
+ exports.OZ_ACCOUNT_ABI = {
195
+ batch_add_signer: {
196
+ args: [
197
+ {
198
+ name: 'context_rule_id',
199
+ type: 'u32',
200
+ meaning: 'OZ context rule id this signer is added to',
201
+ },
202
+ {
203
+ name: 'signers',
204
+ type: 'vec',
205
+ meaning: 'vec<SignerKey> signers to add (Delegated G-address or Account C-address)',
206
+ },
207
+ ],
208
+ },
209
+ batch_remove_signer: {
210
+ args: [
211
+ {
212
+ name: 'context_rule_id',
213
+ type: 'u32',
214
+ meaning: 'OZ context rule id to remove signers from',
215
+ },
216
+ {
217
+ name: 'signers',
218
+ type: 'vec',
219
+ meaning: 'vec<SignerKey> signers to remove from the rule',
220
+ },
221
+ ],
222
+ },
223
+ remove_context_rule: {
224
+ args: [
225
+ {
226
+ name: 'context_rule_id',
227
+ type: 'u32',
228
+ meaning: 'OZ context rule id to delete',
229
+ },
230
+ ],
231
+ },
232
+ };
146
233
  exports.PROTOCOL_ABIS = {
147
234
  sep41: exports.SEP41_ABI,
148
235
  blend: exports.BLEND_ABI,
149
236
  soroswap: exports.SOROSWAP_ABI,
237
+ oz_account: exports.OZ_ACCOUNT_ABI,
150
238
  };
151
239
  function getAbi(protocol) {
152
240
  return exports.PROTOCOL_ABIS[protocol];
@@ -12,3 +12,16 @@ export interface ReviewCardSummary {
12
12
  /** Build a deterministic review-card summary from a policy + context rule +
13
13
  * simulation result. Pure: same inputs -> byte-identical output. */
14
14
  export declare function buildReviewCardSummary(predicate: PredicateNode | null, policyRefs: PolicyRef[], contextRule: ContextRuleDraft, simulation: SimulationResult): ReviewCardSummary;
15
+ /** Walk every comparison / membership node of the predicate and invoke
16
+ * `visit` on each. The walk is depth-first, left-to-right, so the
17
+ * constraint list is stable across runs. Pure boolean nodes contribute no
18
+ * constraint lines themselves; their leaf children do, via the visitor. */
19
+ /** Every constraint sentence for one predicate, in walk order.
20
+ *
21
+ * `buildReviewCardSummary` renders a policy the synthesiser just PRODUCED,
22
+ * and needs the refs / context rule / simulation to do it. This renders a
23
+ * predicate on its own, which is what a caller holding a policy already
24
+ * INSTALLED on chain has: it can read the document out of the interpreter's
25
+ * storage and decode it, but there is no proposal around it. Same renderers,
26
+ * so an installed rule reads exactly as it did on the review card. */
27
+ export declare function describePredicate(predicate: PredicateNode): string[];
@@ -17,7 +17,7 @@
17
17
  //
18
18
  // 2. The interpreter `PredicateNode`. One string per constraint leaf,
19
19
  // rendered by enclosing-comparison kind. Templates (Task 7b):
20
- // - invocation_count_in_window <= N -> Invocations <= N per <window> seconds
20
+ // - invocation_count_in_window < N -> At most N calls per <window> seconds
21
21
  // - call_arg[i] in [list] -> Recipient/arg must be one of [list]
22
22
  // - eq(call_arg[i], literal_vec[...]) -> Path must be exactly [list]
23
23
  // - oracle_price(asset) OP price -> Only when oracle_price(asset) OP price
@@ -31,6 +31,7 @@
31
31
  // hash. There is no clock; the hash never includes a timestamp.
32
32
  Object.defineProperty(exports, "__esModule", { value: true });
33
33
  exports.buildReviewCardSummary = buildReviewCardSummary;
34
+ exports.describePredicate = describePredicate;
34
35
  const node_crypto_1 = require("node:crypto");
35
36
  /** Build a deterministic review-card summary from a policy + context rule +
36
37
  * simulation result. Pure: same inputs -> byte-identical output. */
@@ -84,6 +85,23 @@ function renderOzPrimitive(ref) {
84
85
  * `visit` on each. The walk is depth-first, left-to-right, so the
85
86
  * constraint list is stable across runs. Pure boolean nodes contribute no
86
87
  * constraint lines themselves; their leaf children do, via the visitor. */
88
+ /** Every constraint sentence for one predicate, in walk order.
89
+ *
90
+ * `buildReviewCardSummary` renders a policy the synthesiser just PRODUCED,
91
+ * and needs the refs / context rule / simulation to do it. This renders a
92
+ * predicate on its own, which is what a caller holding a policy already
93
+ * INSTALLED on chain has: it can read the document out of the interpreter's
94
+ * storage and decode it, but there is no proposal around it. Same renderers,
95
+ * so an installed rule reads exactly as it did on the review card. */
96
+ function describePredicate(predicate) {
97
+ const constraints = [];
98
+ walkPredicate(predicate, (node) => {
99
+ const line = renderConstraint(node);
100
+ if (line !== null)
101
+ constraints.push(line);
102
+ });
103
+ return constraints;
104
+ }
87
105
  function walkPredicate(node, visit) {
88
106
  switch (node.op) {
89
107
  case 'and':
@@ -171,17 +189,20 @@ function renderComparison(node) {
171
189
  return `${head} ${sep} [${right.elements.map(renderVecElement).join(', ')}]`;
172
190
  }
173
191
  }
174
- // invocation_count_in_window <= N -> Invocations <= N per <window> seconds
192
+ // The bound is compared against the calls ALREADY made in the window, so
193
+ // `< N` permits N of them and `<= N` permits one more. Report how many
194
+ // calls the rule allows rather than restating the comparison.
175
195
  if (left.kind === 'invocation_count_in_window' && right.kind === 'literal_u32') {
176
- return `Invocations <= ${right.value} per ${left.windowSecs} seconds`;
196
+ const allowed = node.op === 'lt' ? right.value : right.value + 1;
197
+ return `At most ${allowed} calls per ${left.windowSecs} seconds`;
177
198
  }
178
199
  // amount <= v -> Amount <= v
179
200
  if (left.kind === 'amount' && right.kind === 'literal_i128') {
180
201
  return `Amount <= ${right.value}`;
181
202
  }
182
203
  // oracle_price(asset) OP price -> Only when oracle_price(asset) OP price
183
- if (left.kind === 'oracle_price' && right.kind === 'literal_i128') {
184
- return `Only when oracle_price(${left.asset}) ${comparisonOpText(node.op)} ${right.value}`;
204
+ if (left.kind === 'oracle_price' && right.kind === 'oracle_threshold') {
205
+ return `Only when oracle_price(${left.asset}) ${comparisonOpText(node.op)} ${right.value} (${right.decimals} dp)`;
185
206
  }
186
207
  // Any other comparison shape is a structural fail-closed: do not surface
187
208
  // a misleading line. Cross-check still requires every leaf produce a
@@ -219,6 +240,7 @@ function renderVecElement(leaf) {
219
240
  case 'call_arg':
220
241
  case 'call_arg_len':
221
242
  case 'call_arg_field':
243
+ case 'call_arg_scaled':
222
244
  case 'amount':
223
245
  case 'window_spent':
224
246
  case 'now':
@@ -226,6 +248,11 @@ function renderVecElement(leaf) {
226
248
  case 'invocation_count_in_window':
227
249
  case 'oracle_price':
228
250
  return `<${leaf.kind}>`;
251
+ // Show the declared basis, not just the digits. A threshold on the wrong
252
+ // basis is the one policy error the contract cannot detect, so the review
253
+ // card is where a human has to be able to see it.
254
+ case 'oracle_threshold':
255
+ return `${leaf.value} (${leaf.decimals} dp)`;
229
256
  }
230
257
  }
231
258
  function renderHaystackElement(leaf) {
@@ -108,16 +108,19 @@ function pushComparison(left, right, op, out) {
108
108
  return;
109
109
  }
110
110
  }
111
+ // Mirrors the builder's wording byte-for-byte: how many calls the rule
112
+ // permits, since the bound counts the calls already made.
111
113
  if (left.kind === 'invocation_count_in_window' && right.kind === 'literal_u32') {
112
- out.push(`Invocations <= ${right.value} per ${left.windowSecs} seconds`);
114
+ const allowed = op === 'lt' ? right.value : right.value + 1;
115
+ out.push(`At most ${allowed} calls per ${left.windowSecs} seconds`);
113
116
  return;
114
117
  }
115
118
  if (left.kind === 'amount' && right.kind === 'literal_i128') {
116
119
  out.push(`Amount <= ${right.value}`);
117
120
  return;
118
121
  }
119
- if (left.kind === 'oracle_price' && right.kind === 'literal_i128') {
120
- out.push(`Only when oracle_price(${left.asset}) ${comparisonOpText(op)} ${right.value}`);
122
+ if (left.kind === 'oracle_price' && right.kind === 'oracle_threshold') {
123
+ out.push(`Only when oracle_price(${left.asset}) ${comparisonOpText(op)} ${right.value} (${right.decimals} dp)`);
121
124
  return;
122
125
  }
123
126
  }
@@ -148,6 +151,7 @@ function renderVecElement(leaf) {
148
151
  case 'call_arg':
149
152
  case 'call_arg_len':
150
153
  case 'call_arg_field':
154
+ case 'call_arg_scaled':
151
155
  case 'amount':
152
156
  case 'window_spent':
153
157
  case 'now':
@@ -155,6 +159,11 @@ function renderVecElement(leaf) {
155
159
  case 'invocation_count_in_window':
156
160
  case 'oracle_price':
157
161
  return `<${leaf.kind}>`;
162
+ // Show the declared basis, not just the digits. A threshold on the wrong
163
+ // basis is the one policy error the contract cannot detect, so the review
164
+ // card is where a human has to be able to see it.
165
+ case 'oracle_threshold':
166
+ return `${leaf.value} (${leaf.decimals} dp)`;
158
167
  }
159
168
  }
160
169
  function renderHaystackElement(leaf) {
@@ -1,3 +1,3 @@
1
- export { buildReviewCardSummary, type ReviewCardSummary, } from './builder.ts';
1
+ export { buildReviewCardSummary, describePredicate, type ReviewCardSummary, } from './builder.ts';
2
2
  export { type ConflictAnnotation, classifyConflict, type RuleRef, } from './conflict.ts';
3
3
  export { summaryCrossCheck } from './cross-check.ts';
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  // src/review-card/index.ts - re-export the deterministic review-card surface.
3
3
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.summaryCrossCheck = exports.classifyConflict = exports.buildReviewCardSummary = void 0;
4
+ exports.summaryCrossCheck = exports.classifyConflict = exports.describePredicate = exports.buildReviewCardSummary = void 0;
5
5
  var builder_ts_1 = require("./builder.js");
6
6
  Object.defineProperty(exports, "buildReviewCardSummary", { enumerable: true, get: function () { return builder_ts_1.buildReviewCardSummary; } });
7
+ Object.defineProperty(exports, "describePredicate", { enumerable: true, get: function () { return builder_ts_1.describePredicate; } });
7
8
  var conflict_ts_1 = require("./conflict.js");
8
9
  Object.defineProperty(exports, "classifyConflict", { enumerable: true, get: function () { return conflict_ts_1.classifyConflict; } });
9
10
  var cross_check_ts_1 = require("./cross-check.js");
@@ -1093,13 +1093,13 @@ export declare const SynthesizePolicyRecordingInputSchema: z.ZodObject<{
1093
1093
  network: "mainnet" | "testnet";
1094
1094
  source: "recording";
1095
1095
  recordedTx: {
1096
+ signers: string[];
1096
1097
  events: {
1097
1098
  contract: string;
1098
1099
  topics: string[];
1099
1100
  data?: unknown;
1100
1101
  }[];
1101
1102
  network: "mainnet" | "testnet";
1102
- signers: string[];
1103
1103
  invocations: unknown[];
1104
1104
  tokenMovements: {
1105
1105
  amount: string;
@@ -1158,13 +1158,13 @@ export declare const SynthesizePolicyRecordingInputSchema: z.ZodObject<{
1158
1158
  network: "mainnet" | "testnet";
1159
1159
  source: "recording";
1160
1160
  recordedTx: {
1161
+ signers: string[];
1161
1162
  events: {
1162
1163
  contract: string;
1163
1164
  topics: string[];
1164
1165
  data?: unknown;
1165
1166
  }[];
1166
1167
  network: "mainnet" | "testnet";
1167
- signers: string[];
1168
1168
  invocations: unknown[];
1169
1169
  tokenMovements: {
1170
1170
  amount: string;
@@ -1750,13 +1750,13 @@ export declare const SynthesizePolicyInputSchema: z.ZodDiscriminatedUnion<"sourc
1750
1750
  network: "mainnet" | "testnet";
1751
1751
  source: "recording";
1752
1752
  recordedTx: {
1753
+ signers: string[];
1753
1754
  events: {
1754
1755
  contract: string;
1755
1756
  topics: string[];
1756
1757
  data?: unknown;
1757
1758
  }[];
1758
1759
  network: "mainnet" | "testnet";
1759
- signers: string[];
1760
1760
  invocations: unknown[];
1761
1761
  tokenMovements: {
1762
1762
  amount: string;
@@ -1815,13 +1815,13 @@ export declare const SynthesizePolicyInputSchema: z.ZodDiscriminatedUnion<"sourc
1815
1815
  network: "mainnet" | "testnet";
1816
1816
  source: "recording";
1817
1817
  recordedTx: {
1818
+ signers: string[];
1818
1819
  events: {
1819
1820
  contract: string;
1820
1821
  topics: string[];
1821
1822
  data?: unknown;
1822
1823
  }[];
1823
1824
  network: "mainnet" | "testnet";
1824
- signers: string[];
1825
1825
  invocations: unknown[];
1826
1826
  tokenMovements: {
1827
1827
  amount: string;
@@ -8,6 +8,10 @@ export interface OraclePriceBound {
8
8
  asset: string;
9
9
  operator: IRCompOp;
10
10
  value: string;
11
+ /** Decimal basis `value` is written on. REQUIRED: oracle prices normalise to
12
+ * 9 dp, and a threshold silently assumed to share that basis is what let a
13
+ * raw 14-dp bound permit everything. The author states it; we convert. */
14
+ decimals: number;
11
15
  }
12
16
  /** Caller-supplied answers to the ambiguity prompts. Every numeric bound the
13
17
  * synth might apply must come from here - the recording supplies observed
@@ -108,11 +108,17 @@ function composeFromRecording(facts, scopeContract, topLevel, opts) {
108
108
  value: limit,
109
109
  },
110
110
  };
111
- if (!interpreterEnabled || token === scopeContract) {
112
- ozConstraints.push(spendCond);
113
- }
114
- else {
115
- interpreterConstraints.push(spendCond);
111
+ // A rolling spend cap always goes to OZ, whose `spending_limit` is the
112
+ // audited implementation. The interpreter is NOT a fallback for the
113
+ // token != scopeContract case: on chain it sees one authorized call,
114
+ // not the transaction's token movements, so it has no per-call amount
115
+ // to accumulate and the counter would never move. OZ reports the case
116
+ // it cannot cover (it pins the limit to the context contract), which
117
+ // is the honest outcome - the old fallback produced an interpreter
118
+ // predicate that silently never bound.
119
+ ozConstraints.push(spendCond);
120
+ if (interpreterEnabled && token !== scopeContract) {
121
+ warnings.push(`rolling spend cap on ${token} cannot be enforced on chain: OZ spending_limit pins the limit to the context contract, and the interpreter cannot observe token movements. Bound the per-call value with an argument cap plus an invocation-count limit instead.`);
116
122
  }
117
123
  }
118
124
  }
@@ -137,7 +143,10 @@ function composeFromRecording(facts, scopeContract, topLevel, opts) {
137
143
  op: 'compare',
138
144
  compare: {
139
145
  selector: { kind: 'invocation_count', windowSeconds },
140
- operator: 'lte',
146
+ // `lt`, not `lte`: the leaf reports the calls ALREADY made in the
147
+ // window, so `< N` is what permits N of them. With `lte` a limit
148
+ // of N let an N+1th call through.
149
+ operator: 'lt',
141
150
  value: String(invocationLimit),
142
151
  },
143
152
  };
@@ -168,6 +177,7 @@ function composeFromRecording(facts, scopeContract, topLevel, opts) {
168
177
  selector: { kind: 'oracle_price', asset: b.asset },
169
178
  operator: b.operator,
170
179
  value: b.value,
180
+ valueDecimals: b.decimals,
171
181
  },
172
182
  };
173
183
  if (interpreterEnabled) {
@@ -303,8 +313,15 @@ function appendProtocolSpecificConstraints(ozConstraints, interpreterConstraints
303
313
  });
304
314
  for (let i = 0; i < elements.length; i++) {
305
315
  const element = elements[i];
306
- if (!element || element.type !== 'map')
316
+ // An element we cannot bind leaves that request's action, asset and
317
+ // amount free while the length pin makes the policy LOOK total. The
318
+ // length pin still stays (it is a real restriction, and dropping it
319
+ // would only widen the policy) - what must not happen is dropping the
320
+ // element quietly.
321
+ if (element?.type !== 'map') {
322
+ warnings.push(`Blend submit requests element ${i} is not a Request map (recorded as ${element?.type ?? 'nothing'}): its request_type, address and amount are NOT pinned, so any action on any asset for any amount is permitted in that position`);
307
323
  continue;
324
+ }
308
325
  const fields = element.value;
309
326
  const fieldValue = (name, scalarType) => {
310
327
  const entry = fields.find((e) => e.key === name);
@@ -321,8 +338,17 @@ function appendProtocolSpecificConstraints(ozConstraints, interpreterConstraints
321
338
  const address = fieldValue('address', 'address');
322
339
  const amount = fieldValue('amount', 'i128');
323
340
  const requestType = fieldValue('request_type', 'u32');
324
- if (address === null || amount === null || requestType === null)
341
+ if (address === null || amount === null || requestType === null) {
342
+ const missing = [
343
+ requestType === null ? 'request_type (u32)' : null,
344
+ address === null ? 'address' : null,
345
+ amount === null ? 'amount (i128)' : null,
346
+ ].filter((f) => f !== null);
347
+ // Partial pins are deliberately NOT emitted (see the note above): a
348
+ // half-pinned request reads as a bound one on the review card.
349
+ warnings.push(`Blend submit requests element ${i} could not be bound: ${missing.join(', ')} missing or of an unexpected type. That request's request_type, address and amount are NOT pinned, so any action on any asset for any amount is permitted in that position`);
325
350
  continue;
351
+ }
326
352
  interpreterConstraints.push({
327
353
  op: 'compare',
328
354
  compare: {
@@ -1,4 +1,4 @@
1
- import type { PredicateNode } from '../types.ts';
1
+ import type { PredicateNode, ScVal } from '../types.ts';
2
2
  import type { EvalContext } from './evaluate.ts';
3
3
  export interface DenyCase {
4
4
  dimension: string;
@@ -20,3 +20,6 @@ export { ORIGINAL_DIMENSIONS, OVERPERMISSIVE_DIMENSIONS };
20
20
  * are emitted. The synth pipeline passes ORIGINAL_DIMENSIONS so
21
21
  * existing fixtures do not regress. */
22
22
  export declare function generateCases(predicate: PredicateNode, permitCtx: EvalContext, dimensions?: string[]): GeneratedCases;
23
+ /** Deep-copy an ScVal so a mutation cannot alias the recorded call.
24
+ * Exported so the permit-context builder shares this one implementation. */
25
+ export declare function cloneScVal(value: ScVal, depth?: number): ScVal;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OVERPERMISSIVE_DIMENSIONS = exports.ORIGINAL_DIMENSIONS = void 0;
4
4
  exports.generateCases = generateCases;
5
+ exports.cloneScVal = cloneScVal;
5
6
  const types_ts_1 = require("../types.js");
6
7
  const predicate_literals_ts_1 = require("./predicate-literals.js");
7
8
  const ORACLE_CASES = [
@@ -481,6 +482,8 @@ function cloneContext(ctx) {
481
482
  cloned.signerWeights = { ...ctx.signerWeights };
482
483
  return cloned;
483
484
  }
485
+ /** Deep-copy an ScVal so a mutation cannot alias the recorded call.
486
+ * Exported so the permit-context builder shares this one implementation. */
484
487
  function cloneScVal(value, depth = 0) {
485
488
  // Recursion is bounded by MAX_SCVAL_CLONE_DEPTH so a hand-crafted nested-vec
486
489
  // payload cannot RangeError the JS stack during deny-case mutation. Over-depth
@@ -32,6 +32,11 @@
32
32
  Object.defineProperty(exports, "__esModule", { value: true });
33
33
  exports.evaluate = evaluate;
34
34
  const predicate_literals_ts_1 = require("./predicate-literals.js");
35
+ /** Oracle prices normalise to this many decimals; mirrors NORMALISED_DECIMALS
36
+ * in oracle.rs. A threshold on any other basis must say so. */
37
+ const NORMALISED_DECIMALS = 9;
38
+ /** Mirrors MAX_ORACLE_THRESHOLD_DECIMALS in dsl.rs. */
39
+ const MAX_ORACLE_THRESHOLD_DECIMALS = 18;
35
40
  /** Internal fatal thrown by the oracle path; caught at the top of `evaluate`
36
41
  * and converted to the matching `ORACLE_*` deny reason. NOT a
37
42
  * boolean-false that `not` / `or` could mask. */
@@ -168,6 +173,13 @@ function evalCompare(op, left, right, ctx) {
168
173
  }
169
174
  // --- step 4b: call_arg comparison (eq / exact-vec, or an ordered numeric bound) ---
170
175
  if (left.kind === 'call_arg') {
176
+ // The swap's canonical form is `call_arg[out] >= call_arg_scaled(in, num, den)`.
177
+ // Dispatched here so the floor's dedicated reason codes (ARITHMETIC_OVERFLOW
178
+ // -> SLIPPAGE_FLOOR) reach the user; routing the scaled RHS through the
179
+ // generic `evalArgOrderedCompare` would mask overflow as ARG_MISMATCH.
180
+ if (right.kind === 'call_arg_scaled') {
181
+ return evalScaledArgCompare(op, left, right, ctx);
182
+ }
171
183
  const actual = ctx.args[left.index];
172
184
  // An ordered comparison (lt/lte/gt/gte) reads the arg as an integer and
173
185
  // compares it to a numeric literal via BigInt (e.g. a SoroSwap input-amount
@@ -178,6 +190,11 @@ function evalCompare(op, left, right, ctx) {
178
190
  return evalArgOrderedCompare(op, actual, right);
179
191
  return evalArgEq(op, actual, right, ctx);
180
192
  }
193
+ // --- step 4b': scaled leaf on the LEFT (`call_arg_scaled(in, num, den) <= call_arg[out]`).
194
+ // Symmetric form so a policy that phrases the floor either way works.
195
+ if (left.kind === 'call_arg_scaled') {
196
+ return evalScaledArgCompare(op, right, left, ctx);
197
+ }
181
198
  // --- step 4c: call_arg_len: the length of a vec-typed argument as a u32.
182
199
  // Fails closed on a non-vec arg, an absent arg, or a non-u32 literal.
183
200
  if (left.kind === 'call_arg_len') {
@@ -296,6 +313,102 @@ function evalArgEq(op, actual, right, ctx) {
296
313
  return { permit: false, reason: 'ARG_MISMATCH' };
297
314
  return { permit: false, reason: 'ARG_MISMATCH' };
298
315
  }
316
+ /** Step 4b': slippage-floor comparison. Mirrors the Rust `eval_scaled_arg_compare`
317
+ * path: the scaled leaf is `args[index] * num / den` (truncating toward
318
+ * zero). On `checked_mul` / `checked_div` failure (overflow or
319
+ * divide-by-zero) the comparison denies with `ARITHMETIC_OVERFLOW`. A
320
+ * failed comparison denies with `SLIPPAGE_FLOOR` (the dedicated reason)
321
+ * rather than the generic `ARG_MISMATCH`.
322
+ *
323
+ * `left` is whichever side of the compare is NOT the scaled leaf. A
324
+ * scaled-on-scaled compare denies `ARG_MISMATCH` (pipelining two scaled
325
+ * leaves has no definable semantics). The other operand must be a
326
+ * numeric shape (`call_arg` carrying a number, or a numeric literal);
327
+ * anything else is `ARG_MISMATCH`. */
328
+ function evalScaledArgCompare(op, left, right, ctx) {
329
+ // Identify which side is scaled, and pull the other side as a number.
330
+ let scaled;
331
+ let other;
332
+ let scaledOnRight;
333
+ if (left.kind === 'call_arg_scaled') {
334
+ scaled = left;
335
+ other = right;
336
+ scaledOnRight = false;
337
+ }
338
+ else if (right.kind === 'call_arg_scaled') {
339
+ scaled = right;
340
+ other = left;
341
+ scaledOnRight = true;
342
+ }
343
+ else {
344
+ // Neither side is scaled - this is a programming error in the
345
+ // dispatcher; the contract returns ARG_MISMATCH to fail closed.
346
+ return { permit: false, reason: 'ARG_MISMATCH' };
347
+ }
348
+ // Source `args[index]` -> BigInt. An out-of-bounds index or a
349
+ // non-numeric arg fails closed as ARG_MISMATCH (not SLIPPAGE_FLOOR) -
350
+ // a violated floor is the wrong code when the operand itself could
351
+ // not be read.
352
+ if (scaled.index >= ctx.args.length) {
353
+ return { permit: false, reason: 'ARG_MISMATCH' };
354
+ }
355
+ const input = argNumericBigInt(ctx.args[scaled.index]);
356
+ if (input === null)
357
+ return { permit: false, reason: 'ARG_MISMATCH' };
358
+ let num;
359
+ let den;
360
+ try {
361
+ num = BigInt(scaled.num);
362
+ den = BigInt(scaled.den);
363
+ }
364
+ catch {
365
+ return { permit: false, reason: 'ARG_MISMATCH' };
366
+ }
367
+ // Install refuses `den == 0` and `num <= 0` / `den <= 0`. The runtime
368
+ // check is a defensive belt-and-braces - a future validator
369
+ // regression cannot panic the frame on a divide-by-zero.
370
+ if (den === 0n)
371
+ return { permit: false, reason: 'ARITHMETIC_OVERFLOW' };
372
+ const product = input * num;
373
+ // BigInt overflow is silent in JS (it does not throw on multiplication).
374
+ // We can detect over-range by dividing and checking the result against
375
+ // i128 bounds, but the more practical check is whether the result
376
+ // divides cleanly. We rely on BigInt's arbitrary precision and then
377
+ // surface ARITHMETIC_OVERFLOW if the result is outside i128.
378
+ let scaledValue;
379
+ try {
380
+ // BigInt division truncates toward zero (matches Rust `i128::checked_div`).
381
+ scaledValue = product / den;
382
+ }
383
+ catch {
384
+ return { permit: false, reason: 'ARITHMETIC_OVERFLOW' };
385
+ }
386
+ // i128 range check: if the scaled value is outside i128, the contract
387
+ // would have wrapped on i128 arithmetic; surface the same deny.
388
+ const I128_MAX = (1n << 127n) - 1n;
389
+ const I128_MIN = -(1n << 127n);
390
+ if (scaledValue > I128_MAX || scaledValue < I128_MIN) {
391
+ return { permit: false, reason: 'ARITHMETIC_OVERFLOW' };
392
+ }
393
+ // Resolving the operand when the scaled side is on the right: the
394
+ // operand is `left`; the scaled value is the RHS. The AST order is
395
+ // `left <op> scaled`, so the comparator applies to `other <op> scaled`.
396
+ // When the scaled side is on the left, the order is `scaled <op> other`,
397
+ // i.e. `scaled <op> other_val`.
398
+ let otherVal;
399
+ if (other.kind === 'call_arg') {
400
+ otherVal = argNumericBigInt(ctx.args[other.index]);
401
+ }
402
+ else {
403
+ otherVal = (0, predicate_literals_ts_1.literalNumericBigInt)(other);
404
+ }
405
+ if (otherVal === null)
406
+ return { permit: false, reason: 'ARG_MISMATCH' };
407
+ const pass = scaledOnRight
408
+ ? bigintCmp(op, otherVal.toString(), scaledValue.toString())
409
+ : bigintCmp(op, scaledValue.toString(), otherVal.toString());
410
+ return pass ? { permit: true } : { permit: false, reason: 'SLIPPAGE_FLOOR' };
411
+ }
299
412
  /** Ordered numeric comparison (lt/lte/gt/gte) on a `call_arg`. The interpreter
300
413
  * reads the arg as an integer (i128 / u64 / u32 on the recorder's ScVal
301
414
  * surface) and compares it to a numeric literal via BigInt. A non-numeric arg
@@ -392,6 +505,7 @@ function resolveLeaf(leaf, ctx) {
392
505
  case 'invocation_count_in_window':
393
506
  case 'now':
394
507
  case 'valid_until':
508
+ case 'call_arg_scaled':
395
509
  return undefined; // selector leaves with no ScVal projection
396
510
  case 'literal_address':
397
511
  return { type: 'address', value: leaf.value };
@@ -450,10 +564,23 @@ function evalOracleCompare(op, asset, right, ctx) {
450
564
  throw new OracleError('ORACLE_STALE');
451
565
  throw new OracleError(mapped);
452
566
  }
453
- const literal = right.kind === 'literal_i128' ? right.value : null;
454
- if (literal === null)
567
+ // Mirrors eval_oracle_compare in dsl.rs. The threshold MUST declare its
568
+ // decimal basis: prices are on the normalised 9-dp basis, and assuming a
569
+ // bare literal shares it is what let a raw 14-dp threshold permit
570
+ // everything. A bare literal is refused rather than assumed.
571
+ if (right.kind !== 'oracle_threshold')
455
572
  throw new OracleError('ORACLE_DECIMALS_MISMATCH');
456
- return bigintCmp(op, entry.price, literal)
573
+ if (right.decimals > MAX_ORACLE_THRESHOLD_DECIMALS) {
574
+ throw new OracleError('ORACLE_THRESHOLD_DECIMALS_OUT_OF_RANGE');
575
+ }
576
+ // Scale BOTH sides up to the wider basis rather than dividing the threshold
577
+ // down: dividing truncates, and a truncated bound moves the permit boundary.
578
+ const decimals = BigInt(right.decimals);
579
+ const normalised = BigInt(NORMALISED_DECIMALS);
580
+ const common = decimals > normalised ? decimals : normalised;
581
+ const priceScaled = BigInt(entry.price) * 10n ** (common - normalised);
582
+ const literalScaled = BigInt(right.value) * 10n ** (common - decimals);
583
+ return bigintCmp(op, String(priceScaled), String(literalScaled))
457
584
  ? { permit: true }
458
585
  : { permit: false, reason: 'FN_MISMATCH' };
459
586
  }
@@ -0,0 +1,15 @@
1
+ import type { PredicateNode, RecordedTransaction } from '../types.ts';
2
+ import type { EvalContext } from './evaluate.ts';
3
+ export interface PermitContextResponses {
4
+ windowSeconds: number;
5
+ invocationLimit?: number;
6
+ limitAmount?: string;
7
+ validUntilLedger: number;
8
+ oraclePriceBound?: Array<{
9
+ asset: string;
10
+ operator: string;
11
+ value: string;
12
+ decimals: number;
13
+ }>;
14
+ }
15
+ export declare function buildPermitContext(tx: RecordedTransaction, responses: PermitContextResponses, predicate: PredicateNode): EvalContext;