@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
@@ -14,6 +14,7 @@
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
16
16
  // them here so it can build the same args envelope the MCP transport builds.
17
+ import { StrKey } from '@stellar/stellar-sdk';
17
18
  import { z } from 'zod';
18
19
  import { isStellarAddress } from "../synth/address.js";
19
20
  /** Soroban `valid_until` is a u32 ledger sequence; a value above this cannot be
@@ -134,9 +135,25 @@ export const InterpreterOptionsSchema = z.object({
134
135
  smartAccountAddress: z.string(),
135
136
  installNonce: z.number().int().positive().optional(),
136
137
  });
137
- export const SynthesizePolicyInputSchema = z.object({
138
+ export const SynthesizePolicyInputSchema = z
139
+ .object({
138
140
  source: z.literal('recording'),
139
- recordedTx: RecordedTransactionSchema,
141
+ // Two ways to name the recording, because an MCP client has no variable to
142
+ // pass by reference. `recordedTx` is the full RecordedTransaction, which a
143
+ // programmatic caller can hand straight over from `record_transaction`. An
144
+ // agent cannot: it sees that output as text and has to retype it, and the
145
+ // payload is thousands of characters and a dozen levels deep, with exact
146
+ // i128 strings that do not survive the round trip. `transactionHash` lets the
147
+ // agent carry a 64-character handle instead and have the server re-record.
148
+ //
149
+ // Re-recording rather than caching keeps the server stateless (see
150
+ // build-install-policy.ts). Recording is deterministic for a settled
151
+ // transaction, so the second read returns the same thing as the first.
152
+ recordedTx: RecordedTransactionSchema.optional(),
153
+ transactionHash: z
154
+ .string()
155
+ .regex(/^[0-9a-f]{64}$/, 'transaction hash must be 64 lowercase hex characters')
156
+ .optional(),
140
157
  network: NetworkSchema,
141
158
  userResponses: ComposeUserResponsesSchema.optional(),
142
159
  confidenceOverride: z.object({ threshold: z.number().min(0).max(1) }).optional(),
@@ -150,6 +167,9 @@ export const SynthesizePolicyInputSchema = z.object({
150
167
  // (encodedPredicate, predicateHash, etc.) are never altered by enabling
151
168
  // explain.
152
169
  explain: z.boolean().optional(),
170
+ })
171
+ .refine((v) => v.recordedTx !== undefined || v.transactionHash !== undefined, {
172
+ message: 'supply either `recordedTx` (the full recording) or `transactionHash` (and the server will record it)',
153
173
  });
154
174
  // ===== PredicateNode / PredicateLeaf =====
155
175
  //
@@ -242,10 +262,38 @@ export const PredicateNodeSchema = z.lazy(() => z.union([
242
262
  // take the same input. A null predicate used to mean "OZ built-in policies
243
263
  // only"; that backend is gone, so every policy carries a predicate and there is
244
264
  // nothing to simulate without one.
245
- export const SimulatePolicyInputSchema = z.object({
246
- predicate: PredicateNodeSchema,
247
- permitTx: RecordedTransactionSchema,
265
+ export const SimulatePolicyInputSchema = z
266
+ .object({
267
+ // Same two ways in as `synthesize_policy`, for the same reason. The tree
268
+ // is only returned under `explain`, so a caller who did not ask for it has
269
+ // nothing to pass here and skips the check entirely - which is the one
270
+ // step that must not be skippable by accident. `transactionHash` re-records and
271
+ // re-synthesizes, so the predicate checked is the predicate that was built.
272
+ predicate: PredicateNodeSchema.optional(),
273
+ /** The canonical encoding `declare_policy` and `synthesize_policy` both
274
+ * return. A DECLARED policy has no recording behind it, so re-synthesizing
275
+ * from a hash would check a different predicate than the one declared -
276
+ * and the tree is the shape callers mistype. One opaque string is the
277
+ * handle that path was missing. */
278
+ encodedPredicate: z.string().optional(),
279
+ permitTx: RecordedTransactionSchema.optional(),
280
+ transactionHash: z
281
+ .string()
282
+ .regex(/^[0-9a-f]{64}$/, 'transaction hash must be 64 lowercase hex characters')
283
+ .optional(),
284
+ network: NetworkSchema.optional(),
285
+ /** Needed only with `transactionHash`: lowering a recording to an interpreter
286
+ * predicate is scoped to the account it will be installed on, and the
287
+ * self-call gate is defined against it. */
288
+ smartAccount: z.string().optional(),
289
+ userResponses: ComposeUserResponsesSchema.optional(),
248
290
  validUntilLedger: z.number().int().positive().max(U32_MAX).optional(),
