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