@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
@@ -7,9 +7,9 @@
7
7
  // step with the TS source of truth.
8
8
  //
9
9
  // i128 amounts and other large integers are carried as base-10 decimal strings
10
- // end-to-end (no JS number coercion). Networks are pinned to the same closed
11
- // set the core defines. The discriminated union on `source` exposes BOTH
12
- // synthesize_policy front-ends through a single tool input.
10
+ // end-to-end. Networks are pinned to the same closed set the core defines.
11
+ // The discriminated union on `source` exposes BOTH synthesize_policy
12
+ // front-ends through a single tool input.
13
13
  //
14
14
  // This module is the SINGLE source of truth for these shapes. The MCP package
15
15
  // imports them here so its tool-shape bindings stay in step; the CLI imports
@@ -123,7 +123,21 @@ export const MandateSpecSchema = z
123
123
  })
124
124
  .optional(),
125
125
  })
126
- .passthrough();
126
+ .passthrough()
127
+ // TS-F4/F6: a `recipients` allowlist is only meaningful against a SEP-41
128
+ // method whose arg 1 IS the recipient (SAC/SEP-41 `transfer(from, to,
129
+ // amount)` and SEP-41 `mint(to, amount)`). Without this gate the
130
+ // `to-ir.ts` lowering pins the allowlist to `RECIPIENT_ARG_INDEX = 1`
131
+ // for any contract+method, which would let a non-SEP-41 method's
132
+ // arg[1] (e.g. an amount, an op type, an arbitrary address payload)
133
+ // be silently constrained as if it were a recipient. Refusing
134
+ // non-SEP-41 methods at the boundary is the fail-closed shape.
135
+ .refine((v) => v.recipients === undefined ||
136
+ v.recipients.length === 0 ||
137
+ v.method === 'transfer' ||
138
+ v.method === 'mint', {
139
+ message: 'recipients is only valid when method is a SEP-41 method (transfer or mint); other methods do not have a recipient at arg[1]',
140
+ });
127
141
  /** ComposeUserResponses mirrors the core. */
128
142
  export const ComposeUserResponsesSchema = z
129
143
  .object({
@@ -141,6 +155,21 @@ export const ComposeUserResponsesSchema = z
141
155
  swapRecipientAllowlist: z
142
156
  .array(z.string().refine(isStellarAddress, 'must be a Stellar address (G... or C...)'))
143
157
  .optional(),
158
+ // Per-asset oracle-price bound, one entry per asset. Reaches
159
+ // `compose-from-recording` and emits an `oracle_price` compare. Declared
160
+ // here because the object is `.passthrough()`: the field already worked
161
+ // undeclared, which left the accepted surface wider than the documented
162
+ // one. `decimals` is REQUIRED - oracle prices normalise to 9 dp and a
163
+ // threshold silently assumed to share that basis is what let a raw 14-dp
164
+ // bound permit everything.
165
+ oraclePriceBound: z
166
+ .array(z.object({
167
+ asset: z.string().refine(isStellarAddress, 'must be a Stellar address (G... or C...)'),
168
+ operator: z.enum(['eq', 'lt', 'lte', 'gt', 'gte']),
169
+ value: z.string().regex(/^[0-9]+$/),
170
+ decimals: z.number().int().min(0).max(U32_MAX),
171
+ }))
172
+ .optional(),
144
173
  })
145
174
  .passthrough();
146
175
  /** OzAdapterConfig - the per-network OZ built-in instance addresses. */
