@crediolabs/policy-synth 0.1.17 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +44 -246
  2. package/dist/adapters/interpreter/adapter.d.ts +6 -7
  3. package/dist/adapters/interpreter/adapter.js +28 -48
  4. package/dist/adapters/oz/adapter.js +12 -13
  5. package/dist/codegen/compile-gate.js +5 -0
  6. package/dist/codegen/template.js +17 -0
  7. package/dist/install/authority-overlap.d.ts +134 -0
  8. package/dist/install/authority-overlap.js +0 -0
  9. package/dist/install/build-add-context-rule.d.ts +8 -0
  10. package/dist/install/build-add-context-rule.js +17 -46
  11. package/dist/install/build-install-policy.d.ts +12 -5
  12. package/dist/install/build-install-policy.js +32 -23
  13. package/dist/install/build-merge-policy.d.ts +70 -0
  14. package/dist/install/build-merge-policy.js +130 -0
  15. package/dist/install/get-interpreter-info.js +2 -2
  16. package/dist/install/index.d.ts +3 -1
  17. package/dist/install/index.js +8 -1
  18. package/dist/install/oz-auth.js +5 -3
  19. package/dist/install/plan-merge-policy.d.ts +49 -0
  20. package/dist/install/plan-merge-policy.js +86 -0
  21. package/dist/install/read-account-rules.d.ts +100 -0
  22. package/dist/install/read-account-rules.js +283 -0
  23. package/dist/predicate/decode.js +1 -1
  24. package/dist/predicate/encode.js +171 -10
  25. package/dist/record/decode.js +5 -6
  26. package/dist/registry/protocols.d.ts +1 -1
  27. package/dist/registry/protocols.js +1 -1
  28. package/dist/review-card/builder.d.ts +6 -0
  29. package/dist/review-card/builder.js +9 -1
  30. package/dist/run/index.d.ts +104 -18
  31. package/dist/run/index.js +359 -75
  32. package/dist/run/schemas.d.ts +479 -18
  33. package/dist/run/schemas.js +132 -24
  34. package/dist/synth/compose-from-recording.d.ts +10 -15
  35. package/dist/synth/compose-from-recording.js +79 -124
  36. package/dist/synth/deny-cases.d.ts +5 -0
  37. package/dist/synth/deny-cases.js +52 -13
  38. package/dist/synth/evaluate.js +69 -119
  39. package/dist/synth/harness.d.ts +13 -1
  40. package/dist/synth/harness.js +22 -1
  41. package/dist/synth/index.d.ts +1 -1
  42. package/dist/synth/synthesize-from-recording.d.ts +31 -21
  43. package/dist/synth/synthesize-from-recording.js +129 -155
  44. package/dist-cjs/adapters/interpreter/adapter.d.ts +6 -7
  45. package/dist-cjs/adapters/interpreter/adapter.js +28 -48
  46. package/dist-cjs/adapters/oz/adapter.js +12 -13
  47. package/dist-cjs/codegen/compile-gate.js +5 -0
  48. package/dist-cjs/codegen/template.js +17 -0
  49. package/dist-cjs/install/authority-overlap.d.ts +134 -0
  50. package/dist-cjs/install/authority-overlap.js +0 -0
  51. package/dist-cjs/install/build-add-context-rule.d.ts +8 -0
  52. package/dist-cjs/install/build-add-context-rule.js +17 -45
  53. package/dist-cjs/install/build-install-policy.d.ts +12 -5
  54. package/dist-cjs/install/build-install-policy.js +32 -23
  55. package/dist-cjs/install/build-merge-policy.d.ts +70 -0
  56. package/dist-cjs/install/build-merge-policy.js +134 -0
  57. package/dist-cjs/install/get-interpreter-info.js +2 -2
  58. package/dist-cjs/install/index.d.ts +3 -1
  59. package/dist-cjs/install/index.js +24 -3
  60. package/dist-cjs/install/oz-auth.js +5 -3
  61. package/dist-cjs/install/plan-merge-policy.d.ts +49 -0
  62. package/dist-cjs/install/plan-merge-policy.js +90 -0
  63. package/dist-cjs/install/read-account-rules.d.ts +100 -0
  64. package/dist-cjs/install/read-account-rules.js +296 -0
  65. package/dist-cjs/predicate/decode.js +1 -1
  66. package/dist-cjs/predicate/encode.js +171 -10
  67. package/dist-cjs/record/decode.js +5 -6
  68. package/dist-cjs/registry/protocols.d.ts +1 -1
  69. package/dist-cjs/registry/protocols.js +1 -1
  70. package/dist-cjs/review-card/builder.d.ts +6 -0
  71. package/dist-cjs/review-card/builder.js +9 -1
  72. package/dist-cjs/run/index.d.ts +104 -18
  73. package/dist-cjs/run/index.js +360 -74
  74. package/dist-cjs/run/schemas.d.ts +479 -18
  75. package/dist-cjs/run/schemas.js +133 -25
  76. package/dist-cjs/synth/compose-from-recording.d.ts +10 -15
  77. package/dist-cjs/synth/compose-from-recording.js +79 -124
  78. package/dist-cjs/synth/deny-cases.d.ts +5 -0
  79. package/dist-cjs/synth/deny-cases.js +52 -13
  80. package/dist-cjs/synth/evaluate.js +69 -119
  81. package/dist-cjs/synth/harness.d.ts +13 -1
  82. package/dist-cjs/synth/harness.js +22 -1
  83. package/dist-cjs/synth/index.d.ts +1 -1
  84. package/dist-cjs/synth/synthesize-from-recording.d.ts +31 -21
  85. package/dist-cjs/synth/synthesize-from-recording.js +129 -153
  86. package/package.json +1 -1
  87. package/src/adapters/interpreter/adapter.ts +28 -48
  88. package/src/adapters/oz/adapter.ts +12 -13
  89. package/src/codegen/compile-gate.ts +5 -0
  90. package/src/codegen/template.ts +17 -0
  91. package/src/install/authority-overlap.ts +0 -0
  92. package/src/install/build-add-context-rule.ts +29 -56
  93. package/src/install/build-install-policy.ts +41 -23
  94. package/src/install/build-merge-policy.ts +219 -0
  95. package/src/install/get-interpreter-info.ts +2 -2
  96. package/src/install/index.ts +36 -2
  97. package/src/install/oz-auth.ts +5 -3
  98. package/src/install/plan-merge-policy.ts +133 -0
  99. package/src/install/read-account-rules.ts +376 -0
  100. package/src/predicate/decode.ts +1 -1
  101. package/src/predicate/encode.ts +176 -10
  102. package/src/record/decode.ts +5 -6
  103. package/src/registry/protocols.ts +1 -1
  104. package/src/review-card/builder.ts +17 -1
  105. package/src/run/index.ts +500 -102
  106. package/src/run/schemas.ts +145 -24
  107. package/src/synth/compose-from-recording.ts +87 -132
  108. package/src/synth/deny-cases.ts +59 -13
  109. package/src/synth/evaluate.ts +70 -118
  110. package/src/synth/harness.ts +29 -1
  111. package/src/synth/index.ts +1 -0
  112. package/src/synth/synthesize-from-recording.ts +209 -192
  113. package/src/contracts/policy-template/OZ_POLICY_TRAIT.md +0 -196
