@crediolabs/policy-synth 1.0.0 → 1.1.1

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 (35) hide show
  1. package/dist/install/build-add-context-rule.js +48 -16
  2. package/dist/install/build-install-policy.d.ts +41 -0
  3. package/dist/install/build-install-policy.js +51 -5
  4. package/dist/predicate/encode.d.ts +12 -0
  5. package/dist/predicate/encode.js +5 -1
  6. package/dist/run/index.d.ts +14 -5
  7. package/dist/run/index.js +263 -14
  8. package/dist/run/schemas.d.ts +2279 -476
  9. package/dist/run/schemas.js +192 -26
  10. package/dist/synth/lower.d.ts +6 -2
  11. package/dist/synth/lower.js +21 -8
  12. package/dist/synth/synthesize-from-recording.js +1 -1
  13. package/dist/types.d.ts +18 -1
  14. package/dist-cjs/install/build-add-context-rule.js +48 -16
  15. package/dist-cjs/install/build-install-policy.d.ts +41 -0
  16. package/dist-cjs/install/build-install-policy.js +52 -5
  17. package/dist-cjs/predicate/encode.d.ts +12 -0
  18. package/dist-cjs/predicate/encode.js +5 -0
  19. package/dist-cjs/run/index.d.ts +14 -5
  20. package/dist-cjs/run/index.js +263 -13
  21. package/dist-cjs/run/schemas.d.ts +2279 -476
  22. package/dist-cjs/run/schemas.js +193 -27
  23. package/dist-cjs/synth/lower.d.ts +6 -2
  24. package/dist-cjs/synth/lower.js +21 -8
  25. package/dist-cjs/synth/synthesize-from-recording.js +1 -1
  26. package/dist-cjs/types.d.ts +18 -1
  27. package/package.json +1 -1
  28. package/src/install/build-add-context-rule.ts +65 -21
  29. package/src/install/build-install-policy.ts +100 -12
  30. package/src/predicate/encode.ts +5 -1
  31. package/src/run/index.ts +280 -23
  32. package/src/run/schemas.ts +229 -43
  33. package/src/synth/lower.ts +22 -8
  34. package/src/synth/synthesize-from-recording.ts +1 -1
  35. package/src/types.ts +25 -6
@@ -16,7 +16,8 @@
16
16
  // imports them here so its tool-shape bindings stay in step; the CLI imports
17
17
  // them here so it can build the same args envelope the MCP transport builds.
18
18
  Object.defineProperty(exports, "__esModule", { value: true });
19
- exports.ToolErrorSchema = exports.GetInterpreterInfoInputSchema = exports.RevokePolicyInputSchema = exports.InstallPolicyInputSchema = exports.DeclarePolicyInputSchema = exports.NETWORK_PASSPHRASES = exports.PINNED_OZ_POLICY_WASM_SHA256 = exports.PINNED_OZ_POLICY_ADDRESS_BY_NETWORK = exports.RPC_URL_BY_NETWORK = exports.PINNED_INTERPRETER_ADDRESS_BY_NETWORK = exports.MAINNET_RPC_URL = exports.TESTNET_RPC_URL = exports.PINNED_INTERPRETER_GRAMMAR_VERSION = exports.PINNED_INTERPRETER_WASM_SHA256 = exports.PINNED_INTERPRETER_MAINNET_ADDRESS = exports.PINNED_INTERPRETER_TESTNET_ADDRESS = exports.ObservedRuleSchema = exports.VerifyPolicyInputSchema = exports.SimulatePolicyInputSchema = exports.PredicateNodeSchema = exports.PredicateLeafSchema = exports.SynthesizePolicyInputSchema = exports.InterpreterOptionsSchema = exports.RecordTransactionInputSchema = exports.ComposeUserResponsesSchema = exports.RecordedTransactionSchema = exports.ParseConfidenceSchema = exports.OnChainEventSchema = exports.TokenMovementSchema = exports.ContractInvocationSchema = exports.ScValSchema = exports.NetworkSchema = void 0;
19
+ exports.ToolErrorSchema = exports.GetInterpreterInfoInputSchema = exports.RevokePolicyInputSchema = exports.InstallPolicyInputSchema = exports.DeclarePolicyInputSchema = exports.NETWORK_PASSPHRASES = exports.PINNED_OZ_POLICY_WASM_SHA256 = exports.PINNED_OZ_POLICY_ADDRESS_BY_NETWORK = exports.PINNED_OZ_STELLAR_CONTRACTS_TAG = exports.RPC_URL_BY_NETWORK = exports.PINNED_INTERPRETER_ADDRESS_BY_NETWORK = exports.MAINNET_RPC_URL = exports.TESTNET_RPC_URL = exports.PINNED_INTERPRETER_GRAMMAR_VERSION = exports.PINNED_INTERPRETER_WASM_SHA256 = exports.PINNED_INTERPRETER_MAINNET_ADDRESS = exports.PINNED_INTERPRETER_TESTNET_ADDRESS = exports.ObservedRuleSchema = exports.VerifyPolicyInputSchema = exports.SimulatePolicyInputSchema = exports.PredicateNodeSchema = exports.PredicateLeafSchema = exports.SynthesizePolicyInputSchema = exports.InterpreterOptionsSchema = exports.RecordTransactionInputSchema = exports.ComposeUserResponsesSchema = exports.RecordedTransactionSchema = exports.ParseConfidenceSchema = exports.OnChainEventSchema = exports.TokenMovementSchema = exports.ContractInvocationSchema = exports.ScValSchema = exports.NetworkSchema = void 0;
20
+ const stellar_sdk_1 = require("@stellar/stellar-sdk");
20
21
  const zod_1 = require("zod");
