@crediolabs/policy-synth 0.1.9 → 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 (96) 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 +61 -5
  18. package/dist/review-card/cross-check.js +50 -3
  19. package/dist/review-card/index.d.ts +1 -1
  20. package/dist/review-card/index.js +1 -1
  21. package/dist/run/index.d.ts +8 -2
  22. package/dist/run/index.js +2 -1
  23. package/dist/run/schemas.d.ts +16 -4
  24. package/dist/run/schemas.js +14 -0
  25. package/dist/synth/compose-from-recording.d.ts +4 -0
  26. package/dist/synth/compose-from-recording.js +34 -8
  27. package/dist/synth/deny-cases.d.ts +4 -1
  28. package/dist/synth/deny-cases.js +3 -1
  29. package/dist/synth/evaluate.js +130 -3
  30. package/dist/synth/permit-context.d.ts +15 -0
  31. package/dist/synth/permit-context.js +116 -0
  32. package/dist/synth/synthesize-from-mandate.d.ts +17 -2
  33. package/dist/synth/synthesize-from-mandate.js +27 -2
  34. package/dist/synth/synthesize-from-recording.d.ts +25 -1
  35. package/dist/synth/synthesize-from-recording.js +80 -3
  36. package/dist/types.d.ts +9 -0
  37. package/dist-cjs/adapters/interpreter/adapter.js +62 -11
  38. package/dist-cjs/errors.d.ts +1 -1
  39. package/dist-cjs/install/build-add-context-rule.d.ts +48 -0
  40. package/dist-cjs/install/build-add-context-rule.js +308 -0
  41. package/dist-cjs/ir/types.d.ts +4 -0
  42. package/dist-cjs/predicate/decode.d.ts +11 -0
  43. package/dist-cjs/predicate/decode.js +239 -0
  44. package/dist-cjs/predicate/encode.js +79 -14
  45. package/dist-cjs/predicate/from-json.d.ts +4 -0
  46. package/dist-cjs/predicate/from-json.js +116 -0
  47. package/dist-cjs/predicate/index.d.ts +2 -0
  48. package/dist-cjs/predicate/index.js +10 -2
  49. package/dist-cjs/registry/identify.js +20 -1
  50. package/dist-cjs/registry/protocols.d.ts +50 -1
  51. package/dist-cjs/registry/protocols.js +89 -1
  52. package/dist-cjs/review-card/builder.d.ts +13 -0
  53. package/dist-cjs/review-card/builder.js +62 -5
  54. package/dist-cjs/review-card/cross-check.js +50 -3
  55. package/dist-cjs/review-card/index.d.ts +1 -1
  56. package/dist-cjs/review-card/index.js +2 -1
  57. package/dist-cjs/run/index.d.ts +8 -2
  58. package/dist-cjs/run/index.js +2 -1
  59. package/dist-cjs/run/schemas.d.ts +16 -4
  60. package/dist-cjs/run/schemas.js +14 -0
  61. package/dist-cjs/synth/compose-from-recording.d.ts +4 -0
  62. package/dist-cjs/synth/compose-from-recording.js +34 -8
  63. package/dist-cjs/synth/deny-cases.d.ts +4 -1
  64. package/dist-cjs/synth/deny-cases.js +3 -0
  65. package/dist-cjs/synth/evaluate.js +130 -3
  66. package/dist-cjs/synth/permit-context.d.ts +15 -0
  67. package/dist-cjs/synth/permit-context.js +119 -0
  68. package/dist-cjs/synth/synthesize-from-mandate.d.ts +17 -2
  69. package/dist-cjs/synth/synthesize-from-mandate.js +27 -2
  70. package/dist-cjs/synth/synthesize-from-recording.d.ts +25 -1
  71. package/dist-cjs/synth/synthesize-from-recording.js +80 -3
  72. package/dist-cjs/types.d.ts +9 -0
  73. package/package.json +5 -2
  74. package/src/adapters/interpreter/adapter.ts +72 -11
  75. package/src/contracts/policy-template/OZ_POLICY_TRAIT.md +28 -3
  76. package/src/errors.ts +13 -0
  77. package/src/install/build-add-context-rule.ts +429 -0
  78. package/src/ir/types.ts +4 -0
  79. package/src/predicate/decode.ts +242 -0
  80. package/src/predicate/encode.ts +110 -13
  81. package/src/predicate/from-json.ts +124 -0
  82. package/src/predicate/index.ts +5 -1
  83. package/src/registry/identify.ts +22 -2
  84. package/src/registry/protocols.ts +90 -1
  85. package/src/review-card/builder.ts +57 -5
  86. package/src/review-card/cross-check.ts +50 -3
  87. package/src/review-card/index.ts +1 -0
  88. package/src/run/index.ts +16 -2
  89. package/src/run/schemas.ts +14 -0
  90. package/src/synth/compose-from-recording.ts +46 -7
  91. package/src/synth/deny-cases.ts +3 -1
  92. package/src/synth/evaluate.ts +131 -3
  93. package/src/synth/permit-context.ts +137 -0
  94. package/src/synth/synthesize-from-mandate.ts +40 -4
  95. package/src/synth/synthesize-from-recording.ts +116 -6
  96. package/src/types.ts +12 -0