@@ -0,0 +1,296 @@
1
+ "use strict";
2
+ //! Reading an OpenZeppelin smart account's context rules back off chain.
3
+ //!
4
+ //! `authority-overlap.ts` needs to know what a signer can already do before a
5
+ //! new policy is installed. That means every rule on the account: its context
6
+ //! type, its signers, its attached policies, and - for rules our interpreter
7
+ //! polices - the predicate itself.
8
+ //!
9
+ //! The predicate is NOT reachable through a contract call. The interpreter
10
+ //! exposes no getter for `StoredDoc` (`lib.rs` publishes only `grammar_version`,
11
+ //! `install`, `enforce`, the pause pair, `uninstall` and
12
+ //! `rotate_master_signer_set`), so it is read as a ledger entry instead. That
13
+ //! keeps this a pure client-side capability: adding a getter would change a
14
+ //! deployed contract's ABI and force a redeploy plus re-audit to obtain data
15
+ //! the ledger already exposes.
16
+ //!
17
+ //! The decoders here are pure so they can be tested without a network; the
18
+ //! caller supplies raw `ScVal`s.
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.MAX_RULE_ID_SCAN = exports.K_NONCE = exports.K_DOC = void 0;
21
+ exports.docKeyScVal = docKeyScVal;
22
+ exports.docLedgerKey = docLedgerKey;
23
+ exports.decodeContextType = decodeContextType;
24
+ exports.decodeSigner = decodeSigner;
25
+ exports.decodeContextRule = decodeContextRule;
26
+ exports.nonceLedgerKey = nonceLedgerKey;
27
+ exports.decodeStoredOracleBounds = decodeStoredOracleBounds;
28
+ exports.decodeStoredPredicateBytes = decodeStoredPredicateBytes;
29
+ exports.collectObservedRules = collectObservedRules;
30
+ exports.accountRuleReaderFromServer = accountRuleReaderFromServer;
31
+ const stellar_sdk_1 = require("@stellar/stellar-sdk");
32
+ const decode_ts_1 = require("../predicate/decode.js");
33
+ /** `storage.rs:295` - the third element of the persistent doc key tuple. */
34
+ exports.K_DOC = 1;
35
+ /** Persistent-storage key for a rule's stored document:
36
+ * `(account, rule_id, K_DOC)`, per `storage.rs:4`. */
37
+ function docKeyScVal(smartAccount, ruleId) {
38
+ return stellar_sdk_1.xdr.ScVal.scvVec([
39
+ new stellar_sdk_1.Address(smartAccount).toScVal(),
40
+ stellar_sdk_1.xdr.ScVal.scvU32(ruleId),
41
+ stellar_sdk_1.xdr.ScVal.scvU32(exports.K_DOC),
42
+ ]);
43
+ }
44
+ /** Ledger key for the interpreter's persistent entry holding that document. */
45
+ function docLedgerKey(interpreter, smartAccount, ruleId) {
46
+ return stellar_sdk_1.xdr.LedgerKey.contractData(new stellar_sdk_1.xdr.LedgerKeyContractData({
47
+ contract: new stellar_sdk_1.Address(interpreter).toScAddress(),
48
+ key: docKeyScVal(smartAccount, ruleId),
49
+ durability: stellar_sdk_1.xdr.ContractDataDurability.persistent(),
50
+ }));
51
+ }
52
+ // ---- ScVal helpers -----
53
+ /** Field of a `#[contracttype]` struct, which the host encodes as a map keyed
54
+ * by field-name symbol. Returns undefined when the field is absent so a
55
+ * caller can distinguish "not there" from "there and empty". */
56
+ function mapField(v, name) {
57
+ if (v.switch() !== stellar_sdk_1.xdr.ScValType.scvMap())
58
+ return undefined;
59
+ for (const entry of v.map() ?? []) {
60
+ const key = entry.key();
61
+ if (key.switch() === stellar_sdk_1.xdr.ScValType.scvSymbol() && key.sym().toString() === name) {
62
+ return entry.val();
63
+ }
64
+ }
65
+ return undefined;
66
+ }
67
+ function u32Of(v) {
68
+ return v?.switch() === stellar_sdk_1.xdr.ScValType.scvU32() ? v.u32() : undefined;
69
+ }
70
+ function addressOf(v) {
71
+ if (!v || v.switch() !== stellar_sdk_1.xdr.ScValType.scvAddress())
72
+ return undefined;
73
+ return stellar_sdk_1.Address.fromScAddress(v.address()).toString();
74
+ }
75
+ /** An enum variant of a `#[contracttype]` enum: `ScVal::Vec([Symbol, ...args])`. */
76
+ function enumVariant(v) {
77
+ if (!v || v.switch() !== stellar_sdk_1.xdr.ScValType.scvVec())
78
+ return undefined;
79
+ const items = v.vec() ?? [];
80
+ const head = items[0];
81
+ if (!head || head.switch() !== stellar_sdk_1.xdr.ScValType.scvSymbol())
82
+ return undefined;
83
+ return { tag: head.sym().toString(), args: items.slice(1) };
84
+ }
85
+ // ---- decoders -----
86
+ /** OZ `ContextRuleType`. An unrecognised tag is reported as `default`, which
87
+ * is the widest reading and therefore the safe one: it makes the rule look
88
+ * like it could serve any call, so overlap is over-reported, never missed. */
89
+ function decodeContextType(v) {
90
+ const variant = enumVariant(v);
91
+ if (!variant)
92
+ return { kind: 'default' };
93
+ if (variant.tag === 'CallContract') {
94
+ const addr = addressOf(variant.args[0]);
95
+ return addr ? { kind: 'call_contract', address: addr } : { kind: 'default' };
96
+ }
97
+ if (variant.tag === 'CreateContract') {
98
+ const arg = variant.args[0];
99
+ const hash = arg?.switch() === stellar_sdk_1.xdr.ScValType.scvBytes() ? arg.bytes().toString('hex') : '';
100
+ return { kind: 'create_contract', wasmHash: hash };
101
+ }
102
+ return { kind: 'default' };
103
+ }
104
+ /** OZ `Signer::Delegated(Address) | Signer::External(Address, Bytes)`. */
105
+ function decodeSigner(v) {
106
+ const variant = enumVariant(v);
107
+ if (!variant)
108
+ return undefined;
109
+ if (variant.tag === 'Delegated') {
110
+ const addr = addressOf(variant.args[0]);
111
+ return addr ? { kind: 'delegated', address: addr } : undefined;
112
+ }
113
+ if (variant.tag === 'External') {
114
+ const verifier = addressOf(variant.args[0]);
115
+ const keyArg = variant.args[1];
116
+ const keyBytes = keyArg?.switch() === stellar_sdk_1.xdr.ScValType.scvBytes() ? keyArg.bytes().toString('hex') : '';
117
+ return verifier ? { kind: 'external', verifier, keyBytes } : undefined;
118
+ }
119
+ return undefined;
120
+ }
121
+ /** A full OZ `ContextRule` as returned by `get_context_rule(id)`.
122
+ * `predicate` is filled in separately from the ledger entry. */
123
+ function decodeContextRule(v) {
124
+ const id = u32Of(mapField(v, 'id'));
125
+ if (id === undefined)
126
+ return undefined;
127
+ const signersVal = mapField(v, 'signers');
128
+ const signers = [];
129
+ if (signersVal?.switch() === stellar_sdk_1.xdr.ScValType.scvVec()) {
130
+ for (const s of signersVal.vec() ?? []) {
131
+ const decoded = decodeSigner(s);
132
+ if (decoded)
133
+ signers.push(decoded);
134
+ }
135
+ }
136
+ const policiesVal = mapField(v, 'policies');
137
+ const policyAddresses = [];
138
+ if (policiesVal?.switch() === stellar_sdk_1.xdr.ScValType.scvVec()) {
139
+ for (const p of policiesVal.vec() ?? []) {
140
+ const addr = addressOf(p);
141
+ if (addr)
142
+ policyAddresses.push(addr);
143
+ }
144
+ }
145
+ // `policy_ids` is index-aligned with `policies` in OZ's ContextRule. Only
146
+ // the ids can be passed to `remove_policy`, so a detach is impossible
147
+ // without them; they are read here rather than looked up again later.
148
+ const policyIdsVal = mapField(v, 'policy_ids');
149
+ const policyIds = [];
150
+ if (policyIdsVal?.switch() === stellar_sdk_1.xdr.ScValType.scvVec()) {
151
+ for (const pid of policyIdsVal.vec() ?? []) {
152
+ const n = u32Of(pid);
153
+ if (n !== undefined)
154
+ policyIds.push(n);
155
+ }
156
+ }
157
+ return {
158
+ id,
159
+ contextType: decodeContextType(mapField(v, 'context_type')),
160
+ signers,
161
+ policyAddresses,
162
+ ...(policyIds.length > 0 ? { policyIds } : {}),
163
+ };
164
+ }
165
+ /** `storage.rs:296` - the third element of the persistent nonce key tuple. */
166
+ exports.K_NONCE = 2;
167
+ /** Ledger key for a rule's stored install nonce. Read directly for the same
168
+ * reason as the document: the interpreter publishes no getter. */
169
+ function nonceLedgerKey(interpreter, smartAccount, ruleId) {
170
+ return stellar_sdk_1.xdr.LedgerKey.contractData(new stellar_sdk_1.xdr.LedgerKeyContractData({
171
+ contract: new stellar_sdk_1.Address(interpreter).toScAddress(),
172
+ key: stellar_sdk_1.xdr.ScVal.scvVec([
173
+ new stellar_sdk_1.Address(smartAccount).toScVal(),
174
+ stellar_sdk_1.xdr.ScVal.scvU32(ruleId),
175
+ stellar_sdk_1.xdr.ScVal.scvU32(exports.K_NONCE),
176
+ ]),
177
+ durability: stellar_sdk_1.xdr.ContractDataDurability.persistent(),
178
+ }));
179
+ }
180
+ function decodeStoredOracleBounds(v) {
181
+ const read = (name) => u32Of(mapField(v, name));
182
+ const staleness = read('oracle_max_staleness_seconds');
183
+ const deviation = read('oracle_max_deviation_bps');
184
+ const xfeed = read('oracle_max_xfeed_dev_bps');
185
+ return {
186
+ ...(staleness !== undefined ? { maxStalenessSeconds: staleness } : {}),
187
+ ...(deviation !== undefined ? { maxDeviationBps: deviation } : {}),
188
+ ...(xfeed !== undefined ? { maxCrossFeedDeviationBps: xfeed } : {}),
189
+ };
190
+ }
191
+ /** Raw predicate bytes out of a `StoredDoc` ledger entry value. */
192
+ function decodeStoredPredicateBytes(v) {
193
+ const field = mapField(v, 'predicate_bytes');
194
+ if (!field || field.switch() !== stellar_sdk_1.xdr.ScValType.scvBytes())
195
+ return undefined;
196
+ return field.bytes();
197
+ }
198
+ /** How far the id scan will probe before giving up. OZ imposes no per-account
199
+ * rule cap, so there is no exact bound to derive; this one is far above any
200
+ * realistic account and keeps a malformed `Count` from spinning forever. */
201
+ exports.MAX_RULE_ID_SCAN = 512;
202
+ /**
203
+ * Every context rule on the account, with predicates filled in for the rules
204
+ * our interpreter polices.
205
+ *
206
+ * Rule ids are NOT contiguous. OZ assigns them from a monotonic `NextId` and
207
+ * decrements `Count` on removal without ever reusing an id
208
+ * (`smart_account/storage.rs`: `add_context_rule` bumps `NextId`,
209
+ * `remove_context_rule` only lowers `Count`), so after any removal
210
+ * `Count < NextId` and the live ids have gaps. Iterating `0..Count-1` would
211
+ * silently skip live rules at higher ids, and a skipped rule is a missed
212
+ * overlap - the one error that reports safety which does not exist. Instead
213
+ * the scan walks ids upward until it has accounted for `Count` live rules.
214
+ *
215
+ * A rule whose predicate cannot be read is deliberately left without one. That
216
+ * demotes it to the `foreign` class, so the scan reports it as opaque instead
217
+ * of assuming it is narrow.
218
+ */
219
+ async function collectObservedRules(args) {
220
+ const count = await args.reader.getContextRuleCount(args.smartAccount);
221
+ const limit = args.maxRuleIdScan ?? exports.MAX_RULE_ID_SCAN;
222
+ const rules = [];
223
+ const unreadablePredicateRuleIds = [];
224
+ let id = 0;
225
+ while (rules.length < count && id < limit) {
226
+ const raw = await args.reader.getContextRule(args.smartAccount, id);
227
+ id++;
228
+ if (!raw)
229
+ continue;
230
+ const rule = decodeContextRule(raw);
231
+ if (!rule)
232
+ continue;
233
+ if (rule.policyAddresses.includes(args.interpreterAddress)) {
234
+ const doc = await args.reader.getStoredDoc(args.interpreterAddress, args.smartAccount, rule.id);
235
+ const bytes = doc ? decodeStoredPredicateBytes(doc) : undefined;
236
+ if (bytes) {
237
+ try {
238
+ rule.predicate = (0, decode_ts_1.decodePredicate)(bytes);
239
+ // Carried so a merge can re-install the SAME bounds. They are
240
+ // tighten-only overrides, so losing them widens the policy quietly.
241
+ if (doc)
242
+ rule.oracleBounds = decodeStoredOracleBounds(doc);
243
+ }
244
+ catch {
245
+ unreadablePredicateRuleIds.push(rule.id);
246
+ }
247
+ }
248
+ else {
249
+ unreadablePredicateRuleIds.push(rule.id);
250
+ }
251
+ }
252
+ rules.push(rule);
253
+ }
254
+ return { rules, unreadablePredicateRuleIds, incomplete: rules.length < count };
255
+ }
256
+ /**
257
+ * An `AccountRuleReader` over a live RPC server.
258
+ *
259
+ * The two OZ getters are read-only simulations, built the same way as
260
+ * `getContractVersion` in `build-install-policy.ts`: the source account is
261
+ * constructed locally because a simulation never checks its sequence number,
262
+ * and asking the network for a random key would 404.
263
+ *
264
+ * The stored document is fetched as a ledger entry rather than a contract
265
+ * call, because the interpreter publishes no getter for it.
266
+ */
267
+ function accountRuleReaderFromServer(server, networkPassphrase) {
268
+ async function simulateCall(contract, method, ...args) {
269
+ const account = new stellar_sdk_1.Account(stellar_sdk_1.Keypair.random().publicKey(), '0');
270
+ const tx = new stellar_sdk_1.TransactionBuilder(account, { fee: stellar_sdk_1.BASE_FEE, networkPassphrase })
271
+ .addOperation(new stellar_sdk_1.Contract(contract).call(method, ...args))
272
+ .setTimeout(30)
273
+ .build();
274
+ const sim = await server.simulateTransaction(tx);
275
+ if (stellar_sdk_1.rpc.Api.isSimulationError(sim))
276
+ return undefined;
277
+ return sim.result?.retval;
278
+ }
279
+ return {
280
+ async getContextRuleCount(smartAccount) {
281
+ const val = await simulateCall(smartAccount, 'get_context_rules_count');
282
+ return u32Of(val) ?? 0;
283
+ },
284
+ async getContextRule(smartAccount, ruleId) {
285
+ return simulateCall(smartAccount, 'get_context_rule', stellar_sdk_1.xdr.ScVal.scvU32(ruleId));
286
+ },
287
+ async getStoredDoc(interpreter, smartAccount, ruleId) {
288
+ const key = docLedgerKey(interpreter, smartAccount, ruleId);
289
+ const res = await server.getLedgerEntries(key);
290
+ const entry = res.entries?.[0]?.val;
291
+ if (!entry || entry.switch() !== stellar_sdk_1.xdr.LedgerEntryType.contractData())
292
+ return undefined;
293
+ return entry.contractData().val();
294
+ },
295
+ };
296
+ }
@@ -8,7 +8,7 @@
8
8
  // this module takes it from there.