21
22
  const address_ts_1 = require("../synth/address.js");
22
23
  /** Soroban `valid_until` is a u32 ledger sequence; a value above this cannot be
@@ -137,9 +138,25 @@ exports.InterpreterOptionsSchema = zod_1.z.object({
137
138
  smartAccountAddress: zod_1.z.string(),
138
139
  installNonce: zod_1.z.number().int().positive().optional(),
139
140
  });
140
- exports.SynthesizePolicyInputSchema = zod_1.z.object({
141
+ exports.SynthesizePolicyInputSchema = zod_1.z
142
+ .object({
141
143
  source: zod_1.z.literal('recording'),
142
- recordedTx: exports.RecordedTransactionSchema,
144
+ // Two ways to name the recording, because an MCP client has no variable to
145
+ // pass by reference. `recordedTx` is the full RecordedTransaction, which a
146
+ // programmatic caller can hand straight over from `record_transaction`. An
147
+ // agent cannot: it sees that output as text and has to retype it, and the
148
+ // payload is thousands of characters and a dozen levels deep, with exact
149
+ // i128 strings that do not survive the round trip. `transactionHash` lets the
150
+ // agent carry a 64-character handle instead and have the server re-record.
151
+ //
152
+ // Re-recording rather than caching keeps the server stateless (see
153
+ // build-install-policy.ts). Recording is deterministic for a settled
154
+ // transaction, so the second read returns the same thing as the first.
155
+ recordedTx: exports.RecordedTransactionSchema.optional(),
156
+ transactionHash: zod_1.z
157
+ .string()
158
+ .regex(/^[0-9a-f]{64}$/, 'transaction hash must be 64 lowercase hex characters')
159
+ .optional(),
143
160
  network: exports.NetworkSchema,
144
161
  userResponses: exports.ComposeUserResponsesSchema.optional(),
145
162
  confidenceOverride: zod_1.z.object({ threshold: zod_1.z.number().min(0).max(1) }).optional(),
@@ -153,6 +170,9 @@ exports.SynthesizePolicyInputSchema = zod_1.z.object({
153
170
  // (encodedPredicate, predicateHash, etc.) are never altered by enabling
154
171
  // explain.
155
172
  explain: zod_1.z.boolean().optional(),
173
+ })
174
+ .refine((v) => v.recordedTx !== undefined || v.transactionHash !== undefined, {
175
+ message: 'supply either `recordedTx` (the full recording) or `transactionHash` (and the server will record it)',
156
176
  });
157
177
  // ===== PredicateNode / PredicateLeaf =====
158
178
  //
@@ -245,10 +265,38 @@ exports.PredicateNodeSchema = zod_1.z.lazy(() => zod_1.z.union([
245
265
  // take the same input. A null predicate used to mean "OZ built-in policies
246
266
  // only"; that backend is gone, so every policy carries a predicate and there is
247
267
  // nothing to simulate without one.
248
- exports.SimulatePolicyInputSchema = zod_1.z.object({
249
- predicate: exports.PredicateNodeSchema,
250
- permitTx: exports.RecordedTransactionSchema,
268
+ exports.SimulatePolicyInputSchema = zod_1.z
269
+ .object({
270
+ // Same two ways in as `synthesize_policy`, for the same reason. The tree
271
+ // is only returned under `explain`, so a caller who did not ask for it has
272
+ // nothing to pass here and skips the check entirely - which is the one
273
+ // step that must not be skippable by accident. `transactionHash` re-records and
274
+ // re-synthesizes, so the predicate checked is the predicate that was built.
275
+ predicate: exports.PredicateNodeSchema.optional(),
276
+ /** The canonical encoding `declare_policy` and `synthesize_policy` both
277
+ * return. A DECLARED policy has no recording behind it, so re-synthesizing
278
+ * from a hash would check a different predicate than the one declared -
279
+ * and the tree is the shape callers mistype. One opaque string is the
280
+ * handle that path was missing. */
281
+ encodedPredicate: zod_1.z.string().optional(),
282
+ permitTx: exports.RecordedTransactionSchema.optional(),
283
+ transactionHash: zod_1.z
284
+ .string()
285
+ .regex(/^[0-9a-f]{64}$/, 'transaction hash must be 64 lowercase hex characters')
286
+ .optional(),
287
+ network: exports.NetworkSchema.optional(),
288
+ /** Needed only with `transactionHash`: lowering a recording to an interpreter
289
+ * predicate is scoped to the account it will be installed on, and the
290
+ * self-call gate is defined against it. */
291
+ smartAccount: zod_1.z.string().optional(),
292
+ userResponses: exports.ComposeUserResponsesSchema.optional(),
251
293
  validUntilLedger: zod_1.z.number().int().positive().max(U32_MAX).optional(),