@@ -264,7 +293,12 @@ export const PredicateLeafSchema = z.lazy(() => z.union([
264
293
  windowSeconds: z.number().int().positive(),
265
294
  }),
266
295
  z.object({ kind: z.literal('now') }),
267
- z.object({ kind: z.literal('valid_until') }),
296
+ // `valid_until` is NOT in the public predicate grammar: the encoder +
297
+ // decoder already throw on it, so accepting it here would let a
298
+ // hand-crafted payload through the schema and only surface a 200+
299
+ // character internal-commentary error at encode time. Drop it - the
300
+ // policy's expiry is carried at the install layer (MandateSpec +
301
+ // validUntilLedger) instead.
268
302
  z.object({
269
303
  kind: z.literal('invocation_count_in_window'),
270
304
  windowSecs: z.number().int().positive(),
@@ -424,20 +458,28 @@ const MandateSpecSchemaForRule = z
424
458
  // install/revoke/get_info schemas live HERE (after the helper) so the const
425
459
  // reference resolves at module init. They are the new tools on top of the
426
460
  // existing four.
427
- /** Pinned interpreter address (testnet). Mirrors DEPLOYMENTS.md:128.
461
+ /** Pinned interpreter address (testnet).
428
462
  * Single source for the MCP layer; do not embed elsewhere. */
429
- export const PINNED_INTERPRETER_TESTNET_ADDRESS = 'CDR4NLV22STCXFGZPNKDQTEANWLF7LZ6AJLY6B7CLJXKHDZGYJWIOKGP';
430
- /** Pinned interpreter address (mainnet). Mirrors DEPLOYMENTS.md:18. Mainnet
431
- * has now been deployed (2026-08-04); the mainnet interpreter IS the binary
432
- * that was exercised on testnet (same wasm sha256, see
433
- * PINNED_INTERPRETER_WASM_SHA256). The address differs because instance
434
- * ids are network-scoped. UNAUDITED at the time of writing - see
435
- * DEPLOYMENTS.md:29-32 for the recorded decision and what is still pending. */
463
+ export const PINNED_INTERPRETER_TESTNET_ADDRESS = 'CALHNU4LXZRKFAXYRBODTGDANTNXHJPBTJNYGLUWLIFIP24NWSGWIE4K';
464
+ /** Pinned interpreter address (mainnet), deployed 2026-08-04.
465
+ * UNAUDITED at the time of writing. */
436
466
  export const PINNED_INTERPRETER_MAINNET_ADDRESS = 'CALZAMUPREIRY4TULBEXIK77AUTOEJG63XLCPUWEHHQDOVK6ZVVS7VQ2';
437
- /** Pinned interpreter wasm sha256 (hex). Mirrors DEPLOYMENTS.md:156-157. */
467
+ /** Pinned interpreter wasm sha256 (hex), mainnet.
468
+ *
469
+ * The two networks no longer run the same binary. Testnet carries the
470
+ * selector-leaf minimum and the signer-set cap; mainnet predates both. Read
471
+ * the hash through `PINNED_INTERPRETER_WASM_SHA256_BY_NETWORK` rather than
472
+ * this constant unless mainnet is specifically what is meant, or
473
+ * `get_interpreter_info` will report a hash the queried network does not
474
+ * run. */
438
475
  export const PINNED_INTERPRETER_WASM_SHA256 = '6e6c13d93e197aa380303a42cd120f5ddb080dd36ef2a343ee1dbd04ca52a443';
476
+ /** Pinned interpreter wasm sha256 (hex), testnet. Byte-identical to the
477
+ * artifact built from `contracts/policy-interpreter` at the commit that
478
+ * introduced errors 216 and 217, verified by fetching the deployed wasm back
479
+ * off chain. */
480
+ export const PINNED_INTERPRETER_WASM_SHA256_TESTNET = 'a4d58bc88fd82bbb8e223941ba5889db919717fae92ced13f6f55bfe583b8e22';
439
481
  /** The grammar version the interpreter enforces (matches SELF_VERSION in
440
- * packages/policy-interpreter/src/version.rs). */
482
+ * contracts/policy-interpreter/src/version.rs). */
441
483
  export const PINNED_INTERPRETER_GRAMMAR_VERSION = 1;
442
484
  /** Default Soroban RPC for the install / revoke / info tools. The recorder
443
485
  * keeps its own copy in record/rpc.ts because it hands back a fetcher rather
@@ -449,14 +491,18 @@ export const TESTNET_RPC_URL = 'https://soroban-testnet.stellar.org';
449
491
  * RPC rather than always testnet. Public mainnet endpoint, the same one
450
492
  * the deploy script hit during the 2026-08-04 mainnet rollout. */
451
493
  export const MAINNET_RPC_URL = 'https://mainnet.sorobanrpc.com';
452
- /** Pin + RPC lookup for the gate enforcement. The interpreters' wasm sha256
453
- * is identical across both networks (the same binary was uploaded both
454
- * places; DEPLOYMENTS.md:25-27), so `PINNED_INTERPRETER_WASM_SHA256` stays
455
- * a single constant - only the addresses and RPCs are network-scoped. */
494
+ /** Pin + RPC lookup for the gate enforcement. Addresses, RPCs and wasm
495
+ * hashes are all network-scoped: the networks diverged when the
496
+ * selector-leaf and signer-cap controls were deployed to testnet ahead of
497
+ * mainnet. */
456
498
  export const PINNED_INTERPRETER_ADDRESS_BY_NETWORK = {
457
499
  testnet: PINNED_INTERPRETER_TESTNET_ADDRESS,
458
500
  mainnet: PINNED_INTERPRETER_MAINNET_ADDRESS,
459
501
  };
502
+ export const PINNED_INTERPRETER_WASM_SHA256_BY_NETWORK = {
503
+ testnet: PINNED_INTERPRETER_WASM_SHA256_TESTNET,
504
+ mainnet: PINNED_INTERPRETER_WASM_SHA256,
505
+ };
460
506
  export const RPC_URL_BY_NETWORK = {
461
507
  testnet: TESTNET_RPC_URL,
462
508
  mainnet: MAINNET_RPC_URL,
@@ -471,13 +517,26 @@ export const NETWORK_PASSPHRASES = {
471
517
  testnet: 'Test SDF Network ; September 2015',
472
518
  mainnet: 'Public Global Stellar Network ; September 2015',
473
519
  };
520
+ // Stellar strkey shapes (StrKey base32, no checksum byte, version byte
521
+ // 0x30/0x40 prefixed by the decoder, then 32 base32 chars giving a 56-char
522
+ // total). The shared `isStellarAddress` helper accepts BOTH wallet (G...) and
523
+ // contract (C...) addresses; the install schema has to distinguish them
524
+ // because the smart account is a contract (C...) - a wallet address would
525
+ // mean the rule is being installed against the WRONG account kind entirely.
526
+ // `sourceAccount` is the signing wallet (G...).
527
+ const STELLAR_CONTRACT_ADDRESS = /^C[2-7A-Z]{55}$/;
528
+ const STELLAR_ACCOUNT_ADDRESS = /^G[2-7A-Z]{55}$/;
474
529
  export const InstallPolicyInputSchema = z
475
530
  .object({
476
531
  /** The smart account contract address (C...) that will receive the rule. */
477
- smartAccount: z.string(),
532
+ smartAccount: z
533
+ .string()
534
+ .regex(STELLAR_CONTRACT_ADDRESS, 'smartAccount must be a Stellar contract address (C...)'),
478
535
  /** The signer that authorises the install (G... wallet). Used only for
479
536
  * sequence number + auth nonce simulation; never persisted, never signed. */
480
- sourceAccount: z.string(),
537
+ sourceAccount: z
538
+ .string()
539
+ .regex(STELLAR_ACCOUNT_ADDRESS, 'sourceAccount must be a Stellar account address (G...)'),
481
540
  /** Target network for the install. Selects which interpreter pin and
482
541
  * which RPC URL are valid by default. Defaults to `testnet` so the
483
542
  * pre-mainnet callers keep working: they were always pointing at
@@ -507,21 +566,63 @@ export const InstallPolicyInputSchema = z
507
566
  * everything. Selecting `network: 'mainnet'` is NOT an opt-in -
508
567
  * the mainnet pin is its own deny-by-default anchor. */
509
568
  allowUnpinnedInterpreter: z.boolean().optional(),
569
+ /** Opt-in to installing when a signer of this rule can already reach the
570
+ * same calls through a context rule that has NO policy attached. OZ lets
571
+ * the signer choose which rule authorises a call and enforces only that
572
+ * rule's policies, so an unpoliced rule covering the same calls makes
573
+ * this policy decorative. Default-deny, because the caller almost
574
+ * certainly believes they are restricting something. */
575
+ allowAuthorityOverlap: z.boolean().optional(),
576
+ /** Skip the cross-rule authority scan entirely. The scan costs one RPC
577
+ * read per rule on the account; skipping it means the response carries
578
+ * no statement about what the signers can already do. */
579
+ skipAuthorityScan: z.boolean().optional(),
510
580
  /** Base fee in stroops; defaults to BASE_FEE (100). */
511
581
  baseFee: z.number().int().positive().optional(),
512
582
  })
513
583
  .refine((v) => Boolean(v.smartAccount) && Boolean(v.sourceAccount), {
514
584
  message: 'smartAccount and sourceAccount are required',
515
585
  });
586
+ /** `merge_policy` input.
587
+ *
588
+ * The tightening remedy for a cross-rule overlap: replace a rule's predicate
589
+ * with the conjunction of it and a new one. Two transactions, in order,
590
+ * because OZ refuses to re-attach a policy already on the rule - so the
591
+ * caller runs `detach`, waits for it to confirm, then runs `reinstall`. */
592
+ export const MergePolicyInputSchema = z
593
+ .object({
594
+ smartAccount: z
595
+ .string()
596
+ .regex(STELLAR_CONTRACT_ADDRESS, 'smartAccount must be a Stellar contract address (C...)'),
597
+ sourceAccount: z
598
+ .string()
599
+ .regex(STELLAR_ACCOUNT_ADDRESS, 'sourceAccount must be a Stellar account address (G...)'),
600
+ /** The rule whose predicate is being tightened. */
601
+ ruleId: z.number().int().nonnegative(),
602
+ /** The predicate to conjoin, base64 canonical ScVal, as emitted by
603
+ * `synthesize_policy`. */
604
+ incomingPredicateBlobBase64: z.string().min(1),
605
+ /** Which half of the remedy to build. */
606
+ step: z.enum(['detach', 'reinstall']),
607
+ network: NetworkSchema.optional(),
608
+ rpcUrl: z.string().url().optional(),
609
+ allowUnpinnedRpcUrl: z.boolean().optional(),
610
+ baseFee: z.number().int().positive().optional(),
611
+ })
612
+ .strict();
516
613
  export const RevokePolicyInputSchema = z
517
614
  .object({
518
615
  /** The smart account contract address (C...). */
519
- smartAccount: z.string(),
616
+ smartAccount: z
617
+ .string()
618
+ .regex(STELLAR_CONTRACT_ADDRESS, 'smartAccount must be a Stellar contract address (C...)'),
520
619
  /** The wallet that will sign the removal. The ACCOUNT decides whether it
521
620
  * accepts that signer; this schema does not assert a rule it cannot
522
621
  * verify, since the account's source is not in this repo. Proven on
523
622
  * testnet: the account's deployer can revoke. */
524
- sourceAccount: z.string(),
623
+ sourceAccount: z
624
+ .string()
625
+ .regex(STELLAR_ACCOUNT_ADDRESS, 'sourceAccount must be a Stellar account address (G...)'),
525
626
  /** Target network for the revoke. Same `testnet`-default as install,
526
627
  * so pre-mainnet callers keep working without an explicit flag. */
527
628
  network: NetworkSchema.optional(),
@@ -543,8 +644,15 @@ export const GetInterpreterInfoInputSchema = z.object({
543
644
  /** When true, perform an optional live `grammar_version()` RPC call to
544
645
  * verify the deployed contract matches the pin. */
545
646
  verifyLive: z.boolean().optional(),
546
- /** Optional RPC URL override. */
647
+ /** Optional RPC URL override. When `verifyLive` is true, the URL must
648
+ * equal the pinned RPC for the selected network unless
649
+ * `allowUnpinnedRpcUrl: true` is also set (same opt-in shape as
650
+ * install/revoke - the live grammar_version() answer binds to whichever
651
+ * RPC returned it). */
547
652
  rpcUrl: z.string().url().optional(),
653
+ /** Opt-in to using a non-pinned RPC URL when `verifyLive` is true. Same
654
+ * semantics as install/revoke: the caller accepts the trust shift. */
655
+ allowUnpinnedRpcUrl: z.boolean().optional(),
548
656
  });
549
657
  // ===== Error envelope (canonical) =====
550
658
  //
@@ -28,28 +28,23 @@ export interface ComposeUserResponses {
28
28
  * invocation_count bound; absent -> FREQUENCY_BOUND_MISSING. */
29
29
  invocationLimit?: number;
30
30
  /** Per-asset oracle-price bound(s). Each entry lowers to a single
31
- * `oracle_price(asset) OP value` compare in the interpreter IR. Multiple
32
- * entries on the same asset emit multiple leaves. */
31
+ * `oracle_price(asset) OP value` compare in the interpreter IR. */
33
32
  oraclePriceBound?: OraclePriceBound[];
34
33
  /** Minimum acceptable swap output per unit of input, as `num/den` (e.g.
35
- * `{num:'95',den:'100'}` = accept losing at most 5%). Emitted as a
36
- * slippage floor bounding the output arg against the input arg of the same
37
- * call.
38
- *
39
- * REQUIRED to be supplied by the caller: it is never derived from the
40
- * recording. The recorded in/out pair is a price at one moment, and
41
- * freezing it as policy would deny ordinary trades as soon as the rate
42
- * moves. Absent, no floor is emitted and the existing unbounded-output
43
- * warning stands. */
34
+ * `{num:'95',den:'100'}` = accept losing at most 5%). REQUIRED to be
35
+ * supplied by the caller: never derived from the recording (the recorded
36
+ * in/out pair is a price at one moment, and freezing it as policy would
37
+ * deny ordinary trades as soon as the rate moves). Absent, no floor is
38
+ * emitted and the existing unbounded-output warning stands. */
44
39
  swapMinOutRatio?: {
45
40
  num: string;
46
41
  den: string;
47
42
  };
48
43
  /** Recipient allowlist for a swap (call_arg[3] on SoroSwap's
49
- * swap_exact_tokens_for_tokens). When supplied, it REPLACES the default
50
- * pin. Absent -> the recipient is pinned to the recorded value (mirroring
51
- * SEP-41) and RECIPIENT_ALLOWLIST_EMPTY is surfaced as informational, never
52
- * a silent free pass. */
44
+ * swap_exact_tokens_for_tokens). When supplied, REPLACES the default pin.
45
+ * Absent -> recipient is pinned to the recorded value (mirroring SEP-41)
46
+ * and RECIPIENT_ALLOWLIST_EMPTY surfaces as informational, never a silent
47
+ * free pass. */
53
48
  swapRecipientAllowlist?: string[];
54
49
  }
55
50
  /** Composition options. */
@@ -1,52 +1,42 @@
1
- // src/synth/compose-from-recording.ts - facts + scope -> PolicyIR (OZ-shape + interpreter-shape).
2
- //
3
- // Composes the canonical IR rules the two backends compile FROM. Fail-closed
4
- // composition rules:
5
- //
6
- // - identify the protocol of the top-level call (registry.identifyProtocol).
7
- // When it is unknown (null), emit NO OZ-primitive-producing IR node: the
8
- // scope is kept (CallContract + method) and every inferred bound is surfaced
9
- // as a descriptive warning. An unrecognised call never compiles to a
10
- // permissive OZ primitive.
1
+ // src/synth/compose-from-recording.ts - facts + scope -> PolicyIR (OZ + interpreter).
11
2
  //
3
+ // Fail-closed composition rules:
4
+ // - unknown top-level protocol (registry.identifyProtocol returns null) ->
5
+ // emit no OZ-primitive-producing IR node; scope is kept (CallContract + method)
6
+ // and every inferred bound surfaces as a descriptive warning. An unrecognised
7
+ // call never compiles to a permissive OZ primitive.
12
8
  // - carry the recorded top-level function into `rule.scope.method` so the OZ
13
9
  // adapter flags per-method scoping as not covered (CallContract permits every
14
- // method on the contract; a per-method restriction needs the interpreter predicate).
15
- //
16
- // - a `spending_limit` (window_spent(token, w) <= limit) is emitted ONLY when
17
- // the caller supplies BOTH the limit (userResponses.limitAmount) and the
18
- // window (userResponses.windowSeconds). A single recorded spend does NOT
19
- // authorise that amount every window, so the observed amount is NEVER used as
20
- // an auto-ceiling: a missing limit surfaces AMOUNT_BOUND_MISSING (the observed
21
- // amount is offered as a suggestion), a missing window surfaces
22
- // DURATION_UNSPECIFIED. EVERY spent token is handled - none is silently
23
- // dropped; a single caller limit binds only an unambiguous single-token spend.
24
- //
25
- // - incoming-only flows (e.g. Blend yield claim) emit an `invocation_count`
26
- // bound ONLY when the caller supplies the count (userResponses.invocationLimit)
27
- // and a window; otherwise FREQUENCY_BOUND_MISSING is surfaced with no
28
- // fabricated count.
29
- //
30
- // - the IR carries ONLY constraints justified by the recording (observed
31
- // recipient allowlist) + explicit user input. Nothing invented: no oracle
32
- // price fabricated from a slippage bound, no synthetic exact-path compare.
33
- // Those needs are surfaced as descriptive warnings instead.
10
+ // method; a per-method restriction needs the interpreter predicate).
11
+ // - `spending_limit` (window_spent(token, w) <= limit) is emitted ONLY when
12
+ // the caller supplies BOTH limit (userResponses.limitAmount) AND window
13
+ // (userResponses.windowSeconds). A single recorded spend does NOT authorise
14
+ // that amount every window, so the observed amount is NEVER used as an
15
+ // auto-ceiling: missing limit -> AMOUNT_BOUND_MISSING (observed amount
16
+ // offered as a suggestion); missing window -> DURATION_UNSPECIFIED. EVERY
17
+ // spent token is handled - none is silently dropped.
18
+ // - incoming-only flows emit an `invocation_count` bound ONLY when the caller
19
+ // supplies both the count and the window; otherwise FREQUENCY_BOUND_MISSING
20
+ // with no fabricated count.
21
+ // - the IR carries ONLY constraints justified by the recording + explicit
22
+ // user input. Nothing invented: no oracle price fabricated from a slippage
23
+ // bound, no synthetic exact-path compare. Those needs surface as warnings.
34
24
  //
35
25
  // Split rule (P3 wiring): `ComposeResult` carries BOTH `ir` (OZ-shape) and
36
26
  // `interpreterIr` (predicate-shape). Each constraint is routed to EXACTLY ONE
37
27
  // adapter:
38
- // - `compare window_spent(token, w) <= limit` where `token === scope.contract`
39
- // and the protocol is known -> `ir` (OZ lowers to spending_limit).
40
- // - everything else the compose step emits (recipient allowlists, per-method
41
- // scoping via scope.method, invocation_count bounds, eq_seq swap paths,
42
- // oracle_price bounds, AND window_spent where token != scope.contract, i.e.
43
- // a SoroSwap input-token cap) -> `interpreterIr`.
28
+ // - `window_spent(token, w) <= limit` where `token === scope.contract` and
29
+ // protocol is known -> `ir` (OZ lowers to spending_limit).
30
+ // - everything else (recipient allowlists, per-method scope.method,
31
+ // invocation_count, eq_seq swap paths, oracle_price, AND window_spent
32
+ // where token != scope.contract i.e. SoroSwap input-token cap) ->
33
+ // `interpreterIr`.
44
34
  //
45
35
  // This prevents the interpreter adapter from emitting a duplicate
46
36
  // `window_spent` predicate leaf alongside an OZ `spending_limit` primitive
47
37
  // covering the same spend semantic - the two adapters never overlap.
48
38
  //
49
- // The default behavior is `deny_all` (OZ context rules are deny-by-default).
39
+ // Default policy is `deny_all` (OZ context rules are deny-by-default).
50
40
  import { identifyProtocol } from "../registry/identify.js";
51
41
  /** Compose a PolicyIR pair from the lowered facts + the resolved scope.
52
42
  * Pure (no randomness, no clock); same inputs -> byte-identical result. */
@@ -56,6 +46,15 @@ export function composeFromRecording(facts, scopeContract, topLevel, opts) {
56
46
  const warnings = [];
57
47
  const ozConstraints = [];
58
48
  const interpreterConstraints = [];
49
+ // Route to the matching IR. When the interpreter is enabled, constraints the
50
+ // OZ adapter cannot lower go there; otherwise they go to OZ (which flags them
51
+ // as uncovered) so today's warning-driven behaviour is preserved.
52
+ const routeToAdapter = (cond) => {
53
+ if (interpreterEnabled)
54
+ interpreterConstraints.push(cond);
55
+ else
56
+ ozConstraints.push(cond);
57
+ };
59
58
  const protocol = topLevel
60
59
  ? identifyProtocol(topLevel.contract, topLevel.fn, topLevel.args, opts.network)
61
60
  : null;
@@ -63,14 +62,15 @@ export function composeFromRecording(facts, scopeContract, topLevel, opts) {
63
62
  const windowSeconds = opts.userResponses?.windowSeconds;
64
63
  const limitAmount = opts.userResponses?.limitAmount;
65
64
  const spendTokens = Object.keys(facts.spendByToken);
66
- // Outgoing spend -> one spending_limit per spent token. A single caller limit
67
- // binds only an unambiguous single-token spend; a multi-token flow needs a
68
- // per-token limit, so each unmatched token surfaces AMOUNT_BOUND_MISSING.
65
+ // Outgoing spend -> one spending_limit per spent token. A single caller
66
+ // limit binds only an unambiguous single-token spend; a multi-token flow
67
+ // needs a per-token limit, so each unmatched token surfaces
68
+ // AMOUNT_BOUND_MISSING.
69
69
  //
70
70
  // Routing: a `window_spent(token, w) <= limit` constraint goes to the OZ IR
71
71
  // only when token === scope.contract (OZ's spending_limit binds the
72
72
  // CallContract target, not a token parameter). Otherwise it goes to the
73
- // interpreter IR (the interpreter lowers window_spent to a predicate leaf).
73
+ // interpreter IR.
74
74
  if (spendTokens.length > 0 && topLevel) {
75
75
  let durationFlagged = false;
76
76
  for (const token of spendTokens) {
@@ -96,24 +96,23 @@ export function composeFromRecording(facts, scopeContract, topLevel, opts) {
96
96
  });
97
97
  continue;
98
98
  }
99
- if (windowSeconds !== undefined && limit !== undefined) {
100
- const spendCond = {
99
+ if (windowSeconds !== undefined) {
100
+ // Rolling spend cap always goes to OZ (`spending_limit` is the audited
101
+ // implementation). The interpreter is NOT a fallback for token !=
102
+ // scopeContract: on chain it sees one authorized call, not the
103
+ // transaction's token movements, so it has no per-call amount to
104
+ // accumulate and the counter would never move. OZ reports the case it
105
+ // cannot cover (limit pins to the context contract) - the honest
106
+ // outcome; the old fallback produced an interpreter predicate that
107
+ // silently never bound.
108
+ ozConstraints.push({
101
109
  op: 'compare',
102
110
  compare: {
103
111
  selector: { kind: 'window_spent', token, windowSeconds },
104
112
  operator: 'lte',
105
113
  value: limit,
106
114
  },
107
- };
108
- // A rolling spend cap always goes to OZ, whose `spending_limit` is the
109
- // audited implementation. The interpreter is NOT a fallback for the
110
- // token != scopeContract case: on chain it sees one authorized call,
111
- // not the transaction's token movements, so it has no per-call amount
112
- // to accumulate and the counter would never move. OZ reports the case
113
- // it cannot cover (it pins the limit to the context contract), which
114
- // is the honest outcome - the old fallback produced an interpreter
115
- // predicate that silently never bound.
116
- ozConstraints.push(spendCond);
115
+ });
117
116
  if (interpreterEnabled && token !== scopeContract) {
118
117
  warnings.push(`rolling spend cap on ${token} cannot be enforced on chain: OZ spending_limit pins the limit to the context contract, and the interpreter cannot observe token movements. Bound the per-call value with an argument cap plus an invocation-count limit instead.`);
119
118
  }
@@ -125,18 +124,18 @@ export function composeFromRecording(facts, scopeContract, topLevel, opts) {
125
124
  // Routed to the interpreter IR when interpreter is enabled (OZ cannot lower
126
125
  // invocation_count); otherwise to the OZ IR (which flags it as uncovered).
127
126
  //
128
- // A recognised swap is NOT an incoming-only flow: it has an outgoing input leg
129
- // whose spend simply was not attributed to the source account (the
130
- // fee-sponsored / holder != source case). Its real restrictions - exact path,
131
- // recipient, and the input-amount cap - come from the protocol-specific pass,
132
- // so it does NOT get the incoming-only frequency prompt. A caller who wants to
127
+ // A recognised swap is NOT an incoming-only flow: it has an outgoing input
128
+ // leg whose spend simply was not attributed to the source account
129
+ // (fee-sponsored / holder != source). Its real restrictions - exact path,
130
+ // recipient, input-amount cap - come from the protocol-specific pass, so it
131
+ // does NOT get the incoming-only frequency prompt. A caller wanting to
133
132
  // rate-limit the swap can still supply an invocationLimit + window, which
134
133
  // lowers to an invocation_count for any flow.
135
134
  if (spendTokens.length === 0 && topLevel) {
136
135
  const invocationLimit = opts.userResponses?.invocationLimit;
137
136
  const isRecognisedSwap = protocol?.protocol === 'soroswap';
138
137
  if (known && windowSeconds !== undefined && invocationLimit !== undefined) {
139
- const icCond = {
138
+ routeToAdapter({
140
139
  op: 'compare',
141
140
  compare: {
142
141
  selector: { kind: 'invocation_count', windowSeconds },
@@ -146,13 +145,7 @@ export function composeFromRecording(facts, scopeContract, topLevel, opts) {
146
145
  operator: 'lt',
147
146
  value: String(invocationLimit),
148
147
  },
149
- };
150
- if (interpreterEnabled) {
151
- interpreterConstraints.push(icCond);
152
- }
153
- else {
154
- ozConstraints.push(icCond);
155
- }
148
+ });
156
149
  }
157
150
  else if (!isRecognisedSwap) {
158
151
  ambiguities.push({
@@ -168,7 +161,7 @@ export function composeFromRecording(facts, scopeContract, topLevel, opts) {
168
161
  const oracleBounds = opts.userResponses?.oraclePriceBound;
169
162
  if (oracleBounds) {
170
163
  for (const b of oracleBounds) {
171
- const oracleCond = {
164
+ routeToAdapter({
172
165
  op: 'compare',
173
166
  compare: {
174
167
  selector: { kind: 'oracle_price', asset: b.asset },
@@ -176,13 +169,7 @@ export function composeFromRecording(facts, scopeContract, topLevel, opts) {
176
169
  value: b.value,
177
170
  valueDecimals: b.decimals,
178
171
  },
179
- };
180
- if (interpreterEnabled) {
181
- interpreterConstraints.push(oracleCond);
182
- }
183
- else {
184
- ozConstraints.push(oracleCond);
185
- }
172
+ });
186
173
  }
187
174
  }
188
175
  // Observed recipient allowlist (SEP-41) is a real, recorded constraint the OZ
@@ -197,7 +184,7 @@ export function composeFromRecording(facts, scopeContract, topLevel, opts) {
197
184
  // the window_spent path above already consumed the limit, so the per-call
198
185
  // arg cap is skipped to avoid binding one limit to two different semantics.
199
186
  const swapInputAmountCap = spendTokens.length === 0 ? limitAmount : undefined;
200
- appendProtocolSpecificConstraints(ozConstraints, interpreterConstraints, warnings, ambiguities, facts, topLevel, protocol, opts.userResponses?.swapRecipientAllowlist, swapInputAmountCap, opts.userResponses?.swapMinOutRatio, interpreterEnabled);
187
+ appendProtocolSpecificConstraints(interpreterConstraints, routeToAdapter, warnings, ambiguities, facts, topLevel, protocol, opts.userResponses?.swapRecipientAllowlist, swapInputAmountCap, opts.userResponses?.swapMinOutRatio, interpreterEnabled);
201
188
  }
202
189
  // `scope.method` is carried on BOTH IRs so each adapter produces a
203
190
  // self-consistent rule. The interpreter adapter lowers scope.method into a
@@ -239,32 +226,24 @@ export function composeFromRecording(facts, scopeContract, topLevel, opts) {
239
226
  * SoroSwap's slippage / oracle / exact-path needs come from `userResponses`
240
227
  * (oraclePriceBound + limitAmount) + the recorded path (eq_seq on
241
228
  * call_arg[2]). */
242
- function appendProtocolSpecificConstraints(ozConstraints, interpreterConstraints, warnings, ambiguities, facts, topLevel, protocol, swapRecipientAllowlist, swapInputAmountCap, swapMinOutRatio, interpreterEnabled) {
243
- // SEP-41 transfer / mint: the `to` arg (index 1) is the recipient. Emit it as
244
- // a single-element allowlist; the interpreter adapter lowers it to `in`.
229
+ function appendProtocolSpecificConstraints(interpreterConstraints, routeToAdapter, warnings, ambiguities, facts, topLevel, protocol, swapRecipientAllowlist, swapInputAmountCap, swapMinOutRatio, interpreterEnabled) {
230
+ // SEP-41 transfer / mint: the `to` arg (index 1) is the recipient. Emit a
231
+ // single-element allowlist; the interpreter adapter lowers it to `in`.
245
232
  // When interpreter is not enabled, route to OZ so the caller sees today's
246
- // `value allowlist on arg 1 (arg allowlist)` warning.
233
+ // `value allowlist on arg 1` warning.
247
234
  if (protocol.protocol === 'sep41' && (protocol.fn === 'transfer' || protocol.fn === 'mint')) {
248
235
  const toArg = topLevel.args[1];
249
236
  if (toArg && toArg.type === 'address') {
250
- const cond = {
237
+ routeToAdapter({
251
238
  op: 'in',
252
239
  selector: { kind: 'arg', argIndex: 1, scalarType: 'address' },
253
240
  values: [toArg.value],
254
- };
255
- if (interpreterEnabled) {
256
- interpreterConstraints.push(cond);
257
- }
258
- else {
259
- ozConstraints.push(cond);
260
- }
241
+ });
261
242
  }
262
243
  }
263
244
  // Blend submit / claim: the `to` arg is the beneficiary - it receives the
264
245
  // resulting position shares on `submit` and the claimed tokens on `claim`.
265
- // That is the same role as the SEP-41 recipient above and the SoroSwap swap
266
- // recipient below, so it is pinned to the recorded address the same way:
267
- // without it a policy scoped to a pool and method still lets an agent send
246
+ // Without it, a policy scoped to a pool + method still lets an agent send
268
247
  // the proceeds anywhere. `from` and `spender` are deliberately NOT pinned -
269
248
  // the call already requires their authorisation, so binding them adds no
270
249
  // restriction the chain is not already enforcing.
@@ -273,25 +252,19 @@ function appendProtocolSpecificConstraints(ozConstraints, interpreterConstraints
273
252
  // claim(from, reserve_token_ids, to).
274
253
  const toArg = topLevel.args[2];
275
254
  if (toArg && toArg.type === 'address') {
276
- const cond = {
255
+ routeToAdapter({
277
256
  op: 'in',
278
257
  selector: { kind: 'arg', argIndex: 2, scalarType: 'address' },
279
258
  values: [toArg.value],
280
- };
281
- if (interpreterEnabled) {
282
- interpreterConstraints.push(cond);
283
- }
284
- else {
285
- ozConstraints.push(cond);
286
- }
259
+ });
287
260
  }
288
261
  }
289
262
  // Blend `submit` ONLY (not `claim`, whose vec arg is a vec<u32> of
290
263
  // reserve_token_ids - no map fields to bind). The `requests` vec
291
264
  // (call_arg[3]) is a vec<Request{ address, amount, request_type }>. Each
292
- // Request is the per-reserve action selector - 0 Supply, 1 Withdraw,
265
+ // Request is the per-reserve action selector (0 Supply, 1 Withdraw,
293
266
  // 2 SupplyCollateral, 3 WithdrawCollateral, 4 Borrow, 5 Repay, 6-9
294
- // liquidation/auction fills. Pinning only one element is unsafe: a caller
267
+ // liquidation/auction fills). Pinning only one element is unsafe: a caller
295
268
  // can append a second element with a different action (WithdrawCollateral
296
269
  // -> Borrow on a different asset, any amount, then auction fills). Length
297
270
  // + per-element pinning is total; a quantifier over elements is not. If we
@@ -432,20 +405,14 @@ function appendProtocolSpecificConstraints(ozConstraints, interpreterConstraints
432
405
  inputArgIndex !== undefined &&
433
406
  inputAmountArg &&
434
407
  inputAmountArg.type === 'i128') {
435
- const cond = {
408
+ routeToAdapter({
436
409
  op: 'compare',
437
410
  compare: {
438
411
  selector: { kind: 'arg', argIndex: inputArgIndex, scalarType: 'i128' },
439
412
  operator: 'lte',
440
413
  value: swapInputAmountCap,
441
414
  },
442
- };
443
- if (interpreterEnabled) {
444
- interpreterConstraints.push(cond);
445
- }
446
- else {
447
- ozConstraints.push(cond);
448
- }
415
+ });
449
416
  }
450
417
  // Slippage floor: `out >= in * num/den`. Only when the caller supplied the
451
418
  // ratio - see `swapMinOutRatio`. Without it the output arg stays free,
@@ -457,19 +424,13 @@ function appendProtocolSpecificConstraints(ozConstraints, interpreterConstraints
457
424
  outMinArgIndex !== undefined &&
458
425
  inputAmountArg &&
459
426
  inputAmountArg.type === 'i128') {
460
- const floor = {
427
+ routeToAdapter({
461
428
  op: 'slippage_floor',
462
429
  outArgIndex: outMinArgIndex,
463
430
  inArgIndex: inputArgIndex,
464
431
  num: minOutRatio.num,
465
432
  den: minOutRatio.den,
466
- };
467
- if (interpreterEnabled) {
468
- interpreterConstraints.push(floor);
469
- }
470
- else {
471
- ozConstraints.push(floor);
472
- }
433
+ });
473
434
  }
474
435
  // Swap recipient (call_arg[3]): when the caller supplies
475
436
  // swapRecipientAllowlist, emit it as an `in` constraint on the recipient
@@ -485,17 +446,11 @@ function appendProtocolSpecificConstraints(ozConstraints, interpreterConstraints
485
446
  // (today's behaviour, matching the other SoroSwap constraints).
486
447
  const recipientArg = topLevel.args[3];
487
448
  if (swapRecipientAllowlist && swapRecipientAllowlist.length > 0) {
488
- const cond = {
449
+ routeToAdapter({
489
450
  op: 'in',
490
451
  selector: { kind: 'arg', argIndex: 3, scalarType: 'address' },
491
452
  values: [...swapRecipientAllowlist],
492
- };
493
- if (interpreterEnabled) {
494
- interpreterConstraints.push(cond);
495
- }
496
- else {
497
- ozConstraints.push(cond);
498
- }
453
+ });
499
454
  }
500
455
  else if (interpreterEnabled && recipientArg && recipientArg.type === 'address') {
501
456
  interpreterConstraints.push({