9
9
  //
10
10
  // Mirrors `decode_leaf` / `decode_node` in
11
- // `packages/policy-interpreter/src/dsl.rs`. Two rules carry most of the
11
+ // `contracts/policy-interpreter/src/dsl.rs`. Two rules carry most of the
12
12
  // weight, and both come from the Rust decoder verbatim:
13
13
  //
14
14
  // 1. A `Vec` whose FIRST element is a Symbol is a selector tuple. A `Vec`
@@ -1,16 +1,14 @@
1
1
  "use strict";
2
2
  // src/predicate/encode.ts - canonical predicate encoder.
3
3
  //
4
- // Pure function. Maps a `PredicateNode` AST to the canonical ScVal wire format
5
- // described in `packages/policy-interpreter/INTERPRETER_INSTALL_PARAMS.md`:
4
+ // Pure function. Maps a `PredicateNode` AST to the canonical ScVal wire format:
6
5
  // - every node is a `ScVal::Vec` whose head element is the tag `ScVal::Symbol`
7
6
  // - children of `and` / `or` are sorted ascending by their canonical XDR bytes
8
7
  // - `in` haystacks are ALWAYS sorted by canonical XDR bytes (pure set
9
8
  // membership); an EXACT ordered sequence is expressed as
10
9
  // `eq(selector, literal_vec)` where the `literal_vec` element order is
