@crediolabs/policy-synth 0.1.17 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/README.md +44 -246
  2. package/dist/adapters/interpreter/adapter.d.ts +6 -7
  3. package/dist/adapters/interpreter/adapter.js +28 -48
  4. package/dist/adapters/oz/adapter.js +12 -13
  5. package/dist/codegen/compile-gate.js +5 -0
  6. package/dist/codegen/template.js +17 -0
  7. package/dist/install/authority-overlap.d.ts +134 -0
  8. package/dist/install/authority-overlap.js +0 -0
  9. package/dist/install/build-add-context-rule.d.ts +8 -0
  10. package/dist/install/build-add-context-rule.js +17 -46
  11. package/dist/install/build-install-policy.d.ts +12 -5
  12. package/dist/install/build-install-policy.js +32 -23
  13. package/dist/install/build-merge-policy.d.ts +70 -0
  14. package/dist/install/build-merge-policy.js +130 -0
  15. package/dist/install/get-interpreter-info.js +2 -2
  16. package/dist/install/index.d.ts +3 -1
  17. package/dist/install/index.js +8 -1
  18. package/dist/install/oz-auth.js +5 -3
  19. package/dist/install/plan-merge-policy.d.ts +49 -0
  20. package/dist/install/plan-merge-policy.js +86 -0
  21. package/dist/install/read-account-rules.d.ts +100 -0
  22. package/dist/install/read-account-rules.js +283 -0
  23. package/dist/predicate/decode.js +1 -1
  24. package/dist/predicate/encode.js +171 -10
  25. package/dist/record/decode.js +5 -6
  26. package/dist/registry/protocols.d.ts +1 -1
  27. package/dist/registry/protocols.js +1 -1
  28. package/dist/review-card/builder.d.ts +6 -0
  29. package/dist/review-card/builder.js +9 -1
  30. package/dist/run/index.d.ts +104 -18
  31. package/dist/run/index.js +359 -75
  32. package/dist/run/schemas.d.ts +479 -18
  33. package/dist/run/schemas.js +132 -24
  34. package/dist/synth/compose-from-recording.d.ts +10 -15
  35. package/dist/synth/compose-from-recording.js +79 -124
  36. package/dist/synth/deny-cases.d.ts +5 -0
  37. package/dist/synth/deny-cases.js +52 -13
  38. package/dist/synth/evaluate.js +69 -119
  39. package/dist/synth/harness.d.ts +13 -1
  40. package/dist/synth/harness.js +22 -1
  41. package/dist/synth/index.d.ts +1 -1
  42. package/dist/synth/synthesize-from-recording.d.ts +31 -21
  43. package/dist/synth/synthesize-from-recording.js +129 -155
  44. package/dist-cjs/adapters/interpreter/adapter.d.ts +6 -7
  45. package/dist-cjs/adapters/interpreter/adapter.js +28 -48
  46. package/dist-cjs/adapters/oz/adapter.js +12 -13
  47. package/dist-cjs/codegen/compile-gate.js +5 -0
  48. package/dist-cjs/codegen/template.js +17 -0
  49. package/dist-cjs/install/authority-overlap.d.ts +134 -0
  50. package/dist-cjs/install/authority-overlap.js +0 -0
  51. package/dist-cjs/install/build-add-context-rule.d.ts +8 -0
  52. package/dist-cjs/install/build-add-context-rule.js +17 -45
  53. package/dist-cjs/install/build-install-policy.d.ts +12 -5
  54. package/dist-cjs/install/build-install-policy.js +32 -23
  55. package/dist-cjs/install/build-merge-policy.d.ts +70 -0
  56. package/dist-cjs/install/build-merge-policy.js +134 -0
  57. package/dist-cjs/install/get-interpreter-info.js +2 -2
  58. package/dist-cjs/install/index.d.ts +3 -1
  59. package/dist-cjs/install/index.js +24 -3
  60. package/dist-cjs/install/oz-auth.js +5 -3
  61. package/dist-cjs/install/plan-merge-policy.d.ts +49 -0
  62. package/dist-cjs/install/plan-merge-policy.js +90 -0
  63. package/dist-cjs/install/read-account-rules.d.ts +100 -0
  64. package/dist-cjs/install/read-account-rules.js +296 -0
  65. package/dist-cjs/predicate/decode.js +1 -1
  66. package/dist-cjs/predicate/encode.js +171 -10
  67. package/dist-cjs/record/decode.js +5 -6
  68. package/dist-cjs/registry/protocols.d.ts +1 -1
  69. package/dist-cjs/registry/protocols.js +1 -1
  70. package/dist-cjs/review-card/builder.d.ts +6 -0
  71. package/dist-cjs/review-card/builder.js +9 -1
  72. package/dist-cjs/run/index.d.ts +104 -18
  73. package/dist-cjs/run/index.js +360 -74
  74. package/dist-cjs/run/schemas.d.ts +479 -18
  75. package/dist-cjs/run/schemas.js +133 -25
  76. package/dist-cjs/synth/compose-from-recording.d.ts +10 -15
  77. package/dist-cjs/synth/compose-from-recording.js +79 -124
  78. package/dist-cjs/synth/deny-cases.d.ts +5 -0
  79. package/dist-cjs/synth/deny-cases.js +52 -13
  80. package/dist-cjs/synth/evaluate.js +69 -119
  81. package/dist-cjs/synth/harness.d.ts +13 -1
  82. package/dist-cjs/synth/harness.js +22 -1
  83. package/dist-cjs/synth/index.d.ts +1 -1
  84. package/dist-cjs/synth/synthesize-from-recording.d.ts +31 -21
  85. package/dist-cjs/synth/synthesize-from-recording.js +129 -153
  86. package/package.json +1 -1
  87. package/src/adapters/interpreter/adapter.ts +28 -48
  88. package/src/adapters/oz/adapter.ts +12 -13
  89. package/src/codegen/compile-gate.ts +5 -0
  90. package/src/codegen/template.ts +17 -0
  91. package/src/install/authority-overlap.ts +0 -0
  92. package/src/install/build-add-context-rule.ts +29 -56
  93. package/src/install/build-install-policy.ts +41 -23
  94. package/src/install/build-merge-policy.ts +219 -0
  95. package/src/install/get-interpreter-info.ts +2 -2
  96. package/src/install/index.ts +36 -2
  97. package/src/install/oz-auth.ts +5 -3
  98. package/src/install/plan-merge-policy.ts +133 -0
  99. package/src/install/read-account-rules.ts +376 -0
  100. package/src/predicate/decode.ts +1 -1
  101. package/src/predicate/encode.ts +176 -10
  102. package/src/record/decode.ts +5 -6
  103. package/src/registry/protocols.ts +1 -1
  104. package/src/review-card/builder.ts +17 -1
  105. package/src/run/index.ts +500 -102
  106. package/src/run/schemas.ts +145 -24
  107. package/src/synth/compose-from-recording.ts +87 -132
  108. package/src/synth/deny-cases.ts +59 -13
  109. package/src/synth/evaluate.ts +70 -118
  110. package/src/synth/harness.ts +29 -1
  111. package/src/synth/index.ts +1 -0
  112. package/src/synth/synthesize-from-recording.ts +209 -192
  113. package/src/contracts/policy-template/OZ_POLICY_TRAIT.md +0 -196