294
+ })
295
+ // Two halves, each satisfiable on its own terms: something to check, and a
296
+ // call to check it against. `transactionHash` alone answers both.
297
+ .refine((v) => v.transactionHash !== undefined ||
298
+ ((v.predicate !== undefined || v.encodedPredicate !== undefined) && v.permitTx !== undefined), {
299
+ message: 'supply `transactionHash` (and the server will record and synthesize), or a predicate (`predicate` tree or `encodedPredicate` string) together with `permitTx` or `transactionHash`',
252
300
  });
253
301
  exports.VerifyPolicyInputSchema = exports.SimulatePolicyInputSchema;
254
302
  // ===== install_policy / revoke_policy / get_interpreter_info =====
@@ -313,12 +361,25 @@ const ContextRuleDraftSchema = zod_1.z
313
361
  }),
314
362
  ]))
315
363
  .max(MAX_SIGNERS_PER_RULE),
364
+ /** Policies on one rule compose as ALL-OF, so an interpreter predicate and
365
+ * an OpenZeppelin built-in can sit together and both must permit. That
366
+ * pairing is what expresses a rolling total: the predicate bounds each
367
+ * call, the built-in bounds the sum across calls. */
316
368
  policies: zod_1.z
317
- .array(zod_1.z.object({
318
- kind: zod_1.z.literal('interpreter'),
319
- interpreterAddress: zod_1.z.string(),
320
- predicateBlobBase64: zod_1.z.string().min(1),
321
- }))
369
+ .array(zod_1.z.discriminatedUnion('kind', [
370
+ zod_1.z.object({
371
+ kind: zod_1.z.literal('interpreter'),
372
+ interpreterAddress: zod_1.z.string(),
373
+ predicateBlobBase64: zod_1.z.string().min(1),
374
+ }),
375
+ zod_1.z.object({
376
+ kind: zod_1.z.literal('spending_limit'),
377
+ policyAddress: zod_1.z.string(),
378
+ /** LEDGERS, not seconds. */
379
+ periodLedgers: zod_1.z.number().int().positive().max(U32_MAX),
380
+ spendingLimit: zod_1.z.string().regex(/^[0-9]+$/),
381
+ }),
382
+ ]))
322
383
  .max(MAX_POLICIES_PER_RULE),
323
384
  })
324
385
  .passthrough()
@@ -367,6 +428,10 @@ exports.RPC_URL_BY_NETWORK = {
367
428
  testnet: exports.TESTNET_RPC_URL,
368
429
  mainnet: exports.MAINNET_RPC_URL,
369
430
  };