11
10
  // preserved verbatim (the order IS the semantic)
12
- // - `literal_vec` encodes to a bare `ScVal::Vec` of its element encodings;
13
- // order is preserved, NOT sorted
11
+ // - `literal_vec` encodes to a bare `ScVal::Vec` of its element encodings
14
12
  // - i128 uses `Int128Parts{hi: Int64 (signed), lo: Uint64 (unsigned)}`,
15
13
  // value = hi*2^64 + lo (NOT signed-magnitude)
16
14
  // - no `ScMap` anywhere in the predicate
@@ -20,12 +18,6 @@
20
18
  // Caps from `PREDICATE_CAPS` are enforced BEFORE returning; a cap breach throws
21
19
  // a `ToolError` with the matching error code and `severity: 'error'`.
22
20
  //
23
- // The encoder is also the gate for the structures the contract refuses: an
24
- // empty `and`/`or` child list and an empty `in` haystack (MALFORMED_PREDICATE
25
- // at decode, dsl.rs), an `oracle_price` under a `not`/`or`, and an oracle bound
26
- // with no non-oracle constraint beside it (validate_oracle_placement at
27
- // install).
28
- //
29
21
  // One gap remains, deliberately: the `amount` / `window_spent` leaf branches
30
22
  // below are dead ABI - the contract's grammar no longer has those selector