@@ -0,0 +1,49 @@
1
+ import type { PredicateNode } from '../types.ts';
2
+ import type { ObservedRule } from './authority-overlap.ts';
3
+ export type MergeStep = 'detach' | 'reinstall';
4
+ export interface MergePlanRefused {
5
+ ok: false;
6
+ /** Why the merge cannot proceed, in terms the caller can act on. */
7
+ reason: string;
8
+ }
9
+ export interface MergePlanAccepted {
10
+ ok: true;
11
+ /** The conjunction to install in step 2. */
12
+ predicate: PredicateNode;
13
+ /** OZ registry id of the interpreter policy on this rule, for
14
+ * `remove_policy`. */
15
+ policyId: number;
16
+ /** Oracle bounds to re-install with the merged predicate. Carried from the
17
+ * document being replaced: they are tighten-only overrides against the wasm
18
+ * defaults, so omitting them would quietly widen the policy while the
19
+ * operator believed they were tightening it. */
20
+ oracleParams?: {
21
+ maxStalenessSeconds?: number;
22
+ maxDeviationBps?: number;
23
+ maxCrossFeedDeviationBps?: number;
24
+ };
25
+ /** Consequences the caller must see BEFORE signing step 1, because step 1 is
26
+ * the destructive one. */
27
+ warnings: string[];
28
+ /** What the caller should do after the requested step confirms. */
29
+ followUp: string;
30
+ }
31
+ export type MergePlan = MergePlanRefused | MergePlanAccepted;
32
+ /** The interpreter's registry id on a rule, or null when it is not attached
33
+ * or the ids were not readable. */
34
+ export declare function interpreterPolicyId(rule: ObservedRule, interpreterAddress: string): number | null;
35
+ /**
36
+ * Decide whether the merge can proceed, and say what it will cost.
37
+ *
38
+ * Refuses rather than guesses whenever the account is not in the shape the
39
+ * remedy assumes: the rule must be policed by our interpreter, its predicate
40
+ * must have been readable, and the ids needed to detach it must be present. A
41
+ * merge built on a predicate we could not read would silently replace a rule
42
+ * with something narrower or wider than its author wrote.
43
+ */
44
+ export declare function planMergePolicy(args: {
45
+ rule: ObservedRule;
46
+ interpreterAddress: string;
47
+ incoming: PredicateNode;
48
+ step: MergeStep;
49
+ }): MergePlan;
@@ -0,0 +1,86 @@
1
+ //! Planning the merge remedy for a cross-rule authority overlap.
2
+ //!
3
+ //! When two rules our interpreter polices can serve the same calls, the
4
+ //! tightening remedy is to replace one rule's predicate with the conjunction
5
+ //! of both (see `authority-overlap.ts`). Carrying that out against an OZ smart
6
+ //! account is not one call, and the reasons are worth stating because they
7
+ //! shape the whole tool:
8
+ //!
9
+ //! 1. A Soroban transaction carries exactly ONE operation - "smart contract
10
+ //! transactions can only have one operation per transaction" - so the
11
+ //! detach and the re-attach cannot be bundled even though the host would
12
+ //! run them in order happily. And `add_policy` panics `DuplicatePolicy`
13
+ //! while the policy is still attached (`smart_account/storage.rs`
14
+ //! `add_policy`), so the second transaction cannot even be simulated
15
+ //! until the first has confirmed.
16
+ //! 2. `remove_policy` calls `try_uninstall` and DISCARDS the result
17
+ //! (`smart_account/storage.rs`: `let _ = ...try_uninstall(...)`), so the
18
+ //! policy is detached whether or not our `uninstall` succeeded. When it
19
+ //! succeeded the document, nonce, signer hash, master set and counters
20
+ //! are gone and the re-install is a fresh install at nonce 1. When it
21
+ //! panicked - our `uninstall` panics `MissingState` if the master set has
22
+ //! been archived - the nonce SURVIVES, and re-installing at 1 would be
23
+ //! refused on chain as a replay, leaving the rule stuck unpoliced. The
24
+ //! nonce is therefore READ at reinstall time rather than assumed.
25
+ //! 3. Because of (2), any rate-limit or spend window on that rule is reset
26
+ //! by the merge. A signer who had consumed most of a window gets a clean
27
+ //! one. That is a real cost of tightening this way and the caller has to
28
+ //! be told, not discover it.
29
+ //! 4. So the caller performs step 1, waits for it to confirm, then asks for
30
+ //! step 2.
31
+ //!
32
+ //! This module is pure. It decides what should happen and why; the XDR is
33
+ //! built by `build-merge-policy.ts`.
34
+ import { mergeIntoAnd } from "./authority-overlap.js";
35
+ /** The interpreter's registry id on a rule, or null when it is not attached
36
+ * or the ids were not readable. */
37
+ export function interpreterPolicyId(rule, interpreterAddress) {
38
+ const index = rule.policyAddresses.indexOf(interpreterAddress);
39
+ if (index < 0)
40
+ return null;
41
+ const id = rule.policyIds?.[index];
42
+ return typeof id === 'number' ? id : null;
43
+ }
44
+ /**
45
+ * Decide whether the merge can proceed, and say what it will cost.
46
+ *
47
+ * Refuses rather than guesses whenever the account is not in the shape the
48
+ * remedy assumes: the rule must be policed by our interpreter, its predicate
49
+ * must have been readable, and the ids needed to detach it must be present. A
50
+ * merge built on a predicate we could not read would silently replace a rule
51
+ * with something narrower or wider than its author wrote.
52
+ */
53
+ export function planMergePolicy(args) {
54
+ const policyId = interpreterPolicyId(args.rule, args.interpreterAddress);
55
+ if (policyId === null) {
56
+ return {
57
+ ok: false,
58
+ reason: `rule ${args.rule.id} is not policed by the interpreter at ${args.interpreterAddress}, or its policy ids could not be read, so there is nothing to merge into and no id to detach. The merge hard-pins to that interpreter and has no opt-out: the auth digest it builds binds to the audited deployment. A rule installed against a different interpreter has to be replaced rather than merged.`,
59
+ };
60
+ }
61
+ const existing = args.rule.predicate;
62
+ if (!existing) {
63
+ return {
64
+ ok: false,
65
+ reason: `the predicate installed on rule ${args.rule.id} could not be read, so it cannot be conjoined; merging against an unknown predicate would replace the rule with something other than what its author wrote`,
66
+ };
67
+ }
68
+ const merged = mergeIntoAnd(existing, args.incoming);
69
+ if (!merged.ok || !merged.predicate) {
70
+ return { ok: false, reason: merged.reason ?? 'the two predicates cannot be conjoined' };
71
+ }
72
+ const warnings = [
73
+ `detaching the policy uninstalls it, which removes every counter on rule ${args.rule.id}: any rate limit or spend window there restarts from zero after the merge`,
74
+ 'the rule is unpoliced between the two transactions, so a signer of it is unconstrained by this policy until step 2 confirms',
75
+ ];
76
+ return {
77
+ ok: true,
78
+ predicate: merged.predicate,
79
+ policyId,
80
+ ...(args.rule.oracleBounds ? { oracleParams: args.rule.oracleBounds } : {}),
81
+ warnings,
82
+ followUp: args.step === 'detach'
83
+ ? "sign and submit this transaction, wait for it to confirm, then call again with step: 'reinstall' to install the merged predicate"
84
+ : 'sign and submit this transaction; the merged predicate is then the only policy governing this rule',
85
+ };
86
+ }
@@ -0,0 +1,100 @@
1
+ import { rpc, xdr } from '@stellar/stellar-sdk';
2
+ import type { SignerDraft } from '../types.ts';
3
+ import type { ContextType, ObservedRule } from './authority-overlap.ts';
4
+ /** `storage.rs:295` - the third element of the persistent doc key tuple. */
5
+ export declare const K_DOC = 1;
6
+ /** Persistent-storage key for a rule's stored document:
7
+ * `(account, rule_id, K_DOC)`, per `storage.rs:4`. */
8
+ export declare function docKeyScVal(smartAccount: string, ruleId: number): xdr.ScVal;
9
+ /** Ledger key for the interpreter's persistent entry holding that document. */
10
+ export declare function docLedgerKey(interpreter: string, smartAccount: string, ruleId: number): xdr.LedgerKey;
11
+ /** OZ `ContextRuleType`. An unrecognised tag is reported as `default`, which
12
+ * is the widest reading and therefore the safe one: it makes the rule look
13
+ * like it could serve any call, so overlap is over-reported, never missed. */
14
+ export declare function decodeContextType(v: xdr.ScVal | undefined): ContextType;
15
+ /** OZ `Signer::Delegated(Address) | Signer::External(Address, Bytes)`. */
16
+ export declare function decodeSigner(v: xdr.ScVal): SignerDraft | undefined;
17
+ /** A full OZ `ContextRule` as returned by `get_context_rule(id)`.
18
+ * `predicate` is filled in separately from the ledger entry. */
19
+ export declare function decodeContextRule(v: xdr.ScVal): ObservedRule | undefined;
20
+ /** `storage.rs:296` - the third element of the persistent nonce key tuple. */
21
+ export declare const K_NONCE = 2;
22
+ /** Ledger key for a rule's stored install nonce. Read directly for the same
23
+ * reason as the document: the interpreter publishes no getter. */
24
+ export declare function nonceLedgerKey(interpreter: string, smartAccount: string, ruleId: number): xdr.LedgerKey;
25
+ /** Per-policy oracle bounds carried on a `StoredDoc`.
26
+ *
27
+ * These must survive a merge. They are tighten-only overrides against the
28
+ * wasm defaults, so dropping them does not fail loudly: the rule keeps
29
+ * working and silently tolerates staler prices and wider deviation than its
30
+ * author chose. */
31
+ export interface StoredOracleBounds {
32
+ maxStalenessSeconds?: number;
33
+ maxDeviationBps?: number;
34
+ maxCrossFeedDeviationBps?: number;
35
+ }
36
+ export declare function decodeStoredOracleBounds(v: xdr.ScVal): StoredOracleBounds;
37
+ /** Raw predicate bytes out of a `StoredDoc` ledger entry value. */
38
+ export declare function decodeStoredPredicateBytes(v: xdr.ScVal): Buffer | undefined;
39
+ /** The three reads the scan needs. Kept as an interface so the collection
40
+ * below is testable without a network, matching the `InstallRpcClient`
41
+ * pattern in `build-install-policy.ts`. */
42
+ export interface AccountRuleReader {
43
+ /** OZ `get_context_rules_count()`. */
44
+ getContextRuleCount(smartAccount: string): Promise<number>;
45
+ /** OZ `get_context_rule(id)`. Undefined when the id is absent. */
46
+ getContextRule(smartAccount: string, ruleId: number): Promise<xdr.ScVal | undefined>;
47
+ /** The interpreter's persistent `StoredDoc` entry, read as a ledger entry.
48
+ * Undefined when no document is stored for that rule. */
49
+ getStoredDoc(interpreter: string, smartAccount: string, ruleId: number): Promise<xdr.ScVal | undefined>;
50
+ }
51
+ /** How far the id scan will probe before giving up. OZ imposes no per-account
52
+ * rule cap, so there is no exact bound to derive; this one is far above any
53
+ * realistic account and keeps a malformed `Count` from spinning forever. */
54
+ export declare const MAX_RULE_ID_SCAN = 512;
55
+ export interface CollectedRules {
56
+ rules: ObservedRule[];
57
+ /** Rule ids whose stored predicate could not be read even though the
58
+ * interpreter is attached. Such a rule is reported without a predicate,
59
+ * which classifies it as opaque rather than as safely narrow. */
60
+ unreadablePredicateRuleIds: number[];
61
+ /** True when the scan stopped before accounting for every live rule. The
62
+ * result is then a SUBSET of the account's rules, so an empty overlap list
63
+ * proves nothing and the caller must not present it as safety. */
64
+ incomplete: boolean;
65
+ }
66
+ /**
67
+ * Every context rule on the account, with predicates filled in for the rules
68
+ * our interpreter polices.
69
+ *
70
+ * Rule ids are NOT contiguous. OZ assigns them from a monotonic `NextId` and
71
+ * decrements `Count` on removal without ever reusing an id
72
+ * (`smart_account/storage.rs`: `add_context_rule` bumps `NextId`,
73
+ * `remove_context_rule` only lowers `Count`), so after any removal
74
+ * `Count < NextId` and the live ids have gaps. Iterating `0..Count-1` would
75
+ * silently skip live rules at higher ids, and a skipped rule is a missed
76
+ * overlap - the one error that reports safety which does not exist. Instead
77
+ * the scan walks ids upward until it has accounted for `Count` live rules.
78
+ *
79
+ * A rule whose predicate cannot be read is deliberately left without one. That
80
+ * demotes it to the `foreign` class, so the scan reports it as opaque instead
81
+ * of assuming it is narrow.
82
+ */
83
+ export declare function collectObservedRules(args: {
84
+ reader: AccountRuleReader;
85
+ smartAccount: string;
86
+ interpreterAddress: string;
87
+ maxRuleIdScan?: number;
88
+ }): Promise<CollectedRules>;
89
+ /**
90
+ * An `AccountRuleReader` over a live RPC server.
91
+ *
92
+ * The two OZ getters are read-only simulations, built the same way as
93
+ * `getContractVersion` in `build-install-policy.ts`: the source account is
94
+ * constructed locally because a simulation never checks its sequence number,
95
+ * and asking the network for a random key would 404.
96
+ *
97
+ * The stored document is fetched as a ledger entry rather than a contract
98
+ * call, because the interpreter publishes no getter for it.
99
+ */
100
+ export declare function accountRuleReaderFromServer(server: rpc.Server, networkPassphrase: string): AccountRuleReader;
@@ -0,0 +1,283 @@
1
+ //! Reading an OpenZeppelin smart account's context rules back off chain.
2
+ //!
3
+ //! `authority-overlap.ts` needs to know what a signer can already do before a
4
+ //! new policy is installed. That means every rule on the account: its context
5
+ //! type, its signers, its attached policies, and - for rules our interpreter
6
+ //! polices - the predicate itself.
7
+ //!
8
+ //! The predicate is NOT reachable through a contract call. The interpreter
9
+ //! exposes no getter for `StoredDoc` (`lib.rs` publishes only `grammar_version`,
10
+ //! `install`, `enforce`, the pause pair, `uninstall` and
11
+ //! `rotate_master_signer_set`), so it is read as a ledger entry instead. That
12
+ //! keeps this a pure client-side capability: adding a getter would change a
13
+ //! deployed contract's ABI and force a redeploy plus re-audit to obtain data
14
+ //! the ledger already exposes.
15
+ //!
16
+ //! The decoders here are pure so they can be tested without a network; the
17
+ //! caller supplies raw `ScVal`s.
18
+ import { Account, Address, BASE_FEE, Contract, Keypair, rpc, TransactionBuilder, xdr, } from '@stellar/stellar-sdk';
19
+ import { decodePredicate } from "../predicate/decode.js";
20
+ /** `storage.rs:295` - the third element of the persistent doc key tuple. */
21
+ export const K_DOC = 1;
22
+ /** Persistent-storage key for a rule's stored document:
23
+ * `(account, rule_id, K_DOC)`, per `storage.rs:4`. */
24
+ export function docKeyScVal(smartAccount, ruleId) {
25
+ return xdr.ScVal.scvVec([
26
+ new Address(smartAccount).toScVal(),
27
+ xdr.ScVal.scvU32(ruleId),
28
+ xdr.ScVal.scvU32(K_DOC),
29
+ ]);
30
+ }
31
+ /** Ledger key for the interpreter's persistent entry holding that document. */
32
+ export function docLedgerKey(interpreter, smartAccount, ruleId) {
33
+ return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({
34
+ contract: new Address(interpreter).toScAddress(),
35
+ key: docKeyScVal(smartAccount, ruleId),
36
+ durability: xdr.ContractDataDurability.persistent(),
37
+ }));
38
+ }
39
+ // ---- ScVal helpers -----
40
+ /** Field of a `#[contracttype]` struct, which the host encodes as a map keyed
41
+ * by field-name symbol. Returns undefined when the field is absent so a
42
+ * caller can distinguish "not there" from "there and empty". */
43
+ function mapField(v, name) {
44
+ if (v.switch() !== xdr.ScValType.scvMap())
45
+ return undefined;
46
+ for (const entry of v.map() ?? []) {
47
+ const key = entry.key();
48
+ if (key.switch() === xdr.ScValType.scvSymbol() && key.sym().toString() === name) {
49
+ return entry.val();
50
+ }
51
+ }
52
+ return undefined;
53
+ }
54
+ function u32Of(v) {
55
+ return v?.switch() === xdr.ScValType.scvU32() ? v.u32() : undefined;
56
+ }
57
+ function addressOf(v) {
58
+ if (!v || v.switch() !== xdr.ScValType.scvAddress())
59
+ return undefined;
60
+ return Address.fromScAddress(v.address()).toString();
61
+ }
62
+ /** An enum variant of a `#[contracttype]` enum: `ScVal::Vec([Symbol, ...args])`. */
63
+ function enumVariant(v) {
64
+ if (!v || v.switch() !== xdr.ScValType.scvVec())
65
+ return undefined;
66
+ const items = v.vec() ?? [];
67
+ const head = items[0];
68
+ if (!head || head.switch() !== xdr.ScValType.scvSymbol())
69
+ return undefined;
70
+ return { tag: head.sym().toString(), args: items.slice(1) };
71
+ }
72
+ // ---- decoders -----
73
+ /** OZ `ContextRuleType`. An unrecognised tag is reported as `default`, which
74
+ * is the widest reading and therefore the safe one: it makes the rule look
75
+ * like it could serve any call, so overlap is over-reported, never missed. */
76
+ export function decodeContextType(v) {
77
+ const variant = enumVariant(v);
78
+ if (!variant)
79
+ return { kind: 'default' };
80
+ if (variant.tag === 'CallContract') {
81
+ const addr = addressOf(variant.args[0]);
82
+ return addr ? { kind: 'call_contract', address: addr } : { kind: 'default' };
83
+ }
84
+ if (variant.tag === 'CreateContract') {
85
+ const arg = variant.args[0];
86
+ const hash = arg?.switch() === xdr.ScValType.scvBytes() ? arg.bytes().toString('hex') : '';
87
+ return { kind: 'create_contract', wasmHash: hash };
88
+ }
89
+ return { kind: 'default' };
90
+ }
91
+ /** OZ `Signer::Delegated(Address) | Signer::External(Address, Bytes)`. */
92
+ export function decodeSigner(v) {
93
+ const variant = enumVariant(v);
94
+ if (!variant)
95
+ return undefined;
96
+ if (variant.tag === 'Delegated') {
97
+ const addr = addressOf(variant.args[0]);
98
+ return addr ? { kind: 'delegated', address: addr } : undefined;
99
+ }
100
+ if (variant.tag === 'External') {
101
+ const verifier = addressOf(variant.args[0]);
102
+ const keyArg = variant.args[1];
103
+ const keyBytes = keyArg?.switch() === xdr.ScValType.scvBytes() ? keyArg.bytes().toString('hex') : '';
104
+ return verifier ? { kind: 'external', verifier, keyBytes } : undefined;
105
+ }
106
+ return undefined;
107
+ }
108
+ /** A full OZ `ContextRule` as returned by `get_context_rule(id)`.
109
+ * `predicate` is filled in separately from the ledger entry. */
110
+ export function decodeContextRule(v) {
111
+ const id = u32Of(mapField(v, 'id'));
112
+ if (id === undefined)
113
+ return undefined;
114
+ const signersVal = mapField(v, 'signers');
115
+ const signers = [];
116
+ if (signersVal?.switch() === xdr.ScValType.scvVec()) {
117
+ for (const s of signersVal.vec() ?? []) {
118
+ const decoded = decodeSigner(s);
119
+ if (decoded)
120
+ signers.push(decoded);
121
+ }
122
+ }
123
+ const policiesVal = mapField(v, 'policies');
124
+ const policyAddresses = [];
125
+ if (policiesVal?.switch() === xdr.ScValType.scvVec()) {
126
+ for (const p of policiesVal.vec() ?? []) {
127
+ const addr = addressOf(p);
128
+ if (addr)
129
+ policyAddresses.push(addr);
130
+ }
131
+ }
132
+ // `policy_ids` is index-aligned with `policies` in OZ's ContextRule. Only
133
+ // the ids can be passed to `remove_policy`, so a detach is impossible
134
+ // without them; they are read here rather than looked up again later.
135
+ const policyIdsVal = mapField(v, 'policy_ids');
136
+ const policyIds = [];
137
+ if (policyIdsVal?.switch() === xdr.ScValType.scvVec()) {
138
+ for (const pid of policyIdsVal.vec() ?? []) {
139
+ const n = u32Of(pid);
140
+ if (n !== undefined)
141
+ policyIds.push(n);
142
+ }
143
+ }
144
+ return {
145
+ id,
146
+ contextType: decodeContextType(mapField(v, 'context_type')),
147
+ signers,
148
+ policyAddresses,
149
+ ...(policyIds.length > 0 ? { policyIds } : {}),
150
+ };
151
+ }
152
+ /** `storage.rs:296` - the third element of the persistent nonce key tuple. */
153
+ export const K_NONCE = 2;
154
+ /** Ledger key for a rule's stored install nonce. Read directly for the same
155
+ * reason as the document: the interpreter publishes no getter. */
156
+ export function nonceLedgerKey(interpreter, smartAccount, ruleId) {
157
+ return xdr.LedgerKey.contractData(new xdr.LedgerKeyContractData({
158
+ contract: new Address(interpreter).toScAddress(),
159
+ key: xdr.ScVal.scvVec([
160
+ new Address(smartAccount).toScVal(),
161
+ xdr.ScVal.scvU32(ruleId),
162
+ xdr.ScVal.scvU32(K_NONCE),
163
+ ]),
164
+ durability: xdr.ContractDataDurability.persistent(),
165
+ }));
166
+ }
167
+ export function decodeStoredOracleBounds(v) {
168
+ const read = (name) => u32Of(mapField(v, name));
169
+ const staleness = read('oracle_max_staleness_seconds');
170
+ const deviation = read('oracle_max_deviation_bps');
171
+ const xfeed = read('oracle_max_xfeed_dev_bps');
172
+ return {
173
+ ...(staleness !== undefined ? { maxStalenessSeconds: staleness } : {}),
174
+ ...(deviation !== undefined ? { maxDeviationBps: deviation } : {}),
175
+ ...(xfeed !== undefined ? { maxCrossFeedDeviationBps: xfeed } : {}),
176
+ };
177
+ }
178
+ /** Raw predicate bytes out of a `StoredDoc` ledger entry value. */
179
+ export function decodeStoredPredicateBytes(v) {
180
+ const field = mapField(v, 'predicate_bytes');
181
+ if (!field || field.switch() !== xdr.ScValType.scvBytes())
182
+ return undefined;
183
+ return field.bytes();
184
+ }
185
+ /** How far the id scan will probe before giving up. OZ imposes no per-account
186
+ * rule cap, so there is no exact bound to derive; this one is far above any
187
+ * realistic account and keeps a malformed `Count` from spinning forever. */
188
+ export const MAX_RULE_ID_SCAN = 512;
189
+ /**
190
+ * Every context rule on the account, with predicates filled in for the rules
191
+ * our interpreter polices.
192
+ *
193
+ * Rule ids are NOT contiguous. OZ assigns them from a monotonic `NextId` and
194
+ * decrements `Count` on removal without ever reusing an id
195
+ * (`smart_account/storage.rs`: `add_context_rule` bumps `NextId`,
196
+ * `remove_context_rule` only lowers `Count`), so after any removal
197
+ * `Count < NextId` and the live ids have gaps. Iterating `0..Count-1` would
198
+ * silently skip live rules at higher ids, and a skipped rule is a missed
199
+ * overlap - the one error that reports safety which does not exist. Instead
200
+ * the scan walks ids upward until it has accounted for `Count` live rules.
201
+ *
202
+ * A rule whose predicate cannot be read is deliberately left without one. That
203
+ * demotes it to the `foreign` class, so the scan reports it as opaque instead
204
+ * of assuming it is narrow.
205
+ */
206
+ export async function collectObservedRules(args) {
207
+ const count = await args.reader.getContextRuleCount(args.smartAccount);
208
+ const limit = args.maxRuleIdScan ?? MAX_RULE_ID_SCAN;
209
+ const rules = [];
210
+ const unreadablePredicateRuleIds = [];
211
+ let id = 0;
212
+ while (rules.length < count && id < limit) {
213
+ const raw = await args.reader.getContextRule(args.smartAccount, id);
214
+ id++;
215
+ if (!raw)
216
+ continue;
217
+ const rule = decodeContextRule(raw);
218
+ if (!rule)
219
+ continue;
220
+ if (rule.policyAddresses.includes(args.interpreterAddress)) {
221
+ const doc = await args.reader.getStoredDoc(args.interpreterAddress, args.smartAccount, rule.id);
222
+ const bytes = doc ? decodeStoredPredicateBytes(doc) : undefined;
223
+ if (bytes) {
224
+ try {
225
+ rule.predicate = decodePredicate(bytes);
226
+ // Carried so a merge can re-install the SAME bounds. They are
227
+ // tighten-only overrides, so losing them widens the policy quietly.
228
+ if (doc)
229
+ rule.oracleBounds = decodeStoredOracleBounds(doc);
230
+ }
231
+ catch {
232
+ unreadablePredicateRuleIds.push(rule.id);
233
+ }
234
+ }
235
+ else {
236
+ unreadablePredicateRuleIds.push(rule.id);
237
+ }
238
+ }
239
+ rules.push(rule);
240
+ }
241
+ return { rules, unreadablePredicateRuleIds, incomplete: rules.length < count };
242
+ }
243
+ /**
244
+ * An `AccountRuleReader` over a live RPC server.
245
+ *
246
+ * The two OZ getters are read-only simulations, built the same way as
247
+ * `getContractVersion` in `build-install-policy.ts`: the source account is
248
+ * constructed locally because a simulation never checks its sequence number,
249
+ * and asking the network for a random key would 404.
250
+ *
251
+ * The stored document is fetched as a ledger entry rather than a contract
252
+ * call, because the interpreter publishes no getter for it.
253
+ */
254
+ export function accountRuleReaderFromServer(server, networkPassphrase) {
255
+ async function simulateCall(contract, method, ...args) {
256
+ const account = new Account(Keypair.random().publicKey(), '0');
257
+ const tx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase })
258
+ .addOperation(new Contract(contract).call(method, ...args))
259
+ .setTimeout(30)
260
+ .build();
261
+ const sim = await server.simulateTransaction(tx);
262
+ if (rpc.Api.isSimulationError(sim))
263
+ return undefined;
264
+ return sim.result?.retval;
265
+ }
266
+ return {
267
+ async getContextRuleCount(smartAccount) {
268
+ const val = await simulateCall(smartAccount, 'get_context_rules_count');
269
+ return u32Of(val) ?? 0;
270
+ },
271
+ async getContextRule(smartAccount, ruleId) {
272
+ return simulateCall(smartAccount, 'get_context_rule', xdr.ScVal.scvU32(ruleId));
273
+ },
274
+ async getStoredDoc(interpreter, smartAccount, ruleId) {
275
+ const key = docLedgerKey(interpreter, smartAccount, ruleId);
276
+ const res = await server.getLedgerEntries(key);
277
+ const entry = res.entries?.[0]?.val;
278
+ if (!entry || entry.switch() !== xdr.LedgerEntryType.contractData())
279
+ return undefined;
280
+ return entry.contractData().val();
281
+ },
282
+ };
283
+ }
@@ -7,7 +7,7 @@
7
7
  // this module takes it from there.
8
8
  //
9
9
  // Mirrors `decode_leaf` / `decode_node` in
10
- // `packages/policy-interpreter/src/dsl.rs`. Two rules carry most of the
10
+ // `contracts/policy-interpreter/src/dsl.rs`. Two rules carry most of the
11
11
  // weight, and both come from the Rust decoder verbatim:
12
12
  //
13
13
  // 1. A `Vec` whose FIRST element is a Symbol is a selector tuple. A `Vec`