431
+ /** The upstream tag the deployed policy instances were built from. Exported so
432
+ * `scripts/upstream-drift-check.ts` can compare it against the latest upstream
433
+ * release; a tag recorded only in prose cannot be checked by anything. */
434
+ exports.PINNED_OZ_STELLAR_CONTRACTS_TAG = 'v0.7.2';
370
435
  /** Instance addresses per network. Exported so consumers import the pin
371
436
  * instead of copying a literal - a copied address is how a testnet id ends up
372
437
  * being queried against mainnet, which returns `Error(Storage, MissingValue)`
@@ -410,6 +475,20 @@ exports.NETWORK_PASSPHRASES = {
410
475
  // `sourceAccount` is the signing wallet (G...).
411
476
  const STELLAR_CONTRACT_ADDRESS = /^C[2-7A-Z]{55}$/;
412
477
  const STELLAR_ACCOUNT_ADDRESS = /^G[2-7A-Z]{55}$/;
478
+ // The regexes above check SHAPE only. A wrong-but-well-formed address - the
479
+ // classic case being one an agent reproduced from memory - passes them and then
480
+ // fails the SDK's StrKey decoder deep inside the build, where the throw is
481
+ // caught by the tool envelope and reported as a bare "invalid checksum" naming
482
+ // no field. A caller holding several addresses then cannot tell which one is
483
+ // wrong. Validating the checksum HERE keeps the field name attached.
484
+ const contractAddress = (field) => zod_1.z
485
+ .string()
486
+ .regex(STELLAR_CONTRACT_ADDRESS, `${field} must be a Stellar contract address (C...)`)
487
+ .refine(stellar_sdk_1.StrKey.isValidContract, `${field} is not a valid contract address: the checksum does not match, so this address does not exist`);
488
+ const accountAddress = (field) => zod_1.z
489
+ .string()
490
+ .regex(STELLAR_ACCOUNT_ADDRESS, `${field} must be a Stellar account address (G...)`)
491
+ .refine(stellar_sdk_1.StrKey.isValidEd25519PublicKey, `${field} is not a valid account address: the checksum does not match, so this address does not exist`);
413
492
  // ===== declare_policy =====
414
493
  //
415
494
  // The declarative front-end: the constraint stated outright, with no
@@ -471,14 +550,10 @@ exports.InstallPolicyInputSchema = zod_1.z
471
550
  * result says so rather than reporting "no overlaps found". */
472
551
  existingRules: zod_1.z.array(exports.ObservedRuleSchema).optional(),
473
552
  /** The smart account contract address (C...) that will receive the rule. */
474
- smartAccount: zod_1.z
475
- .string()
476
- .regex(STELLAR_CONTRACT_ADDRESS, 'smartAccount must be a Stellar contract address (C...)'),
553
+ smartAccount: contractAddress('smartAccount'),
477
554
  /** The signer that authorises the install (G... wallet). Used only for
478
555
  * sequence number + auth nonce simulation; never persisted, never signed. */
479
- sourceAccount: zod_1.z
480
- .string()
481
- .regex(STELLAR_ACCOUNT_ADDRESS, 'sourceAccount must be a Stellar account address (G...)'),
556
+ sourceAccount: accountAddress('sourceAccount'),
482
557
  /** Target network for the install. Selects which interpreter pin and
483
558
  * which RPC URL are valid by default. Defaults to `testnet` so the
484
559
  * pre-mainnet callers keep working: they were always pointing at
@@ -487,10 +562,70 @@ exports.InstallPolicyInputSchema = zod_1.z
487
562
  * A caller that targets mainnet MUST set this to `mainnet` (the
488
563
  * pin and RPC pin do not move by themselves). */
489
564
  network: exports.NetworkSchema.optional(),