291
+ })
292
+ // Two halves, each satisfiable on its own terms: something to check, and a
293
+ // call to check it against. `transactionHash` alone answers both.
294
+ .refine((v) => v.transactionHash !== undefined ||
295
+ ((v.predicate !== undefined || v.encodedPredicate !== undefined) && v.permitTx !== undefined), {
296
+ message: 'supply `transactionHash` (and the server will record and synthesize), or a predicate (`predicate` tree or `encodedPredicate` string) together with `permitTx` or `transactionHash`',
249
297
  });
250
298
  export const VerifyPolicyInputSchema = SimulatePolicyInputSchema;
251
299
  // ===== install_policy / revoke_policy / get_interpreter_info =====
@@ -310,12 +358,25 @@ const ContextRuleDraftSchema = z
310
358
  }),
311
359
  ]))
312
360
  .max(MAX_SIGNERS_PER_RULE),
361
+ /** Policies on one rule compose as ALL-OF, so an interpreter predicate and
362
+ * an OpenZeppelin built-in can sit together and both must permit. That
363
+ * pairing is what expresses a rolling total: the predicate bounds each
364
+ * call, the built-in bounds the sum across calls. */
313
365
  policies: z
314
- .array(z.object({
315
- kind: z.literal('interpreter'),
316
- interpreterAddress: z.string(),
317
- predicateBlobBase64: z.string().min(1),
318
- }))
366
+ .array(z.discriminatedUnion('kind', [
367
+ z.object({
368
+ kind: z.literal('interpreter'),
369
+ interpreterAddress: z.string(),
370
+ predicateBlobBase64: z.string().min(1),
371
+ }),
372
+ z.object({
373
+ kind: z.literal('spending_limit'),
374
+ policyAddress: z.string(),
375
+ /** LEDGERS, not seconds. */
376
+ periodLedgers: z.number().int().positive().max(U32_MAX),
377
+ spendingLimit: z.string().regex(/^[0-9]+$/),
378
+ }),
379
+ ]))
319
380
  .max(MAX_POLICIES_PER_RULE),
320
381
  })
321
382
  .passthrough()
@@ -364,6 +425,10 @@ export const RPC_URL_BY_NETWORK = {
364
425
  testnet: TESTNET_RPC_URL,
365
426
  mainnet: MAINNET_RPC_URL,
366
427
  };