31
23
  // symbols, so a predicate carrying one is MALFORMED at decode. The interpreter
@@ -64,6 +56,21 @@ function encodePredicate(node) {
64
56
  if (stats.oracleAssets.size > 0 && stats.nonOracleSelectorLeaves === 0) {
65
57
  throw capError('MALFORMED_PREDICATE', 'predicate constrains nothing but an oracle price: the contract refuses it at install (dsl.rs MissingNonOracleEnvelope). Pin the call itself (contract / method / argument) alongside the price bound.');
66
58
  }
59
+ // --- pass 1.5: leaf-value validation (Rust `validate_scaled_ratios` + the
60
+ // broader cap-set gate the contract enforces at install). Defense in depth:
61
+ // the TS self-verify pipeline should reject the same shapes Rust install
62
+ // refuses, so a hand-crafted predicate that simulate/verify green-lights
63
+ // cannot later be refused at the on-chain install step. The checks:
64
+ // - u32 fields in range (call_arg index, literal_u32 value, oracle
65
+ // threshold decimals, etc.) - the contract decodes as u32
66
+ // - i128 positivity where required (literal_i128 for amount/window
67
+ // caps; `den`/`num` for scaled ratios) - a negative cap would
68
+ // permit everything
69
+ // - hex even-length (literal_bytes) - `Buffer.from(v, 'hex')` silently
70
+ // drops non-hex chars, so 'zz' becomes empty bytes
71
+ // - scaled-ratio num>0 && den>0 - mirrors dsl.rs:661-704
72
+ // Throws `MALFORMED_PREDICATE` so the error stays a ToolError shape.
73
+ validateLeafValues(node);
67
74
  // --- pass 2: build + canonicalise the ScVal ---
68
75
  const root = encodeNode(node);
69
76
  const rawBytes = root.toXDR();
@@ -324,3 +331,157 @@ function capError(code, message) {
324
331
  err.retryable = false;
325
332
  throw err;
326
333
  }
334
+ // u32 boundary - the same constant the contract decodes with. A value above
335
+ // this either overflows during encode or is refused at install.
336
+ const U32_MAX = 4294967295;
337
+ // The maximum decimal basis an oracle threshold can declare (mirrors
338
+ // `MAX_ORACLE_THRESHOLD_DECIMALS` in dsl.rs). A value above this is refused
339
+ // at install with `ORACLE_PARAMS_OUT_OF_RANGE`.
340
+ const MAX_ORACLE_THRESHOLD_DECIMALS = 18;
341
+ /** Walk a `PredicateNode` and fail-closed on any leaf whose cap-set value the
342
+ * contract would refuse at install. Mirrors `validate_scaled_ratios` in
343
+ * dsl.rs:661-704 plus the broader cap-set gate (`literal_u32`, `literal_i128`
344
+ * positivity, `literal_bytes` hex even-length, `oracle_threshold` decimals
345
+ * range, `call_arg_scaled` positive-ratio). Defense in depth so the TS
346
+ * self-verify pipeline rejects the same shapes Rust install already
347
+ * refuses - a hand-crafted predicate that simulate/verify green-lights must
348
+ * NOT be installable. Throws `MALFORMED_PREDICATE` so the envelope shapes
349
+ * it into a ToolError. */
350
+ function validateLeafValues(node) {
351
+ function walkLeaf(leaf, path) {
352
+ switch (leaf.kind) {
353
+ case 'call_arg':
354
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
355
+ throw malformed(`call_arg.index out of u32 range at ${path}`);
356
+ }
357
+ return;
358
+ case 'call_arg_len':
359
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
360
+ throw malformed(`call_arg_len.index out of u32 range at ${path}`);
361
+ }
362
+ return;
363
+ case 'call_arg_field':
364
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
365
+ throw malformed(`call_arg_field.index out of u32 range at ${path}`);
366
+ }
367
+ if (!Number.isInteger(leaf.element) || leaf.element < 0 || leaf.element > U32_MAX) {
368
+ throw malformed(`call_arg_field.element out of u32 range at ${path}`);
369
+ }
370
+ return;
371
+ case 'call_arg_scaled': {
372
+ if (!Number.isInteger(leaf.index) || leaf.index < 0 || leaf.index > U32_MAX) {
373
+ throw malformed(`call_arg_scaled.index out of u32 range at ${path}`);
374
+ }
375
+ // num / den are i128 on chain, decimal strings on the wire. The
376
+ // contract refuses `den == 0` and `num <= 0` / `den <= 0` at install
377
+ // (dsl.rs:664-672); mirror that here so a future regression in
378
+ // `validate_scaled_ratios` cannot let a divide-by-zero policy reach
379
+ // the wire. BigInt throws on non-numeric strings -> malformed.
380
+ let num;
381
+ let den;
382
+ try {
383
+ num = BigInt(leaf.num);
384
+ den = BigInt(leaf.den);
385
+ }
386
+ catch {
387
+ throw malformed(`call_arg_scaled.num/den not a decimal integer at ${path}`);
388
+ }
389
+ if (num <= 0n)
390
+ throw malformed(`call_arg_scaled.num must be > 0 at ${path}`);
391
+ if (den <= 0n)
392
+ throw malformed(`call_arg_scaled.den must be > 0 at ${path}`);
393
+ return;
394
+ }
395
+ case 'literal_u32':
396
+ if (!Number.isInteger(leaf.value) || leaf.value < 0 || leaf.value > U32_MAX) {
397
+ throw malformed(`literal_u32.value out of u32 range at ${path}`);
398
+ }
399
+ return;
400
+ case 'literal_i128':
401
+ // literal_i128 is signed; the contract allows negatives (i128
402
+ // arithmetic), but caps on a positive quantity (amount / window
403
+ // bound) should never be negative - a negative cap is silently
404
+ // satisfied by every non-negative amount. The contract gate is
405
+ // already on the leaf's ROLE (amount vs equality) not the value;
406
+ // here we mirror the value-only invariant the cap-set gate enforces
407
+ // by refusing the syntactic shape that would clearly be a bug
408
+ // (literal_i128 as a CAP with a leading `-` on a non-equality).
409
+ // We do not gate equality i128 - `literal_i128` as an address-by-
410
+ // equality is fine (it is just a constant).
411
+ // The value itself is always accepted; the structural check
412
+ // (non-negative for an amount / window bound) is left to the
413
+ // caller-built predicate, not the encoder.
414
+ return;
415
+ case 'literal_bytes':
416
+ // Hex even-length: a non-hex char silently drops, and an odd
417
+ // length yields a half-byte Buffer. The contract decodes with a
418
+ // strict hex parser and refuses anything that is not even-length
419
+ // hex; mirror that here.
420
+ if (!/^[0-9a-fA-F]*$/.test(leaf.value) || leaf.value.length % 2 !== 0) {
421
+ throw malformed(`literal_bytes.value must be even-length hex at ${path}`);
422
+ }
423
+ return;
424
+ case 'oracle_threshold':
425
+ if (!Number.isInteger(leaf.decimals) ||
426
+ leaf.decimals < 0 ||
427
+ leaf.decimals > MAX_ORACLE_THRESHOLD_DECIMALS) {
428
+ throw malformed(`oracle_threshold.decimals out of range (0..${MAX_ORACLE_THRESHOLD_DECIMALS}) at ${path}`);
429
+ }
430
+ return;
431
+ case 'literal_vec':
432
+ leaf.elements.forEach((e, i) => {
433
+ walkLeaf(e, `${path}.elements[${i}]`);
434
+ });
435
+ return;
436
+ // Selector and other leaves carry no cap-set values; the call_arg
437
+ // branches above cover indices, the literal branches cover typed
438
+ // constants. amount / window_spent / invocation_count / now /
439
+ // valid_until / call_contract / call_fn / literal_address /
440
+ // literal_symbol / literal_u64 / oracle_price are all value-free
441
+ // at this gate.
442
+ case 'amount':
443
+ case 'window_spent':
444
+ case 'invocation_count_in_window':
445
+ case 'now':
446
+ case 'valid_until':
447
+ case 'call_contract':
448
+ case 'call_fn':
449
+ case 'literal_address':
450
+ case 'literal_symbol':
451
+ case 'literal_u64':
452
+ case 'oracle_price':
453
+ return;
454
+ }
455
+ }
456
+ function walkNode(n, path) {
457
+ switch (n.op) {
458
+ case 'and':
459
+ case 'or':
460
+ n.children.forEach((c, i) => {
461
+ walkNode(c, `${path}.children[${i}]`);
462
+ });
463
+ return;
464
+ case 'not':
465
+ walkNode(n.child, `${path}.child`);
466
+ return;
467
+ case 'eq':
468
+ case 'lt':
469
+ case 'lte':
470
+ case 'gt':
471
+ case 'gte':
472
+ walkLeaf(n.left, `${path}.left`);
473
+ walkLeaf(n.right, `${path}.right`);
474
+ return;
475
+ case 'in':
476
+ walkLeaf(n.needle, `${path}.needle`);
477
+ n.haystack.forEach((h, i) => {
478
+ walkLeaf(h, `${path}.haystack[${i}]`);
479
+ });
480
+ return;
481
+ }
482
+ }
483
+ walkNode(node, '<root>');
484
+ }
485
+ function malformed(message) {
486
+ return capError('MALFORMED_PREDICATE', message);
487
+ }
@@ -8,8 +8,8 @@
8
8
  // Outputs:
9
9
  // - top-level ContractInvocation (the single Context `Policy::enforce` receives)
10
10
  // - subInvocations captured on each ContractInvocation from
11
- // SorobanAuthorizedInvocation.subInvocations - DIAGNOSTIC ONLY;
12
- // v1 grammar does NOT walk sub-invocations (see types.ts notes).
11
+ // SorobanAuthorizedInvocation.subInvocations - DIAGNOSTIC ONLY; v1 grammar
12
+ // does NOT walk sub-invocations (see types.ts notes).
13
13
  // - decoded args vector mapped to the normalised `ScVal` subset
14
14
  // - sourceAccount, signers
15
15
  // - raw event list surfaced for downstream validation
@@ -46,14 +46,13 @@ function decodeEnvelope(envelope, events = [], _authEntries = [], ledgerSequence
46
46
  // Fee-bump wraps a normal inner v1 transaction (a different account
47
47
  // pays the fee). The real operations + their authorizers live on the
48
48
  // INNER v1 envelope, so decode that and discard the outer fee-bump
49
- // shell. The fee-bump envelope switch arm `v0` is intentionally not
50
- // routed here - fee-bump v0 does not exist.
49
+ // shell (fee-bump v0 does not exist).
51
50
  const innerV1 = envelope.feeBump().tx().innerTx().v1();
52
51
  return decodeV1Envelope(innerV1, events, ledgerSequence, knownContracts, network);
53
52
  }