490
- /** The proposed rule draft. Mirrors the core `ContextRuleDraft` shape. */
491
- rule: ContextRuleDraftSchema,
492
- /** Per-rule install nonce; 1 for a fresh install. */
493
- installNonce: zod_1.z.number().int().positive(),
565
+ /** The proposed rule draft. Mirrors the core `ContextRuleDraft` shape.
566
+ *
567
+ * Optional because of `fromHash` below. An agent cannot reliably retype the
568
+ * `contextRule` that `synthesize_policy` returned - it is nested, and the
569
+ * observed failures were exactly that: `validUntilLedger` sent as a string,
570
+ * `signers` as "", `policies` as an object instead of an array. Supplying
571
+ * `fromHash` instead lets the server rebuild the same rule it just
572
+ * produced, rather than asking the caller to transcribe it. */
573
+ rule: ContextRuleDraftSchema.optional(),
574
+ /** Build the rule here instead of receiving it: record this transaction,
575
+ * synthesize against `smartAccount`, and install the result. The
576
+ * agent-friendly counterpart to `rule`, and the same handle
577
+ * `synthesize_policy` accepts. */
578
+ fromHash: zod_1.z
579
+ .object({
580
+ transactionHash: zod_1.z
581
+ .string()
582
+ .regex(/^[0-9a-f]{64}$/, 'transaction hash must be 64 lowercase hex characters'),
583
+ /** The keys this rule governs. Synthesis cannot choose them: it reads a
584
+ * transaction, and which keys a rule binds is the caller's security
585
+ * decision, not an inference from one recording. Naming a key here
586
+ * attaches it as a delegated signer. A rule with no signer is refused
587
+ * on chain, so this is required in practice; the `rule` form remains
588
+ * the way to attach an external (verifier + key bytes) signer. */
589
+ signers: zod_1.z
590
+ .array(zod_1.z.string().refine(address_ts_1.isStellarAddress, 'must be a Stellar address (G... or C...)'))
591
+ .max(MAX_SIGNERS_PER_RULE)
592
+ .optional(),
593
+ userResponses: exports.ComposeUserResponsesSchema.optional(),
594
+ })
595
+ .optional(),
596
+ /** Install a predicate the caller ALREADY holds - the base64 string
597
+ * `declare_policy` returns.
598
+ *
599
+ * Without this there is no route from `declare_policy` to here:
600
+ * `fromHash` re-synthesizes from a recording and would discard the
601
+ * declared predicate, and `rule` means hand-building a draft that the
602
+ * tool boundary types as `unknown`, so the caller is guessing. An agent
603
+ * asked to do that invented a requirement to deploy a signer contract,
604
+ * which is not a thing - a delegated signer is a plain account address.
605
+ *
606
+ * The context rule type is taken FROM the predicate: if it pins a
607
+ * contract, the rule is scoped to that contract. One source of truth, so
608
+ * the rule's scope cannot drift from what the predicate actually checks. */
609
+ fromPredicate: zod_1.z
610
+ .object({
611
+ encodedPredicate: zod_1.z.string().min(1),
612
+ /** The keys this rule governs, as plain Stellar account addresses. */
613
+ signers: zod_1.z
614
+ .array(zod_1.z.string().refine(address_ts_1.isStellarAddress, 'must be a Stellar address (G... or C...)'))
615
+ .min(1)
616
+ .max(MAX_SIGNERS_PER_RULE),
617
+ name: zod_1.z.string().min(1).optional(),
618
+ validUntilLedger: zod_1.z.number().int().positive().max(U32_MAX).optional(),
619
+ })
620
+ .optional(),
621
+ /** Per-rule install nonce. Defaults to 1, which is the only correct value
622
+ * here: this tool builds `add_context_rule`, the account assigns a NEW
623
+ * rule id, and the interpreter has no stored nonce for a rule that does
624
+ * not exist yet. Required, it was undiscoverable - an agent has no way to
625
+ * read it, and asking cost a round trip on a value the server already
626
+ * knows. Supply it only to re-install over an existing rule, where the
627
+ * interpreter wants `stored_nonce + 1`. */
628
+ installNonce: zod_1.z.number().int().positive().optional(),
494
629
  /** Optional RPC URL override. Defaults to the pinned RPC for the
495
630
  * selected `network` (testnet by default, mainnet when
496
631
  * `network: 'mainnet'`); the override is refused unless
@@ -502,6 +637,38 @@ exports.InstallPolicyInputSchema = zod_1.z
502
637
  * network because the caller's auth-digest binds to whatever the
503
638
  * RPC returned. */
504
639
  allowUnpinnedRpcUrl: zod_1.z.boolean().optional(),
640
+ /** Attach an OpenZeppelin `spending_limit` beside the predicate, giving the
641
+ * rule a ROLLING TOTAL as well as a per-call bound. Both must permit,
642
+ * because policies on one rule compose as all-of.
643
+ *
644
+ * This is the only way to express "N per day": the interpreter is handed
645
+ * one call and keeps no state, so a predicate cannot add up spending
646
+ * across calls. Composes with all three ways of naming the rule.
647
+ *
648
+ * The primitive meters the third argument of a call named exactly
649
+ * `transfer` and requires a `call_contract` rule scope, so the rule must
650
+ * be pinned to the token whose transfers it meters. */
651
+ spendingLimit: zod_1.z
652
+ .object({
653
+ /** Rolling total in the token's smallest unit. */
654
+ amount: zod_1.z
655
+ .string()
656
+ .regex(/^[0-9]+$/, 'amount must be a base-10 integer in the smallest unit'),
657
+ /** Window length in LEDGERS. Stellar closes one in roughly five
658
+ * seconds, so a period in seconds is an approximation of this. */
659
+ periodLedgers: zod_1.z.number().int().positive().max(U32_MAX),
660
+ })
661
+ .optional(),
662
+ /** Opt-in to installing a rule that bounds no amount, when the recording
663
+ * behind `fromHash` showed a spend.
664
+ *
665
+ * Default-deny, because the failure is silent and reads as success: such
666
+ * a rule installs cleanly, verifies cleanly - a missing constraint
667
+ * generates no deny case to fail - and caps nothing. That combination
668
+ * reached the chain once already. A rule with no spend to bound is
669
+ * unaffected; only the case the synthesizer explicitly flagged is
670
+ * refused. */
671
+ allowUnboundedAmount: zod_1.z.boolean().optional(),
505
672
  /** Opt-in to pointing the rule's interpreter policy at any address
506
673
  * other than the pinned interpreter for the selected network.
507
674
  * Default-deny: a caller that controls the interpreter can permit
@@ -510,6 +677,9 @@ exports.InstallPolicyInputSchema = zod_1.z
510
677
  allowUnpinnedInterpreter: zod_1.z.boolean().optional(),
511
678
  /** Base fee in stroops; defaults to BASE_FEE (100). */