428
+ /** The upstream tag the deployed policy instances were built from. Exported so
429
+ * `scripts/upstream-drift-check.ts` can compare it against the latest upstream
430
+ * release; a tag recorded only in prose cannot be checked by anything. */
431
+ export const PINNED_OZ_STELLAR_CONTRACTS_TAG = 'v0.7.2';
367
432
  /** Instance addresses per network. Exported so consumers import the pin
368
433
  * instead of copying a literal - a copied address is how a testnet id ends up
369
434
  * being queried against mainnet, which returns `Error(Storage, MissingValue)`
@@ -407,6 +472,20 @@ export const NETWORK_PASSPHRASES = {
407
472
  // `sourceAccount` is the signing wallet (G...).
408
473
  const STELLAR_CONTRACT_ADDRESS = /^C[2-7A-Z]{55}$/;
409
474
  const STELLAR_ACCOUNT_ADDRESS = /^G[2-7A-Z]{55}$/;
475
+ // The regexes above check SHAPE only. A wrong-but-well-formed address - the
476
+ // classic case being one an agent reproduced from memory - passes them and then
477
+ // fails the SDK's StrKey decoder deep inside the build, where the throw is
478
+ // caught by the tool envelope and reported as a bare "invalid checksum" naming
479
+ // no field. A caller holding several addresses then cannot tell which one is
480
+ // wrong. Validating the checksum HERE keeps the field name attached.
481
+ const contractAddress = (field) => z
482
+ .string()
483
+ .regex(STELLAR_CONTRACT_ADDRESS, `${field} must be a Stellar contract address (C...)`)
484
+ .refine(StrKey.isValidContract, `${field} is not a valid contract address: the checksum does not match, so this address does not exist`);
485
+ const accountAddress = (field) => z
486
+ .string()
487
+ .regex(STELLAR_ACCOUNT_ADDRESS, `${field} must be a Stellar account address (G...)`)
488
+ .refine(StrKey.isValidEd25519PublicKey, `${field} is not a valid account address: the checksum does not match, so this address does not exist`);
410
489
  // ===== declare_policy =====
411
490
  //
412
491
  // The declarative front-end: the constraint stated outright, with no
@@ -468,14 +547,10 @@ export const InstallPolicyInputSchema = z
468
547
  * result says so rather than reporting "no overlaps found". */
469
548
  existingRules: z.array(ObservedRuleSchema).optional(),
470
549
  /** The smart account contract address (C...) that will receive the rule. */
471
- smartAccount: z
472
- .string()
473
- .regex(STELLAR_CONTRACT_ADDRESS, 'smartAccount must be a Stellar contract address (C...)'),
550
+ smartAccount: contractAddress('smartAccount'),
474
551
  /** The signer that authorises the install (G... wallet). Used only for
475
552
  * sequence number + auth nonce simulation; never persisted, never signed. */
476
- sourceAccount: z
477
- .string()
478
- .regex(STELLAR_ACCOUNT_ADDRESS, 'sourceAccount must be a Stellar account address (G...)'),
553
+ sourceAccount: accountAddress('sourceAccount'),
479
554
  /** Target network for the install. Selects which interpreter pin and
480
555
  * which RPC URL are valid by default. Defaults to `testnet` so the
481
556
  * pre-mainnet callers keep working: they were always pointing at
@@ -484,10 +559,70 @@ export const InstallPolicyInputSchema = z
484
559
  * A caller that targets mainnet MUST set this to `mainnet` (the
485
560
  * pin and RPC pin do not move by themselves). */
486
561
  network: NetworkSchema.optional(),