@@ -0,0 +1,429 @@
1
+ // src/install/build-add-context-rule.ts - pure builder for the OZ
2
+ // `add_context_rule` invocation arguments.
3
+ //
4
+ // Hand-rolled instead of reusing the scripts' helpers because the product
5
+ // path (Phase 06 install_policy) needs a single callable that takes a typed
6
+ // `ContextRuleDraft` + predicate bytes and returns the `ScVal` argument list
7
+ // the host will pass to `add_context_rule`. The script-level helpers stay
8
+ // out of `src/` to avoid dragging the ts-node SDK into the library surface.
9
+ //
10
+ // The OZ trait signature is pinned in
11
+ // `stellar-contracts::smart_account::SmartAccount::add_context_rule`:
12
+ //
13
+ // fn add_context_rule(
14
+ // e: &Env,
15
+ // context_type: ContextRuleType,
16
+ // name: String,
17
+ // valid_until: Option<u32>,
18
+ // signers: Vec<Signer>,
19
+ // policies: Map<Address, Val>,
20
+ // ) -> ContextRule
21
+ //
22
+ // The default body calls `e.current_contract_address().require_auth()`, so
23
+ // installation goes through the account's `__check_auth` -> `do_check_auth`.
24
+ // That requires the DEPLOYER to have shipped an admin rule with NO
25
+ // restrictive policy, otherwise the policy would refuse the very call that
26
+ // installs it. The caller is responsible for that contract; this builder
27
+ // just emits the args.
28
+ //
29
+ // Two hard limits the contract enforces (verified against
30
+ // `storage::validate_signers_and_policies` at /tmp/ozsc):
31
+ // - signers.len() <= MAX_SIGNERS (15)
32
+ // - policies.len() <= MAX_POLICIES (5)
33
+ // - signers and policies must not both be empty
34
+ // The same limits are mirrored in `OZ_LIMITS` (see src/types.ts) and
35
+ // checked here fail-closed before any encoding work - the user gets a
36
+ // typed error with the specific cap, not a runtime trap.
37
+ //
38
+ // Policypayloads are `Map<Address, Val>`. The host orders map entries by the
39
+ // symbol STRING of the key, NOT by the key's XDR bytes (a length prefix
40
+ // would otherwise put `amount` before `address` and produce a map the
41
+ // contract reads differently - a previous session lost hours to this). Our
42
+ // only key is an `Address`, so we build a single-entry map and the ordering
43
+ // question is moot, but the comment is here so the next map-bearing code
44
+ // in this file does not regress.
45
+ //
46
+ // Pure: no network, no signing. The caller hands the returned ScVal[] to
47
+ // `Operation.invokeHostFunction` AFTER wiring the auth entries, otherwise
48
+ // the account refuses with `Error(Auth, InvalidAction)`.
49
+
50
+ import { createHash } from 'node:crypto'
51
+ import { Address, xdr } from '@stellar/stellar-sdk'
52
+ import type { ToolError } from '../errors.ts'
53
+ import {
54
+ type ContextRuleDraft,
55
+ OZ_LIMITS,
56
+ type OZPrimitiveConfig,
57
+ type PolicyRef,
58
+ type SignerDraft,
59
+ } from '../types.ts'
60
+
61
+ /** Inputs for `buildAddContextRuleArgs`. The fields are the ones the contract
62
+ * validates at install; everything else is downstream. */
63
+ export interface BuildAddContextRuleArgs {
64
+ /** The auth-context rule signers to attach - `Vec<Signer>` wire form.
65
+ * These are the SIGNERS the new rule authorises, not the deployer's
66
+ * admin session. The deployer signs the install call via the admin rule
67
+ * already on the account, which is separate from this list. */
68
+ signers: SignerDraft[]
69
+ /** The policy(ies) to attach to the new rule. Only `interpreter` refs
70
+ * reach the wire today; `oz_builtin` is reserved for Phase 06 follow-ups. */
71
+ policies: PolicyRef[]
72
+ /** Per-policy install nonce; 1 for a fresh install. */
73
+ installNonce: number
74
+ /** Already-encoded (base64) canonical ScVal of the predicate. The builder
75
+ * decodes it to bytes for the `predicate` field and re-hashes to confirm
76
+ * the caller-supplied `predicateHash` matches. */
77
+ encodedPredicate: string
78
+ /** Hex sha256 of the canonical predicate XDR bytes. */
79
+ predicateHash: string
80
+ /** Per-policy oracle overrides. Absent on any key uses the wasm default. */
81
+ oracleParams?: {
82
+ maxStalenessSeconds?: number
83
+ maxDeviationBps?: number
84
+ /** Bound between the primary and secondary feeds. Tighten-only against
85
+ * the wasm default, like the other two. */
86
+ maxCrossFeedDeviationBps?: number
87
+ }
88
+ /** Hard pin to the interpreter's wasm grammar. Refusing here fails closed
89
+ * before the chain does; the contract will refuse a mismatch again. */
90
+ grammarVersion?: number
91
+ }
92
+
93
+ export const DEFAULT_GRAMMAR_VERSION = 1 as const
94
+
95
+ /** The verb `add_context_rule` takes on the wire. */
96
+ export const ADD_CONTEXT_RULE_SYMBOL = 'add_context_rule' as const
97
+
98
+ /** Tuple of `ScVal` arguments to pass to `Operation.invokeHostFunction` for
99
+ * `add_context_rule`. Order matches the OZ trait signature. */
100
+ export type AddContextRuleArgs = readonly [
101
+ contextType: xdr.ScVal,
102
+ name: xdr.ScVal,
103
+ validUntil: xdr.ScVal,
104
+ signers: xdr.ScVal,
105
+ policies: xdr.ScVal,
106
+ ]
107
+
108
+ /** Build the `add_context_rule` invocation args. Throws a `ToolError`-shaped
109
+ * error on limit breaches or malformed input. */
110
+ export function buildAddContextRuleArgs(
111
+ draft: ContextRuleDraft,
112
+ args: BuildAddContextRuleArgs
113
+ ): AddContextRuleArgs {
114
+ // ---- 1. Cap checks (fail-closed before any encoding) ----
115
+ if (args.signers.length > OZ_LIMITS.maxSignersPerRule) {
116
+ throw limitError(
117
+ 'INSTALL_BUILD_FAILED',
118
+ `signers ${args.signers.length} exceed MAX_SIGNERS_PER_RULE ${OZ_LIMITS.maxSignersPerRule}`
119
+ )
120
+ }
121
+ if (args.policies.length > OZ_LIMITS.maxPoliciesPerRule) {
122
+ throw limitError(
123
+ 'INSTALL_BUILD_FAILED',
124
+ `policies ${args.policies.length} exceed MAX_POLICIES_PER_RULE ${OZ_LIMITS.maxPoliciesPerRule}`
125
+ )
126
+ }
127
+ if (args.signers.length === 0 && args.policies.length === 0) {
128
+ throw limitError(
129
+ 'INSTALL_BUILD_FAILED',
130
+ 'a rule with no signers and no policies is refused at install (NoSignersAndPolicies)'
131
+ )
132
+ }
133
+ // OZ's spending_limit caps spend on the CONTEXT CONTRACT - it takes no
134
+ // token argument - so it refuses a Default rule on chain with a bare
135
+ // #3227. Say which rule shape it needs here, before the encoding, rather
136
+ // than letting the user read a numeric trap.
137
+ if (
138
+ args.policies.some((p) => p.kind === 'oz_builtin' && p.primitive.primitive === 'spending_limit')
139
+ ) {
140
+ if (draft.contextRuleType.kind !== 'call_contract') {
141
+ throw limitError(
142
+ 'INSTALL_BUILD_FAILED',
143
+ `spending_limit caps spend on the rule's context contract, so the rule must be call_contract-scoped to that token - a "${draft.contextRuleType.kind}" rule is refused on chain (#3227)`
144
+ )
145
+ }
146
+ }
147
+
148
+ // ---- 2. context_type encoding ----
149
+ const contextType = encodeContextRuleType(draft.contextRuleType)
150
+
151
+ // ---- 3. name (string) + valid_until (Option<u32>) ----
152
+ const name = xdr.ScVal.scvString(draft.name)
153
+ const validUntil =
154
+ draft.validUntilLedger === null ? xdr.ScVal.scvVoid() : xdr.ScVal.scvU32(draft.validUntilLedger)
155
+
156
+ // ---- 4. signers ----
157
+ const signersVec = xdr.ScVal.scvVec(args.signers.map(encodeSigner))
158
+
159
+ // ---- 5. policies Map<Address, Val> ----
160
+ const policies = encodePoliciesMap(args)
161
+
162
+ return [contextType, name, validUntil, signersVec, policies] as const
163
+ }
164
+
165
+ // ---- helpers ----
166
+
167
+ /** Field order of the `PolicyInstallParams` struct. The contract's
168
+ * `#[contracttype]` derives a Map<Symbol, Val> encoding, so the host
169
+ * sorts by symbol STRING (NOT by XDR bytes). This explicit list is the
170
+ * single source of truth for the field order. */
171
+ const POLICY_INSTALL_PARAM_FIELDS = [
172
+ 'grammar_version',
173
+ 'install_nonce',
174
+ 'predicate',
175
+ 'predicate_hash',
176
+ 'oracle_max_staleness_seconds',
177
+ 'oracle_max_deviation_bps',
178
+ // Cross-feed divergence bound. A field added to the contract's
179
+ // `PolicyInstallParams` changes the ABI: the host unpacks the map by field
180
+ // count, so omitting one fails the entire install with
181
+ // `Error(Object, UnexpectedSize)` and no indication of which field is
182
+ // missing. The Rust tests build that struct in Rust and never cross this
183
+ // boundary, so only a real install against a deployed contract catches it.
184
+ 'oracle_max_xfeed_dev_bps',
185
+ ] as const
186
+
187
+ function encodeContextRuleType(
188
+ rule:
189
+ | { kind: 'default' }
190
+ | { kind: 'call_contract'; contract: string }
191
+ | { kind: 'create_contract'; wasmHash: string }
192
+ ): xdr.ScVal {
193
+ switch (rule.kind) {
194
+ case 'default':
195
+ return xdr.ScVal.scvVec([xdr.ScVal.scvSymbol('Default')])
196
+ case 'call_contract':
197
+ return xdr.ScVal.scvVec([
198
+ xdr.ScVal.scvSymbol('CallContract'),
199
+ Address.fromString(rule.contract).toScVal(),
200
+ ])
201
+ case 'create_contract':
202
+ return xdr.ScVal.scvVec([
203
+ xdr.ScVal.scvSymbol('CreateContract'),
204
+ xdr.ScVal.scvBytes(Buffer.from(rule.wasmHash, 'hex')),
205
+ ])
206
+ }
207
+ }
208
+
209
+ function encodeSigner(s: SignerDraft): xdr.ScVal {
210
+ switch (s.kind) {
211
+ case 'delegated':
212
+ return xdr.ScVal.scvVec([
213
+ xdr.ScVal.scvSymbol('Delegated'),
214
+ Address.fromString(s.address).toScVal(),
215
+ ])
216
+ case 'external':
217
+ return xdr.ScVal.scvVec([
218
+ xdr.ScVal.scvSymbol('External'),
219
+ Address.fromString(s.verifier).toScVal(),
220
+ xdr.ScVal.scvBytes(Buffer.from(s.keyBytes, 'hex')),
221
+ ])
222
+ }
223
+ }
224
+
225
+ function encodePoliciesMap(args: BuildAddContextRuleArgs): xdr.ScVal {
226
+ const entries: xdr.ScMapEntry[] = []
227
+ for (const ref of args.policies) {
228
+ if (ref.kind === 'interpreter') {
229
+ const val = encodePolicyInstallParams(args)
230
+ entries.push(
231
+ new xdr.ScMapEntry({
232
+ key: Address.fromString(ref.interpreterAddress).toScVal(),
233
+ val,
234
+ })
235
+ )
236
+ }
237
+ if (ref.kind === 'oz_builtin') {
238
+ entries.push(
239
+ new xdr.ScMapEntry({
240
+ key: Address.fromString(ref.instanceAddress).toScVal(),
241
+ val: encodeOzPrimitiveParams(ref.primitive),
242
+ })
243
+ )
244
+ }
245
+ }
246
+ entries.sort(sortByScValSymbolString)
247
+ return xdr.ScVal.scvMap(entries)
248
+ }
249
+
250
+ /** Encode the install params for one OZ built-in policy.
251
+ *
252
+ * Field names and types are read from the deployed contracts' own spec:
253
+ * SpendingLimitAccountParams { period_ledgers: u32, spending_limit: i128 }
254
+ * SimpleThresholdAccountParams { threshold: u32 }
255
+ * WeightedThresholdAccountParams { signer_weights: map, threshold: u32 }
256
+ * Entries are symbol-string ordered for the same reason the interpreter's
257
+ * are: the host orders by symbol, not by XDR bytes.
258
+ */
259
+ function encodeOzPrimitiveParams(primitive: OZPrimitiveConfig): xdr.ScVal {
260
+ const entries: xdr.ScMapEntry[] = []
261
+ const push = (name: string, val: xdr.ScVal) =>
262
+ entries.push(new xdr.ScMapEntry({ key: xdr.ScVal.scvSymbol(name), val }))
263
+ const p = primitive.params as Record<string, unknown>
264
+ switch (primitive.primitive) {
265
+ case 'spending_limit': {
266
+ const limit = p.spending_limit
267
+ const period = p.period_ledgers
268
+ if (typeof limit !== 'string' || typeof period !== 'number') {
269
+ throw limitError(
270
+ 'INSTALL_BUILD_FAILED',
271
+ 'spending_limit needs { spending_limit: string; period_ledgers: number }'
272
+ )
273
+ }
274
+ push('period_ledgers', xdr.ScVal.scvU32(period))
275
+ push('spending_limit', encodeI128(limit))
276
+ break
277
+ }
278
+ case 'simple_threshold': {
279
+ const threshold = p.threshold
280
+ if (typeof threshold !== 'number') {
281
+ throw limitError('INSTALL_BUILD_FAILED', 'simple_threshold needs { threshold: number }')
282
+ }
283
+ push('threshold', xdr.ScVal.scvU32(threshold))
284
+ break
285
+ }
286
+ case 'weighted_threshold': {
287
+ const threshold = p.threshold
288
+ const weights = p.weights as Record<string, number> | undefined
289
+ if (typeof threshold !== 'number' || !weights) {
290
+ throw limitError(
291
+ 'INSTALL_BUILD_FAILED',
292
+ 'weighted_threshold needs { threshold: number; weights: Record<address, number> }'
293
+ )
294
+ }
295
+ const weightEntries = Object.entries(weights)
296
+ .map(
297
+ ([addr, w]) =>
298
+ new xdr.ScMapEntry({
299
+ key: Address.fromString(addr).toScVal(),
300
+ val: xdr.ScVal.scvU32(w),
301
+ })
302
+ )
303
+ .sort((a, b) => (a.key().toXDR('base64') < b.key().toXDR('base64') ? -1 : 1))
304
+ push('signer_weights', xdr.ScVal.scvMap(weightEntries))
305
+ push('threshold', xdr.ScVal.scvU32(threshold))
306
+ break
307
+ }
308
+ }
309
+ entries.sort((a, b) => sortBySymbolString(a.key(), b.key()))
310
+ return xdr.ScVal.scvMap(entries)
311
+ }
312
+
313
+ function encodeI128(value: string): xdr.ScVal {
314
+ const v = BigInt(value)
315
+ return xdr.ScVal.scvI128(
316
+ new xdr.Int128Parts({
317
+ hi: new xdr.Int64(BigInt.asIntN(64, v >> 64n)),
318
+ lo: new xdr.Uint64(BigInt.asUintN(64, v)),
319
+ })
320
+ )
321
+ }
322
+
323
+ function encodePolicyInstallParams(args: BuildAddContextRuleArgs): xdr.ScVal {
324
+ const predicate = Buffer.from(args.encodedPredicate, 'base64')
325
+ const computedHash = createHash('sha256').update(predicate).digest('hex')
326
+ if (computedHash !== args.predicateHash) {
327
+ throw limitError(
328
+ 'INSTALL_BUILD_FAILED',
329
+ `predicateHash ${args.predicateHash.slice(0, 16)}... does not match sha256(encodedPredicate) ${computedHash.slice(0, 16)}...`
330
+ )
331
+ }
332
+ const entries: xdr.ScMapEntry[] = []
333
+ for (const k of POLICY_INSTALL_PARAM_FIELDS) {
334
+ const key = xdr.ScVal.scvSymbol(k)
335
+ switch (k) {
336
+ case 'grammar_version':
337
+ entries.push(
338
+ new xdr.ScMapEntry({
339
+ key,
340
+ val: xdr.ScVal.scvU32(args.grammarVersion ?? DEFAULT_GRAMMAR_VERSION),
341
+ })
342
+ )
343
+ break
344
+ case 'install_nonce':
345
+ entries.push(new xdr.ScMapEntry({ key, val: xdr.ScVal.scvU32(args.installNonce) }))
346
+ break
347
+ case 'predicate':
348
+ entries.push(new xdr.ScMapEntry({ key, val: xdr.ScVal.scvBytes(predicate) }))
349
+ break
350
+ case 'predicate_hash':
351
+ entries.push(
352
+ new xdr.ScMapEntry({
353
+ key,
354
+ val: xdr.ScVal.scvBytes(Buffer.from(args.predicateHash, 'hex')),
355
+ })
356
+ )
357
+ break
358
+ case 'oracle_max_staleness_seconds':
359
+ entries.push(
360
+ new xdr.ScMapEntry({
361
+ key,
362
+ val: encodeOptionU32(args.oracleParams?.maxStalenessSeconds),
363
+ })
364
+ )
365
+ break
366
+ case 'oracle_max_deviation_bps':
367
+ entries.push(
368
+ new xdr.ScMapEntry({
369
+ key,
370
+ val: encodeOptionU32(args.oracleParams?.maxDeviationBps),
371
+ })
372
+ )
373
+ break
374
+ case 'oracle_max_xfeed_dev_bps':
375
+ entries.push(
376
+ new xdr.ScMapEntry({
377
+ key,
378
+ val: encodeOptionU32(args.oracleParams?.maxCrossFeedDeviationBps),
379
+ })
380
+ )
381
+ break
382
+ }
383
+ }
384
+ // The host orders map entries by the SYMBOL STRING, not by XDR bytes. A
385
+ // length prefix in the XDR encoding would otherwise put `amount` before
386
+ // `address` and produce a struct the contract reads differently. Emit the
387
+ // entries in symbol-string order so the wire form matches the host's view.
388
+ entries.sort((a, b) => sortBySymbolString(a.key(), b.key()))
389
+ return xdr.ScVal.scvMap(entries)
390
+ }
391
+
392
+ function encodeOptionU32(v: number | undefined): xdr.ScVal {
393
+ if (v === undefined) return xdr.ScVal.scvVoid()
394
+ if (!Number.isFinite(v) || v < 0 || v > 0xffffffff) {
395
+ throw limitError('INSTALL_BUILD_FAILED', `oracle params value ${v} is outside u32 range`)
396
+ }
397
+ return xdr.ScVal.scvU32(v)
398
+ }
399
+
400
+ /** Sort host-map keys by their symbol-string form. The host orders map
401
+ * entries by the SYMBOL STRING, not by the key's XDR bytes (a length
402
+ * prefix in the encoding would otherwise put `amount` before `address`).
403
+ * For non-symbol keys we fall back to length-prefixed XDR bytes; the
404
+ * caller's only Address keys today are length-stable so this is moot, but
405
+ * the helper stands ready for the multi-policy variant. */
406
+ function sortByScValSymbolString(a: xdr.ScMapEntry, b: xdr.ScMapEntry): number {
407
+ return sortBySymbolString(a.key(), b.key())
408
+ }
409
+
410
+ function sortBySymbolString(a: xdr.ScVal, b: xdr.ScVal): number {
411
+ const aSym = a.switch().name === 'scvSymbol' ? a.sym().toString() : null
412
+ const bSym = b.switch().name === 'scvSymbol' ? b.sym().toString() : null
413
+ if (aSym !== null && bSym !== null) {
414
+ return aSym < bSym ? -1 : aSym > bSym ? 1 : 0
415
+ }
416
+ return Buffer.compare(a.toXDR(), b.toXDR())
417
+ }
418
+
419
+ function limitError(code: ToolError['code'], message: string): ToolError {
420
+ const err = new Error(message) as Error & {
421
+ code: ToolError['code']
422
+ severity: string
423
+ retryable: boolean
424
+ }
425
+ err.code = code
426
+ err.severity = 'error'
427
+ err.retryable = false
428
+ throw err
429
+ }
package/src/ir/types.ts CHANGED
@@ -65,6 +65,10 @@ export interface IRCompare {
65
65
  selector: IRSelector
66
66
  operator: IRCompOp
67
67
  value: string
68
+ /** Decimal basis of `value`, for selectors whose comparand is not on a basis
69
+ * the contract can infer. Set for `oracle_price`, where prices normalise to
70
+ * 9 dp and an undeclared basis fails OPEN. */
71
+ valueDecimals?: number
68
72
  }