512
679
  baseFee: zod_1.z.number().int().positive().optional(),
680
+ })
681
+ .refine((v) => v.rule !== undefined || v.fromHash !== undefined || v.fromPredicate !== undefined, {
682
+ message: 'name the rule one of three ways: `fromHash` (server records, synthesizes and installs), `fromPredicate` (a predicate you already hold, plus the keys it governs), or `rule` (the full ContextRuleDraft, for programmatic callers)',
513
683
  })
514
684
  .refine((v) => Boolean(v.smartAccount) && Boolean(v.sourceAccount), {
515
685
  message: 'smartAccount and sourceAccount are required',
@@ -517,16 +687,12 @@ exports.InstallPolicyInputSchema = zod_1.z
517
687
  exports.RevokePolicyInputSchema = zod_1.z
518
688
  .object({
519
689
  /** The smart account contract address (C...). */
520
- smartAccount: zod_1.z
521
- .string()
522
- .regex(STELLAR_CONTRACT_ADDRESS, 'smartAccount must be a Stellar contract address (C...)'),
690
+ smartAccount: contractAddress('smartAccount'),
523
691
  /** The wallet that will sign the removal. The ACCOUNT decides whether it
524
692
  * accepts that signer; this schema does not assert a rule it cannot
525
693
  * verify, since the account's source is not in this repo. Proven on
526
694
  * testnet: the account's deployer can revoke. */
527
- sourceAccount: zod_1.z
528
- .string()
529
- .regex(STELLAR_ACCOUNT_ADDRESS, 'sourceAccount must be a Stellar account address (G...)'),
695
+ sourceAccount: accountAddress('sourceAccount'),
530
696
  /** Target network for the revoke. Same `testnet`-default as install,
531
697
  * so pre-mainnet callers keep working without an explicit flag. */
532
698
  network: exports.NetworkSchema.optional(),
@@ -19,5 +19,9 @@ export interface IntentFacts {
19
19
  allowedPaths?: Record<string, string[][]>;
20
20
  }
21
21
  /** Lower a recorded transaction to the canonical IntentFacts. Pure (no
22
- * randomness, no clock); same `RecordedTransaction` -> byte-identical facts. */
23
- export declare function lower(tx: RecordedTransaction): IntentFacts;
22
+ * randomness, no clock); same `RecordedTransaction` -> byte-identical facts.
23
+ *
24
+ * `governedAccount` is the smart account the policy will be installed on, when
25
+ * one is known. It spends from itself while a wallet submits the transaction,
26
+ * so it counts as a spender alongside the source account. */
27
+ export declare function lower(tx: RecordedTransaction, governedAccount?: string): IntentFacts;
@@ -12,12 +12,19 @@
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.lower = lower;
14
14
  /** Lower a recorded transaction to the canonical IntentFacts. Pure (no
15
- * randomness, no clock); same `RecordedTransaction` -> byte-identical facts. */
16
- function lower(tx) {
15
+ * randomness, no clock); same `RecordedTransaction` -> byte-identical facts.
16
+ *
17
+ * `governedAccount` is the smart account the policy will be installed on, when
18
+ * one is known. It spends from itself while a wallet submits the transaction,
19
+ * so it counts as a spender alongside the source account. */
20
+ function lower(tx, governedAccount) {
17
21
  const invocations = tx.invocations;
18
22
  const callTargets = uniqueOrdered(invocations.map((i) => i.contract));
19
23
  const functionsByContract = groupFunctionsByContract(invocations);
20
- const spendByToken = aggregateOutgoingSpend(tx.tokenMovements, tx.sourceAccount);
24
+ const spenders = governedAccount !== undefined && governedAccount !== tx.sourceAccount
25
+ ? [tx.sourceAccount, governedAccount]
26
+ : [tx.sourceAccount];
27
+ const spendByToken = aggregateOutgoingSpend(tx.tokenMovements, spenders);
21
28
  const allowedPaths = extractPathsByContract(invocations);
22
29
  const sharedRouter = inferSharedRouter(invocations);
23
30
  const facts = {
@@ -56,13 +63,19 @@ function groupFunctionsByContract(invocations) {
56
63
  }
57
64
  return out;
58
65
  }
59
- /** Sum outgoing TokenMovement amounts per token, where `from === source`.
60
- * BigInt throughout; never lossy. Movements whose `from` does not match the
61
- * recorded source account are NOT counted (incoming yield, refund, etc.). */
62
- function aggregateOutgoingSpend(movements, sourceAccount) {
66
+ /** Sum outgoing TokenMovement amounts per token, across every spender.
67
+ * BigInt throughout; never lossy. Movements whose `from` is none of the
68
+ * spenders are NOT counted (incoming yield, refund, etc.).
69
+ *
70
+ * A smart account spends from ITSELF while a wallet submits the transaction,
71
+ * so matching the source account alone missed the entire treasury case: the
72
+ * flow read as incoming-only, no amount bound was required, and a rule that
73
+ * capped nothing installed with every check green. The account a policy
74
+ * governs is a spender in its own right. */
75
+ function aggregateOutgoingSpend(movements, spenders) {
63
76
  const totals = new Map();
64
77
  for (const m of movements) {
65
- if (m.from !== sourceAccount)
78
+ if (!spenders.includes(m.from))
66
79
  continue;
67
80
  const current = totals.get(m.token) ?? 0n;
68
81
  totals.set(m.token, current + BigInt(m.amount));
@@ -126,7 +126,7 @@ function synthesizeFromRecordingInner(tx, opts) {
126
126
  },
127
127
  };
128
128
  }
129
- const facts = (0, lower_ts_1.lower)(tx);
129
+ const facts = (0, lower_ts_1.lower)(tx, opts.interpreter?.smartAccountAddress);
130
130
  const scopeRes = (0, scope_ts_1.decideScope)(facts, {
131
131
  network: opts.network,
132
132
  ...(opts.userResponses?.validUntilLedger !== undefined
@@ -114,11 +114,28 @@ export type SignerDraft = {
114
114
  verifier: string;
115
115
  keyBytes: string;
116
116
  };
117
- /** Reference to one policy attached to a context rule. */
117
+ /** Reference to one policy attached to a context rule.
118
+ *
119
+ * Policies on one rule compose as ALL-OF, so a rule may carry our interpreter
120
+ * AND an OpenZeppelin built-in, and both must permit. That is what expresses a
121
+ * rolling total: the interpreter bounds each call, the built-in bounds the sum
122
+ * across calls - state the interpreter deliberately does not keep. */
118
123
  export type PolicyRef = {
119
124
  kind: 'interpreter';
120
125
  interpreterAddress: string;
121
126
  predicateBlobBase64: string;
127
+ } | {
128
+ /** OpenZeppelin's `spending_limit`: a rolling total over a window of
129
+ * ledgers. It meters the third argument of a call named exactly
130
+ * `transfer` and refuses any rule scope other than `CallContract`. */
131
+ kind: 'spending_limit';
132
+ policyAddress: string;
133
+ /** Window length in LEDGERS, not seconds. Stellar closes a ledger in
134
+ * roughly five seconds, so a period given in seconds is an
135
+ * approximation of this number and should be reported as one. */
136
+ periodLedgers: number;
137
+ /** i128 as a base-10 string, in the token's smallest unit. */
138
+ spendingLimit: string;
122
139
  };
123
140
  /** Grammar version baked into the interpreter wasm, mirroring `SELF_VERSION` in
124
141
  * `contracts/policy-interpreter/src/version.rs`. Every value this package puts on
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@crediolabs/policy-synth",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "license": "MIT",
5
5
  "description": "Off-chain TypeScript synthesis core for the OZ Accounts Policy Builder. Records Soroban transactions, synthesises the minimal policy that permits exactly that flow, verifies it, and returns an unsigned install transaction.",
6
6
  "type": "module",
@@ -50,6 +50,7 @@
50
50
  import { createHash } from 'node:crypto'
51
51
  import { Address, xdr } from '@stellar/stellar-sdk'
52
52
  import type { ToolError } from '../errors.ts'
53
+ import { scvI128FromDecimal } from '../predicate/encode.ts'
53
54
  import {
54
55
  type ContextRuleDraft,
55
56
  GRAMMAR_VERSION,
@@ -194,33 +195,76 @@ function encodeSigner(s: SignerDraft): xdr.ScVal {
194
195
  function encodePoliciesMap(args: BuildAddContextRuleArgs): xdr.ScVal {
195
196
  const entries: xdr.ScMapEntry[] = []
196
197
  for (const ref of args.policies) {
197
- // Refuse anything that is not an interpreter policy rather than skipping
198
- // it. This loop used to `if (kind === 'interpreter')` and drop everything
199
- // else in silence, so a caller attaching an OZ `spending_limit` beside the
200
- // interpreter got a rule WITHOUT the cap and no indication of it - the
201
- // policy the user asked for was simply absent from the install they signed.
202
- // `PolicyRef` has one shape today, so TypeScript narrows this branch to
203
- // `never`; the guard is for callers reaching the built JS untyped, and for
204
- // the next kind added to `PolicyRef` without a case here. Failing loudly is
205
- // the only safe direction: a dropped policy is a missing restriction.
206
- if (ref.kind !== 'interpreter') {
207
- const kind = JSON.stringify((ref as { kind?: unknown }).kind ?? null)
208
- throw limitError(
209
- 'INSTALL_BUILD_FAILED',
210
- `policy kind ${kind} is not supported; this builder attaches interpreter policies only. Attach an OpenZeppelin built-in through the account layer instead - dropping it here would install a rule missing the restriction you asked for.`
211
- )
198
+ // Each policy carries its OWN params. This loop once applied one set of
199
+ // install params to every entry, which is why nothing but the interpreter
200
+ // could be expressed; before that it dropped other kinds in silence, so a
201
+ // caller attaching a cap received a rule without it and no indication.
202
+ // Both directions were wrong. An unknown kind still fails loudly below - a
203
+ // dropped policy is a missing restriction.
204
+ switch (ref.kind) {
205
+ case 'interpreter':
206
+ entries.push(
207
+ new xdr.ScMapEntry({
208
+ key: Address.fromString(ref.interpreterAddress).toScVal(),
209
+ val: encodePolicyInstallParams(args),
210
+ })
211
+ )
212
+ break
213
+ case 'spending_limit':
214
+ entries.push(
215
+ new xdr.ScMapEntry({
216
+ key: Address.fromString(ref.policyAddress).toScVal(),
217
+ val: encodeSpendingLimitParams(ref),
218
+ })
219
+ )
220
+ break
221
+ default: {
222
+ const kind = JSON.stringify((ref as { kind?: unknown }).kind ?? null)
223
+ throw limitError(
224
+ 'INSTALL_BUILD_FAILED',
225
+ `policy kind ${kind} is not supported; dropping it here would install a rule missing the restriction you asked for`
226
+ )
227
+ }
212
228
  }
213
- entries.push(
214
- new xdr.ScMapEntry({
215
- key: Address.fromString(ref.interpreterAddress).toScVal(),
216
- val: encodePolicyInstallParams(args),
217
- })
218
- )
219
229
  }
220
230
  entries.sort(sortByScValSymbolString)
221
231
  return xdr.ScVal.scvMap(entries)
222
232
  }
223
233
 
234
+ /** OpenZeppelin `spending_limit`'s install params: `{ period_ledgers: u32,
235
+ * spending_limit: i128 }`, emitted in symbol-string order. Validated here
236
+ * rather than left to the chain, because a rolling cap that fails at submit
237
+ * has already cost the caller a signature. */
238
+ function encodeSpendingLimitParams(ref: {
239
+ periodLedgers: number
240
+ spendingLimit: string
241
+ }): xdr.ScVal {
242
+ if (!Number.isInteger(ref.periodLedgers) || ref.periodLedgers <= 0) {
243
+ throw limitError(
244
+ 'INSTALL_BUILD_FAILED',
245
+ `spending_limit periodLedgers must be a positive integer - it counts LEDGERS, not seconds; got: ${ref.periodLedgers}`
246
+ )
247
+ }
248
+ if (!/^[0-9]+$/.test(ref.spendingLimit) || BigInt(ref.spendingLimit) <= 0n) {
249
+ throw limitError(
250
+ 'INSTALL_BUILD_FAILED',
251
+ `spending_limit must be a positive integer in the token's smallest unit; got: ${ref.spendingLimit}`
252
+ )
253
+ }
254
+ const entries = [
255
+ new xdr.ScMapEntry({
256
+ key: xdr.ScVal.scvSymbol('period_ledgers'),
257
+ val: xdr.ScVal.scvU32(ref.periodLedgers),
258
+ }),
259
+ new xdr.ScMapEntry({
260
+ key: xdr.ScVal.scvSymbol('spending_limit'),
261
+ val: scvI128FromDecimal(ref.spendingLimit),
262
+ }),
263
+ ]
264
+ entries.sort((a, b) => sortBySymbolString(a.key(), b.key()))
265
+ return xdr.ScVal.scvMap(entries)
266
+ }
267
+
224
268
  function encodePolicyInstallParams(args: BuildAddContextRuleArgs): xdr.ScVal {
225
269
  const predicate = Buffer.from(args.encodedPredicate, 'base64')
226
270
  const computedHash = createHash('sha256').update(predicate).digest('hex')