487
- /** The proposed rule draft. Mirrors the core `ContextRuleDraft` shape. */
488
- rule: ContextRuleDraftSchema,
489
- /** Per-rule install nonce; 1 for a fresh install. */
490
- installNonce: z.number().int().positive(),
562
+ /** The proposed rule draft. Mirrors the core `ContextRuleDraft` shape.
563
+ *
564
+ * Optional because of `fromHash` below. An agent cannot reliably retype the
565
+ * `contextRule` that `synthesize_policy` returned - it is nested, and the
566
+ * observed failures were exactly that: `validUntilLedger` sent as a string,
567
+ * `signers` as "", `policies` as an object instead of an array. Supplying
568
+ * `fromHash` instead lets the server rebuild the same rule it just
569
+ * produced, rather than asking the caller to transcribe it. */
570
+ rule: ContextRuleDraftSchema.optional(),
571
+ /** Build the rule here instead of receiving it: record this transaction,
572
+ * synthesize against `smartAccount`, and install the result. The
573
+ * agent-friendly counterpart to `rule`, and the same handle
574
+ * `synthesize_policy` accepts. */
575
+ fromHash: z
576
+ .object({
577
+ transactionHash: z
578
+ .string()
579
+ .regex(/^[0-9a-f]{64}$/, 'transaction hash must be 64 lowercase hex characters'),
580
+ /** The keys this rule governs. Synthesis cannot choose them: it reads a
581
+ * transaction, and which keys a rule binds is the caller's security
582
+ * decision, not an inference from one recording. Naming a key here
583
+ * attaches it as a delegated signer. A rule with no signer is refused
584
+ * on chain, so this is required in practice; the `rule` form remains
585
+ * the way to attach an external (verifier + key bytes) signer. */
586
+ signers: z
587
+ .array(z.string().refine(isStellarAddress, 'must be a Stellar address (G... or C...)'))
588
+ .max(MAX_SIGNERS_PER_RULE)
589
+ .optional(),
590
+ userResponses: ComposeUserResponsesSchema.optional(),
591
+ })
592
+ .optional(),
593
+ /** Install a predicate the caller ALREADY holds - the base64 string
594
+ * `declare_policy` returns.
595
+ *
596
+ * Without this there is no route from `declare_policy` to here:
597
+ * `fromHash` re-synthesizes from a recording and would discard the
598
+ * declared predicate, and `rule` means hand-building a draft that the
599
+ * tool boundary types as `unknown`, so the caller is guessing. An agent
600
+ * asked to do that invented a requirement to deploy a signer contract,
601
+ * which is not a thing - a delegated signer is a plain account address.
602
+ *
603
+ * The context rule type is taken FROM the predicate: if it pins a
604
+ * contract, the rule is scoped to that contract. One source of truth, so
605
+ * the rule's scope cannot drift from what the predicate actually checks. */
606
+ fromPredicate: z
607
+ .object({
608
+ encodedPredicate: z.string().min(1),
609
+ /** The keys this rule governs, as plain Stellar account addresses. */
610
+ signers: z
611
+ .array(z.string().refine(isStellarAddress, 'must be a Stellar address (G... or C...)'))
612
+ .min(1)
613
+ .max(MAX_SIGNERS_PER_RULE),
614
+ name: z.string().min(1).optional(),
615
+ validUntilLedger: z.number().int().positive().max(U32_MAX).optional(),
616
+ })
617
+ .optional(),
618
+ /** Per-rule install nonce. Defaults to 1, which is the only correct value
619
+ * here: this tool builds `add_context_rule`, the account assigns a NEW
620
+ * rule id, and the interpreter has no stored nonce for a rule that does
621
+ * not exist yet. Required, it was undiscoverable - an agent has no way to
622
+ * read it, and asking cost a round trip on a value the server already
623
+ * knows. Supply it only to re-install over an existing rule, where the
624
+ * interpreter wants `stored_nonce + 1`. */
625
+ installNonce: z.number().int().positive().optional(),
491
626
  /** Optional RPC URL override. Defaults to the pinned RPC for the
492
627
  * selected `network` (testnet by default, mainnet when
493
628
  * `network: 'mainnet'`); the override is refused unless
@@ -499,6 +634,38 @@ export const InstallPolicyInputSchema = z
499
634
  * network because the caller's auth-digest binds to whatever the
500
635
  * RPC returned. */
501
636
  allowUnpinnedRpcUrl: z.boolean().optional(),