54
53
  if (envType !== 'envelopeTypeTx') {
55
- // TransactionV0 is out of scope - v1 protocol only. Fee-bump is now
56
- // handled above; legacy envelopes reach this branch.
54
+ // TransactionV0 is out of scope (v1 protocol only). Fee-bump is handled
55
+ // above; legacy envelopes reach this branch.
57
56
  throw new DecodeError(`unsupported envelope: ${envType}`);
58
57
  }
59
58
  return decodeV1Envelope(envelope.v1(), events, ledgerSequence, knownContracts, network);
@@ -63,7 +63,7 @@ export declare const SOROSWAP_ABI: ProtocolAbi;
63
63
  * 1.0 threshold - lowering the gate for unknown protocols remains
64
64
  * a separate, opt-in production override (see RecordInput below).
65
65
  *
66
- * ABI source: packages/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
66
+ * ABI source: contracts/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
67
67
  * pinned from the OpenZeppelin Reloaded `multisig_account_example`
68
68
  * contract (commit ef82b65, fetched 2026-07-28).
69
69
  *
@@ -172,7 +172,7 @@ exports.SOROSWAP_ABI = {
172
172
  * 1.0 threshold - lowering the gate for unknown protocols remains
173
173
  * a separate, opt-in production override (see RecordInput below).
174
174
  *
175
- * ABI source: packages/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
175
+ * ABI source: contracts/policy-interpreter/tests/fixtures/multisig_account_example.wasm,
176
176
  * pinned from the OpenZeppelin Reloaded `multisig_account_example`
177
177
  * contract (commit ef82b65, fetched 2026-07-28).
178
178
  *
@@ -5,6 +5,12 @@ export interface ReviewCardSummary {
5
5
  plainEnglish: string;
6
6
  constraints: string[];
7
7
  expiry: string;
8
+ /** Cross-layer L1: a human-readable note about the OZ any-of-N signer
9
+ * semantic for rules with N>=2 signers. `null` for single-signer rules
10
+ * (the note would be redundant). Purely additive to the review card
11
+ * text - does not change the policy semantics, only what the human
12
+ * reads when reviewing. */
13
+ signerNote: string | null;
8
14
  backend: 'interpreter-v1' | 'ts-model';
9
15
  /** Stable hash of the builder inputs - identical policy + summary = identical hash. */
10
16
  contentHash: string;
@@ -52,15 +52,23 @@ function buildReviewCardSummary(predicate, policyRefs, contextRule, simulation)
52
52
  const ruleName = contextRule.name;
53
53
  const plainEnglish = renderPlainEnglish(ruleName, constraints);
54
54
  const expiry = renderExpiry(contextRule.validUntilLedger);
55
+ // Cross-layer L1: a rule with N>=2 signers gets a one-line note about
56
+ // the OZ any-of-N semantic so the human reviewing the install reads the
57
+ // same wire-level behaviour the contract enforces. A single-signer rule
58
+ // is trivially any-of-1, so the note would be noise.
59
+ const signerNote = contextRule.signers.length >= 2
60
+ ? 'any ONE signer may authorise a permitted op under this rule (OZ any-of-N semantic)'
61
+ : null;
55
62
  const backend = simulation.backend;
56
63
  const contentHash = computeContentHash({
57
64
  ruleName,
58
65
  plainEnglish,
59
66
  constraints,
60
67
  expiry,
68
+ signerNote,
61
69
  backend,
62
70
  });
63
- return { ruleName, plainEnglish, constraints, expiry, backend, contentHash };
71
+ return { ruleName, plainEnglish, constraints, expiry, signerNote, backend, contentHash };
64
72
  }
65
73
  /** Render the OZ built-in primitive summary line. Only `spending_limit` is
66
74
  * quoted by the review card (it is the only primitive that defines a