69
73
 
70
74
  /** Condition tree. NEAR-V2 guard/constraint are flat And/Or; the IR allows
@@ -0,0 +1,242 @@
1
+ // src/predicate/decode.ts - the inverse of `encode.ts`.
2
+ //
3
+ // Turns the canonical wire encoding back into a `PredicateNode`, so a policy
4
+ // already installed on chain can be read and explained. The interpreter has no
5
+ // getter for the document, but its persistent storage IS readable over RPC, so
6
+ // the bytes are available to any caller that can reconstruct the storage key -
7
+ // this module takes it from there.
8
+ //
9
+ // Mirrors `decode_leaf` / `decode_node` in
10
+ // `packages/policy-interpreter/src/dsl.rs`. Two rules carry most of the
11
+ // weight, and both come from the Rust decoder verbatim:
12
+ //
13
+ // 1. A `Vec` whose FIRST element is a Symbol is a selector tuple. A `Vec`
14
+ // whose first element is anything else is a `literal_vec`, decoded
15
+ // element-wise with order preserved (the order IS the semantic for exact
16
+ // sequence equality).
17
+ // 2. An unknown symbol at a selector position is MALFORMED, never a
18
+ // literal_vec fallback. Guessing there would let an unsupported selector
19
+ // decode as data and read as permitted.
20
+ //
21
+ // The round-trip `decode(encode(node)) === node` is pinned in decode.test.ts
22
+ // for every leaf and node shape; that test is what keeps this file honest as
23
+ // the grammar grows.
24
+
25
+ import { Address, scValToBigInt, xdr } from '@stellar/stellar-sdk'
26
+ import type { ToolError } from '../errors.ts'
27
+ import type { PredicateLeaf, PredicateNode } from '../types.ts'
28
+
29
+ /** Same shape the encoder raises, so both directions surface one error type.
30
+ * Returns `never` - it always throws; callers `throw malformed(...)` purely
31
+ * so the control flow reads at the call site. */
32
+ function malformed(detail: string): never {
33
+ const err = new Error(`cannot decode predicate: ${detail}`) as Error & {
34
+ code: ToolError['code']
35
+ severity: string
36
+ retryable: boolean
37
+ }
38
+ err.code = 'MALFORMED_PREDICATE'
39
+ err.severity = 'error'
40
+ err.retryable = false
41
+ throw err
42
+ }
43
+
44
+ /** The symbol at a leaf's selector position, or null when the value is not a
45
+ * symbol-headed vec (i.e. it is a literal or a literal vector). */
46
+ function selectorSymbol(items: xdr.ScVal[]): string | null {
47
+ const head = items[0]
48
+ if (!head) return null
49
+ return head.switch() === xdr.ScValType.scvSymbol() ? head.sym().toString() : null
50
+ }
51
+
52
+ function expectVec(v: xdr.ScVal, what: string): xdr.ScVal[] {
53
+ if (v.switch() !== xdr.ScValType.scvVec()) throw malformed(`${what} is not a vec`)
54
+ return v.vec() ?? []
55
+ }
56
+
57
+ function expectU32(v: xdr.ScVal | undefined, what: string): number {
58
+ if (!v || v.switch() !== xdr.ScValType.scvU32()) throw malformed(`${what} is not a u32`)
59
+ return v.u32()
60
+ }
61
+
62
+ function expectSymbol(v: xdr.ScVal | undefined, what: string): string {
63
+ if (!v || v.switch() !== xdr.ScValType.scvSymbol()) throw malformed(`${what} is not a symbol`)
64
+ return v.sym().toString()
65
+ }
66
+
67
+ function expectAddress(v: xdr.ScVal | undefined, what: string): string {
68
+ if (!v || v.switch() !== xdr.ScValType.scvAddress()) throw malformed(`${what} is not an address`)
69
+ return Address.fromScAddress(v.address()).toString()
70
+ }
71
+
72
+ function expectU64(v: xdr.ScVal | undefined, what: string): string {
73
+ if (!v || v.switch() !== xdr.ScValType.scvU64()) throw malformed(`${what} is not a u64`)
74
+ return v.u64().toString()
75
+ }
76
+
77
+ function expectI128(v: xdr.ScVal | undefined, what: string): string {
78
+ if (!v || v.switch() !== xdr.ScValType.scvI128()) throw malformed(`${what} is not an i128`)
79
+ return scValToBigInt(v).toString()
80
+ }
81
+
82
+ /** Arity check with the same intent as the Rust `check_arity`: a selector with
83
+ * the wrong element count is malformed, not silently truncated. */
84
+ function arity(items: xdr.ScVal[], n: number, selector: string): void {
85
+ if (items.length !== n) {
86
+ throw malformed(`${selector} expects ${n} elements, got ${items.length}`)
87
+ }
88
+ }
89
+
90
+ function decodeSelectorLeaf(items: xdr.ScVal[], sym: string): PredicateLeaf {
91
+ switch (sym) {
92
+ case 'call_contract':
93
+ arity(items, 1, sym)
94
+ return { kind: 'call_contract' }
95
+ case 'call_fn':
96
+ arity(items, 1, sym)
97
+ return { kind: 'call_fn' }
98
+ case 'call_arg':
99
+ arity(items, 2, sym)
100
+ return { kind: 'call_arg', index: expectU32(items[1], 'call_arg index') }
101
+ case 'call_arg_len':
102
+ arity(items, 2, sym)
103
+ return { kind: 'call_arg_len', index: expectU32(items[1], 'call_arg_len index') }
104
+ case 'call_arg_field':
105
+ arity(items, 4, sym)
106
+ return {
107
+ kind: 'call_arg_field',
108
+ index: expectU32(items[1], 'call_arg_field index'),
109
+ element: expectU32(items[2], 'call_arg_field element'),
110
+ field: expectSymbol(items[3], 'call_arg_field field'),
111
+ }
112
+ case 'call_arg_scaled':
113
+ arity(items, 4, sym)
114
+ return {
115
+ kind: 'call_arg_scaled',
116
+ index: expectU32(items[1], 'call_arg_scaled index'),
117
+ num: expectI128(items[2], 'call_arg_scaled num'),
118
+ den: expectI128(items[3], 'call_arg_scaled den'),
119
+ }
120
+ case 'amount':
121
+ arity(items, 2, sym)
122
+ return { kind: 'amount', token: expectAddress(items[1], 'amount token') }
123
+ case 'window_spent':
124
+ arity(items, 3, sym)
125
+ return {
126
+ kind: 'window_spent',
127
+ token: expectAddress(items[1], 'window_spent token'),
128
+ windowSeconds: Number(expectU64(items[2], 'window_spent windowSeconds')),
129
+ }
130
+ case 'now':
131
+ arity(items, 1, sym)
132
+ return { kind: 'now' }
133
+ case 'valid_until':
134
+ // The encoder refuses to emit this and the interpreter refuses it at
135
+ // install, so it cannot appear in a document that installed. Decoding it
136
+ // anyway would present a rule the chain would never have accepted.
137
+ throw malformed('valid_until is not a usable predicate leaf')
138
+ case 'invocation_count':
139
+ arity(items, 2, sym)
140
+ return {
141
+ kind: 'invocation_count_in_window',
142
+ windowSecs: Number(expectU64(items[1], 'invocation_count windowSecs')),
143
+ }
144
+ case 'oracle_price':
145
+ arity(items, 2, sym)
146
+ return { kind: 'oracle_price', asset: expectAddress(items[1], 'oracle_price asset') }
147
+ case 'oracle_threshold':
148
+ arity(items, 3, sym)
149
+ return {
150
+ kind: 'oracle_threshold',
151
+ value: expectI128(items[1], 'oracle_threshold value'),
152
+ decimals: expectU32(items[2], 'oracle_threshold decimals'),
153
+ }
154
+ default:
155
+ // Deliberately NOT a literal_vec fallback - see the header note.
156
+ throw malformed(`unknown selector symbol '${sym}'`)
157
+ }
158
+ }
159
+
160
+ /** One leaf. Order of the bare-literal checks mirrors `decode_leaf` in dsl.rs. */
161
+ export function decodeLeaf(v: xdr.ScVal): PredicateLeaf {
162
+ if (v.switch() === xdr.ScValType.scvVec()) {
163
+ const items = v.vec() ?? []
164
+ if (items.length === 0) throw malformed('empty vec is neither a selector nor a literal vector')
165
+ const sym = selectorSymbol(items)
166
+ if (sym !== null) return decodeSelectorLeaf(items, sym)
167
+ return { kind: 'literal_vec', elements: items.map(decodeLeaf) }
168
+ }
169
+ switch (v.switch()) {
170
+ case xdr.ScValType.scvAddress():
171
+ return { kind: 'literal_address', value: Address.fromScAddress(v.address()).toString() }
172
+ case xdr.ScValType.scvSymbol():
173
+ return { kind: 'literal_symbol', value: v.sym().toString() }
174
+ case xdr.ScValType.scvU32():
175
+ return { kind: 'literal_u32', value: v.u32() }
176
+ case xdr.ScValType.scvU64():
177
+ return { kind: 'literal_u64', value: v.u64().toString() }
178
+ case xdr.ScValType.scvI128():
179
+ return { kind: 'literal_i128', value: scValToBigInt(v).toString() }
180
+ case xdr.ScValType.scvBytes():
181
+ return { kind: 'literal_bytes', value: Buffer.from(v.bytes()).toString('hex') }
182
+ default:
183
+ throw malformed(`unsupported leaf value type ${v.switch().name}`)
184
+ }
185
+ }
186
+
187
+ /** One node. `not` wraps a NODE; the comparison ops wrap two LEAVES. */
188
+ export function decodeNode(v: xdr.ScVal): PredicateNode {
189
+ const items = expectVec(v, 'node')
190
+ const op = selectorSymbol(items)
191
+ if (op === null) throw malformed('node does not start with an operator symbol')
192
+ switch (op) {
193
+ case 'and':
194
+ case 'or': {
195
+ arity(items, 2, op)
196
+ const children = expectVec(items[1] as xdr.ScVal, `${op} children`).map(decodeNode)
197
+ if (children.length === 0) throw malformed(`${op} has no children`)
198
+ return { op, children }
199
+ }
200
+ case 'not':
201
+ arity(items, 2, op)
202
+ return { op: 'not', child: decodeNode(items[1] as xdr.ScVal) }
203
+ case 'eq':
204
+ case 'lt':
205
+ case 'lte':
206
+ case 'gt':
207
+ case 'gte':
208
+ arity(items, 3, op)
209
+ return {
210
+ op,
211
+ left: decodeLeaf(items[1] as xdr.ScVal),
212
+ right: decodeLeaf(items[2] as xdr.ScVal),
213
+ }
214
+ case 'in': {
215
+ arity(items, 3, op)
216
+ return {
217
+ op: 'in',
218
+ needle: decodeLeaf(items[1] as xdr.ScVal),
219
+ haystack: expectVec(items[2] as xdr.ScVal, 'in haystack').map(decodeLeaf),
220
+ }
221
+ }
222
+ default:
223
+ throw malformed(`unknown node operator '${op}'`)
224
+ }
225
+ }
226
+
227
+ /** Decode a predicate from the wire bytes the interpreter stores.
228
+ *
229
+ * Accepts the base64 the encoder emits (`encodePredicate().encodedPredicate`)
230
+ * or the raw XDR bytes read straight out of `StoredDoc.predicate_bytes`. */
231
+ export function decodePredicate(encoded: string | Uint8Array): PredicateNode {
232
+ let scv: xdr.ScVal
233
+ try {
234
+ scv =
235
+ typeof encoded === 'string'
236
+ ? xdr.ScVal.fromXDR(Buffer.from(encoded, 'base64'))
237
+ : xdr.ScVal.fromXDR(Buffer.from(encoded))
238
+ } catch (e) {
239
+ throw malformed(`not valid ScVal XDR (${e instanceof Error ? e.message : String(e)})`)
240
+ }
241
+ return decodeNode(scv)
242
+ }