637
+ /** Attach an OpenZeppelin `spending_limit` beside the predicate, giving the
638
+ * rule a ROLLING TOTAL as well as a per-call bound. Both must permit,
639
+ * because policies on one rule compose as all-of.
640
+ *
641
+ * This is the only way to express "N per day": the interpreter is handed
642
+ * one call and keeps no state, so a predicate cannot add up spending
643
+ * across calls. Composes with all three ways of naming the rule.
644
+ *
645
+ * The primitive meters the third argument of a call named exactly
646
+ * `transfer` and requires a `call_contract` rule scope, so the rule must
647
+ * be pinned to the token whose transfers it meters. */
648
+ spendingLimit: z
649
+ .object({
650
+ /** Rolling total in the token's smallest unit. */
651
+ amount: z
652
+ .string()
653
+ .regex(/^[0-9]+$/, 'amount must be a base-10 integer in the smallest unit'),
654
+ /** Window length in LEDGERS. Stellar closes one in roughly five
655
+ * seconds, so a period in seconds is an approximation of this. */
656
+ periodLedgers: z.number().int().positive().max(U32_MAX),
657
+ })
658
+ .optional(),
659
+ /** Opt-in to installing a rule that bounds no amount, when the recording
660
+ * behind `fromHash` showed a spend.
661
+ *
662
+ * Default-deny, because the failure is silent and reads as success: such
663
+ * a rule installs cleanly, verifies cleanly - a missing constraint
664
+ * generates no deny case to fail - and caps nothing. That combination
665
+ * reached the chain once already. A rule with no spend to bound is
666
+ * unaffected; only the case the synthesizer explicitly flagged is
667
+ * refused. */
668
+ allowUnboundedAmount: z.boolean().optional(),
502
669
  /** Opt-in to pointing the rule's interpreter policy at any address
503
670
  * other than the pinned interpreter for the selected network.
504
671
  * Default-deny: a caller that controls the interpreter can permit
@@ -507,6 +674,9 @@ export const InstallPolicyInputSchema = z
507
674
  allowUnpinnedInterpreter: z.boolean().optional(),
508
675
  /** Base fee in stroops; defaults to BASE_FEE (100). */
509
676
  baseFee: z.number().int().positive().optional(),
677
+ })
678
+ .refine((v) => v.rule !== undefined || v.fromHash !== undefined || v.fromPredicate !== undefined, {
679
+ 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)',
510
680
  })
511
681
  .refine((v) => Boolean(v.smartAccount) && Boolean(v.sourceAccount), {
512
682
  message: 'smartAccount and sourceAccount are required',
@@ -514,16 +684,12 @@ export const InstallPolicyInputSchema = z
514
684
  export const RevokePolicyInputSchema = z
515
685
  .object({
516
686
  /** The smart account contract address (C...). */
517
- smartAccount: z
518
- .string()
519
- .regex(STELLAR_CONTRACT_ADDRESS, 'smartAccount must be a Stellar contract address (C...)'),
687
+ smartAccount: contractAddress('smartAccount'),
520
688
  /** The wallet that will sign the removal. The ACCOUNT decides whether it
521
689
  * accepts that signer; this schema does not assert a rule it cannot
522
690
  * verify, since the account's source is not in this repo. Proven on
523
691
  * testnet: the account's deployer can revoke. */
524
- sourceAccount: z
525
- .string()
526
- .regex(STELLAR_ACCOUNT_ADDRESS, 'sourceAccount must be a Stellar account address (G...)'),
692
+ sourceAccount: accountAddress('sourceAccount'),
527
693
  /** Target network for the revoke. Same `testnet`-default as install,
528
694
  * so pre-mainnet callers keep working without an explicit flag. */
529
695
  network: 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;
@@ -9,12 +9,19 @@
9
9
  // invocations hit the same contract, and the per-contract hop-path lists for
10
10
  // router calls (SoroSwap `path`).
11
11
  /** Lower a recorded transaction to the canonical IntentFacts. Pure (no
12
- * randomness, no clock); same `RecordedTransaction` -> byte-identical facts. */
13
- export function lower(tx) {
12
+ * randomness, no clock); same `RecordedTransaction` -> byte-identical facts.
13
+ *
14
+ * `governedAccount` is the smart account the policy will be installed on, when
15
+ * one is known. It spends from itself while a wallet submits the transaction,
16
+ * so it counts as a spender alongside the source account. */
17
+ export function lower(tx, governedAccount) {
14
18
  const invocations = tx.invocations;
15
19
  const callTargets = uniqueOrdered(invocations.map((i) => i.contract));
16
20
  const functionsByContract = groupFunctionsByContract(invocations);
17
- const spendByToken = aggregateOutgoingSpend(tx.tokenMovements, tx.sourceAccount);
21
+ const spenders = governedAccount !== undefined && governedAccount !== tx.sourceAccount
22
+ ? [tx.sourceAccount, governedAccount]
23
+ : [tx.sourceAccount];
24
+ const spendByToken = aggregateOutgoingSpend(tx.tokenMovements, spenders);
18
25
  const allowedPaths = extractPathsByContract(invocations);
19
26
  const sharedRouter = inferSharedRouter(invocations);
20
27
  const facts = {
@@ -53,13 +60,19 @@ function groupFunctionsByContract(invocations) {
53
60
  }
54
61
  return out;
55
62
  }
56
- /** Sum outgoing TokenMovement amounts per token, where `from === source`.
57
- * BigInt throughout; never lossy. Movements whose `from` does not match the
58
- * recorded source account are NOT counted (incoming yield, refund, etc.). */
59
- function aggregateOutgoingSpend(movements, sourceAccount) {
63
+ /** Sum outgoing TokenMovement amounts per token, across every spender.
64
+ * BigInt throughout; never lossy. Movements whose `from` is none of the
65
+ * spenders are NOT counted (incoming yield, refund, etc.).
66
+ *
67
+ * A smart account spends from ITSELF while a wallet submits the transaction,
68
+ * so matching the source account alone missed the entire treasury case: the
69
+ * flow read as incoming-only, no amount bound was required, and a rule that
70
+ * capped nothing installed with every check green. The account a policy
71
+ * governs is a spender in its own right. */
72
+ function aggregateOutgoingSpend(movements, spenders) {
60
73
  const totals = new Map();
61
74
  for (const m of movements) {
62
- if (m.from !== sourceAccount)
75
+ if (!spenders.includes(m.from))
63
76
  continue;
64
77
  const current = totals.get(m.token) ?? 0n;
65
78
  totals.set(m.token, current + BigInt(m.amount));
@@ -122,7 +122,7 @@ function synthesizeFromRecordingInner(tx, opts) {
122
122
  },
123
123
  };
124
124
  }
125
- const facts = lower(tx);
125
+ const facts = lower(tx, opts.interpreter?.smartAccountAddress);
126
126
  const scopeRes = decideScope(facts, {
127
127
  network: opts.network,
128
128
  ...(opts.userResponses?.validUntilLedger !== undefined
package/dist/types.d.ts CHANGED
@@ -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
@@ -52,6 +52,7 @@ exports.ADD_CONTEXT_RULE_SYMBOL = exports.DEFAULT_GRAMMAR_VERSION = void 0;
52
52
  exports.buildAddContextRuleArgs = buildAddContextRuleArgs;
53
53
  const node_crypto_1 = require("node:crypto");
54
54
  const stellar_sdk_1 = require("@stellar/stellar-sdk");
55
+ const encode_ts_1 = require("../predicate/encode.js");
55
56
  const types_ts_1 = require("../types.js");
56
57
  exports.DEFAULT_GRAMMAR_VERSION = types_ts_1.GRAMMAR_VERSION;
57
58
  /** The verb `add_context_rule` takes on the wire. */
@@ -125,27 +126,58 @@ function encodeSigner(s) {
125
126
  function encodePoliciesMap(args) {
126
127
  const entries = [];
127
128
  for (const ref of args.policies) {
128
- // Refuse anything that is not an interpreter policy rather than skipping
129
- // it. This loop used to `if (kind === 'interpreter')` and drop everything
130
- // else in silence, so a caller attaching an OZ `spending_limit` beside the
131
- // interpreter got a rule WITHOUT the cap and no indication of it - the
132
- // policy the user asked for was simply absent from the install they signed.
133
- // `PolicyRef` has one shape today, so TypeScript narrows this branch to
134
- // `never`; the guard is for callers reaching the built JS untyped, and for
135
- // the next kind added to `PolicyRef` without a case here. Failing loudly is
136
- // the only safe direction: a dropped policy is a missing restriction.
137
- if (ref.kind !== 'interpreter') {
138
- const kind = JSON.stringify(ref.kind ?? null);
139
- throw limitError('INSTALL_BUILD_FAILED', `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.`);
129
+ // Each policy carries its OWN params. This loop once applied one set of
130
+ // install params to every entry, which is why nothing but the interpreter
131
+ // could be expressed; before that it dropped other kinds in silence, so a
132
+ // caller attaching a cap received a rule without it and no indication.
133
+ // Both directions were wrong. An unknown kind still fails loudly below - a
134
+ // dropped policy is a missing restriction.
135
+ switch (ref.kind) {
136
+ case 'interpreter':
137
+ entries.push(new stellar_sdk_1.xdr.ScMapEntry({
138
+ key: stellar_sdk_1.Address.fromString(ref.interpreterAddress).toScVal(),
139
+ val: encodePolicyInstallParams(args),
140
+ }));
141
+ break;
142
+ case 'spending_limit':
143
+ entries.push(new stellar_sdk_1.xdr.ScMapEntry({
144
+ key: stellar_sdk_1.Address.fromString(ref.policyAddress).toScVal(),
145
+ val: encodeSpendingLimitParams(ref),
146
+ }));
147
+ break;
148
+ default: {
149
+ const kind = JSON.stringify(ref.kind ?? null);
150
+ throw limitError('INSTALL_BUILD_FAILED', `policy kind ${kind} is not supported; dropping it here would install a rule missing the restriction you asked for`);
151
+ }
140
152
  }
141
- entries.push(new stellar_sdk_1.xdr.ScMapEntry({
142
- key: stellar_sdk_1.Address.fromString(ref.interpreterAddress).toScVal(),
143
- val: encodePolicyInstallParams(args),
144
- }));
145
153
  }
146
154
  entries.sort(sortByScValSymbolString);
147
155
  return stellar_sdk_1.xdr.ScVal.scvMap(entries);
148
156
  }
157
+ /** OpenZeppelin `spending_limit`'s install params: `{ period_ledgers: u32,
158
+ * spending_limit: i128 }`, emitted in symbol-string order. Validated here
159
+ * rather than left to the chain, because a rolling cap that fails at submit
160
+ * has already cost the caller a signature. */
161
+ function encodeSpendingLimitParams(ref) {
162
+ if (!Number.isInteger(ref.periodLedgers) || ref.periodLedgers <= 0) {
163
+ throw limitError('INSTALL_BUILD_FAILED', `spending_limit periodLedgers must be a positive integer - it counts LEDGERS, not seconds; got: ${ref.periodLedgers}`);
164
+ }
165
+ if (!/^[0-9]+$/.test(ref.spendingLimit) || BigInt(ref.spendingLimit) <= 0n) {
166
+ throw limitError('INSTALL_BUILD_FAILED', `spending_limit must be a positive integer in the token's smallest unit; got: ${ref.spendingLimit}`);
167
+ }
168
+ const entries = [
169
+ new stellar_sdk_1.xdr.ScMapEntry({
170
+ key: stellar_sdk_1.xdr.ScVal.scvSymbol('period_ledgers'),
171
+ val: stellar_sdk_1.xdr.ScVal.scvU32(ref.periodLedgers),
172
+ }),
173
+ new stellar_sdk_1.xdr.ScMapEntry({
174
+ key: stellar_sdk_1.xdr.ScVal.scvSymbol('spending_limit'),
175
+ val: (0, encode_ts_1.scvI128FromDecimal)(ref.spendingLimit),
176
+ }),
177
+ ];
178
+ entries.sort((a, b) => sortBySymbolString(a.key(), b.key()));
179
+ return stellar_sdk_1.xdr.ScVal.scvMap(entries);
180
+ }
149
181
  function encodePolicyInstallParams(args) {
150
182
  const predicate = Buffer.from(args.encodedPredicate, 'base64');
151
183
  const computedHash = (0, node_crypto_1.createHash)('sha256').update(predicate).digest('hex');
@@ -93,6 +93,13 @@ export interface InstallCallDescribes {
93
93
  installNonce: number;
94
94
  predicateHash: string;
95
95
  predicateSha256OfEmbeddedBytes: string;
96
+ } | {
97
+ /** An OpenZeppelin built-in bounding the SUM across calls, which the
98
+ * predicate cannot: the interpreter sees one call and keeps no state. */
99
+ kind: 'spending_limit';
100
+ address: string;
101
+ periodLedgers: number;
102
+ spendingLimit: string;
96
103
  }>;
97
104
  /** The install nonce, decoded from the interpreter policy's
98
105
  * `install_nonce` field. Echoed at the top level for reviewer convenience;
@@ -105,6 +112,21 @@ export interface InstallCallDescribes {
105
112
  export interface BuildInstallPolicyResult {
106
113
  /** Unsigned Soroban transaction envelope, base64 XDR. */
107
114
  unsignedXdr: string;
115
+ /** Length and SHA-256 of `unsignedXdr`, so a caller that has to move it can
116
+ * prove it arrived whole.
117
+ *
118
+ * This envelope runs to several thousand characters, and the only route
119
+ * from a tool result onto disk is the caller re-emitting it. A truncated
120
+ * copy is not obviously wrong - it fails later as
121
+ * "failed to decode XDR: xdr value invalid", which reads like a malformed
122
+ * transaction rather than a transport problem. Observed in practice: one of
123
+ * two envelopes written in the same session lost its tail and its base64
124
+ * length went from a multiple of four to `len % 4 == 3`.
125
+ *
126
+ * Check both before signing. They are cheap, and they turn a silent,
127
+ * fatal truncation into a retry. */
128
+ unsignedXdrLength: number;
129
+ unsignedXdrSha256: string;
108
130
  /** Smart account contract address (echo). */
109
131
  smartAccount: string;
110
132
  /** Source account (echo) - the address that must sign. */
@@ -161,6 +183,11 @@ export declare function buildRevokePolicyXdr(args: {
161
183
  }): Promise<BuildRevokePolicyResult>;
162
184
  export interface BuildRevokePolicyResult {
163
185
  unsignedXdr: string;
186
+ /** Same integrity pair as the install result, for the same reason: a revoke
187
+ * envelope also has to reach a signer intact, and a truncated copy fails as
188
+ * a malformed transaction rather than as a transport error. */
189
+ unsignedXdrLength: number;
190
+ unsignedXdrSha256: string;
164
191
  smartAccount: string;
165
192
  sourceAccount: string;
166
193
  call: {
@@ -172,3 +199,17 @@ export interface BuildRevokePolicyResult {
172
199
  authValidUntilLedger: number;
173
200
  rootInvocationXdr: string;
174
201
  }
202
+ /** The actionable half of a failed simulation, with the transport half left out.
203
+ *
204
+ * `sim.error` names both why the chain refused the call and which host was
205
+ * asked, and the second half must not reach a caller. So we return only
206
+ * Soroban's own `Error(Type, #Code)` forms: those are contract state, and they
207
+ * are what tells an operator whether the source account lacks authority, a
208
+ * nonce is stale, or a predicate refused. Without them "simulateTransaction
209
+ * failed" names nothing a caller can act on.
210
+ *
211
+ * Returns "" when the error carries no such form, so the caller keeps its short
212
+ * stable message rather than gaining an empty parenthesis. */
213
+ export declare function simulationReason(sim: {
214
+ error?: string;
215
+ }): string;