@crediolabs/policy-synth 0.2.0 → 0.3.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 (249) hide show
  1. package/README.md +4 -4
  2. package/dist/adapters/interpreter/adapter.d.ts +19 -25
  3. package/dist/adapters/interpreter/adapter.js +54 -487
  4. package/dist/errors.d.ts +1 -1
  5. package/dist/index.d.ts +1 -4
  6. package/dist/index.js +1 -4
  7. package/dist/install/build-add-context-rule.d.ts +3 -19
  8. package/dist/install/build-add-context-rule.js +3 -98
  9. package/dist/install/build-install-policy.d.ts +4 -53
  10. package/dist/install/build-install-policy.js +44 -123
  11. package/dist/install/index.d.ts +0 -2
  12. package/dist/install/index.js +0 -7
  13. package/dist/predicate/decode.d.ts +1 -1
  14. package/dist/predicate/decode.js +2 -70
  15. package/dist/predicate/encode.js +45 -229
  16. package/dist/predicate/from-json.js +1 -42
  17. package/dist/record/decode.js +3 -8
  18. package/dist/record/freshness.d.ts +17 -11
  19. package/dist/record/freshness.js +28 -18
  20. package/dist/review-card/builder.d.ts +4 -3
  21. package/dist/review-card/builder.js +18 -162
  22. package/dist/review-card/cross-check.js +2 -105
  23. package/dist/review-card/render-leaf.d.ts +4 -0
  24. package/dist/review-card/render-leaf.js +47 -0
  25. package/dist/run/index.d.ts +36 -139
  26. package/dist/run/index.js +125 -437
  27. package/dist/run/schemas.d.ts +168 -1929
  28. package/dist/run/schemas.js +40 -269
  29. package/dist/{synth → simulate}/deny-cases.d.ts +4 -8
  30. package/dist/simulate/deny-cases.js +282 -0
  31. package/dist/simulate/evaluate.d.ts +18 -0
  32. package/dist/simulate/evaluate.js +271 -0
  33. package/dist/simulate/index.d.ts +4 -0
  34. package/dist/simulate/index.js +8 -0
  35. package/dist/synth/compose-from-recording.d.ts +24 -51
  36. package/dist/synth/compose-from-recording.js +120 -282
  37. package/dist/synth/index.d.ts +0 -5
  38. package/dist/synth/index.js +0 -5
  39. package/dist/synth/synthesize-from-recording.d.ts +1 -29
  40. package/dist/synth/synthesize-from-recording.js +41 -356
  41. package/dist/types.d.ts +8 -60
  42. package/dist/types.js +5 -2
  43. package/dist-cjs/adapters/interpreter/adapter.d.ts +19 -25
  44. package/dist-cjs/adapters/interpreter/adapter.js +56 -489
  45. package/dist-cjs/errors.d.ts +1 -1
  46. package/dist-cjs/index.d.ts +1 -4
  47. package/dist-cjs/index.js +1 -4
  48. package/dist-cjs/install/build-add-context-rule.d.ts +3 -19
  49. package/dist-cjs/install/build-add-context-rule.js +1 -97
  50. package/dist-cjs/install/build-install-policy.d.ts +4 -53
  51. package/dist-cjs/install/build-install-policy.js +44 -122
  52. package/dist-cjs/install/index.d.ts +0 -2
  53. package/dist-cjs/install/index.js +2 -23
  54. package/dist-cjs/predicate/decode.d.ts +1 -1
  55. package/dist-cjs/predicate/decode.js +2 -70
  56. package/dist-cjs/predicate/encode.js +45 -229
  57. package/dist-cjs/predicate/from-json.js +1 -42
  58. package/dist-cjs/record/decode.js +3 -8
  59. package/dist-cjs/record/freshness.d.ts +17 -11
  60. package/dist-cjs/record/freshness.js +28 -18
  61. package/dist-cjs/review-card/builder.d.ts +4 -3
  62. package/dist-cjs/review-card/builder.js +23 -167
  63. package/dist-cjs/review-card/cross-check.js +7 -110
  64. package/dist-cjs/review-card/render-leaf.d.ts +4 -0
  65. package/dist-cjs/review-card/render-leaf.js +52 -0
  66. package/dist-cjs/run/index.d.ts +36 -139
  67. package/dist-cjs/run/index.js +125 -444
  68. package/dist-cjs/run/schemas.d.ts +168 -1929
  69. package/dist-cjs/run/schemas.js +41 -270
  70. package/dist-cjs/{synth → simulate}/deny-cases.d.ts +4 -8
  71. package/dist-cjs/simulate/deny-cases.js +286 -0
  72. package/dist-cjs/simulate/evaluate.d.ts +18 -0
  73. package/dist-cjs/simulate/evaluate.js +274 -0
  74. package/dist-cjs/simulate/index.d.ts +4 -0
  75. package/dist-cjs/simulate/index.js +13 -0
  76. package/dist-cjs/synth/compose-from-recording.d.ts +24 -51
  77. package/dist-cjs/synth/compose-from-recording.js +120 -282
  78. package/dist-cjs/synth/index.d.ts +0 -5
  79. package/dist-cjs/synth/index.js +1 -11
  80. package/dist-cjs/synth/synthesize-from-recording.d.ts +1 -29
  81. package/dist-cjs/synth/synthesize-from-recording.js +39 -354
  82. package/dist-cjs/types.d.ts +8 -60
  83. package/dist-cjs/types.js +6 -3
  84. package/package.json +5 -5
  85. package/src/adapters/interpreter/adapter.ts +76 -572
  86. package/src/errors.ts +0 -19
  87. package/src/index.ts +1 -4
  88. package/src/install/build-add-context-rule.ts +5 -139
  89. package/src/install/build-install-policy.ts +93 -214
  90. package/src/install/index.ts +0 -34
  91. package/src/predicate/decode.ts +2 -70
  92. package/src/predicate/encode.ts +49 -261
  93. package/src/predicate/from-json.ts +1 -43
  94. package/src/record/decode.ts +3 -8
  95. package/src/record/freshness.ts +29 -18
  96. package/src/review-card/builder.ts +19 -168
  97. package/src/review-card/cross-check.ts +3 -105
  98. package/src/review-card/render-leaf.ts +48 -0
  99. package/src/run/index.ts +144 -572
  100. package/src/run/schemas.ts +42 -291
  101. package/src/simulate/deny-cases.ts +334 -0
  102. package/src/simulate/evaluate.ts +284 -0
  103. package/src/simulate/index.ts +11 -0
  104. package/src/synth/compose-from-recording.ts +148 -347
  105. package/src/synth/index.ts +0 -13
  106. package/src/synth/synthesize-from-recording.ts +43 -456
  107. package/src/types.ts +13 -49
  108. package/dist/adapters/interpreter/index.d.ts +0 -1
  109. package/dist/adapters/interpreter/index.js +0 -2
  110. package/dist/adapters/oz/adapter.d.ts +0 -20
  111. package/dist/adapters/oz/adapter.js +0 -295
  112. package/dist/adapters/oz/index.d.ts +0 -1
  113. package/dist/adapters/oz/index.js +0 -2
  114. package/dist/codegen/compile-gate.d.ts +0 -33
  115. package/dist/codegen/compile-gate.js +0 -124
  116. package/dist/codegen/index.d.ts +0 -2
  117. package/dist/codegen/index.js +0 -8
  118. package/dist/codegen/template.d.ts +0 -18
  119. package/dist/codegen/template.js +0 -148
  120. package/dist/install/authority-overlap.d.ts +0 -134
  121. package/dist/install/authority-overlap.js +0 -0
  122. package/dist/install/build-install-predicate.d.ts +0 -96
  123. package/dist/install/build-install-predicate.js +0 -444
  124. package/dist/install/build-merge-policy.d.ts +0 -70
  125. package/dist/install/build-merge-policy.js +0 -130
  126. package/dist/install/plan-merge-policy.d.ts +0 -49
  127. package/dist/install/plan-merge-policy.js +0 -86
  128. package/dist/install/read-account-rules.d.ts +0 -100
  129. package/dist/install/read-account-rules.js +0 -283
  130. package/dist/ir/index.d.ts +0 -1
  131. package/dist/ir/index.js +0 -2
  132. package/dist/ir/types.d.ts +0 -140
  133. package/dist/ir/types.js +0 -11
  134. package/dist/mandate/index.d.ts +0 -2
  135. package/dist/mandate/index.js +0 -2
  136. package/dist/mandate/to-ir.d.ts +0 -3
  137. package/dist/mandate/to-ir.js +0 -60
  138. package/dist/mandate/types.d.ts +0 -20
  139. package/dist/mandate/types.js +0 -8
  140. package/dist/seams/index.d.ts +0 -1
  141. package/dist/seams/index.js +0 -2
  142. package/dist/seams/types.d.ts +0 -66
  143. package/dist/seams/types.js +0 -11
  144. package/dist/synth/deny-cases.js +0 -562
  145. package/dist/synth/evaluate.d.ts +0 -39
  146. package/dist/synth/evaluate.js +0 -551
  147. package/dist/synth/harness.d.ts +0 -28
  148. package/dist/synth/harness.js +0 -47
  149. package/dist/synth/minimize.d.ts +0 -4
  150. package/dist/synth/minimize.js +0 -38
  151. package/dist/synth/permit-context.d.ts +0 -15
  152. package/dist/synth/permit-context.js +0 -116
  153. package/dist/synth/predicate-literals.d.ts +0 -5
  154. package/dist/synth/predicate-literals.js +0 -25
  155. package/dist/synth/synthesize-from-mandate.d.ts +0 -20
  156. package/dist/synth/synthesize-from-mandate.js +0 -59
  157. package/dist/verify/envelope.d.ts +0 -15
  158. package/dist/verify/envelope.js +0 -22
  159. package/dist/verify/index.d.ts +0 -3
  160. package/dist/verify/index.js +0 -3
  161. package/dist/verify/simulate.d.ts +0 -31
  162. package/dist/verify/simulate.js +0 -258
  163. package/dist/verify/verify.d.ts +0 -21
  164. package/dist/verify/verify.js +0 -189
  165. package/dist-cjs/adapters/interpreter/index.d.ts +0 -1
  166. package/dist-cjs/adapters/interpreter/index.js +0 -8
  167. package/dist-cjs/adapters/oz/adapter.d.ts +0 -20
  168. package/dist-cjs/adapters/oz/adapter.js +0 -300
  169. package/dist-cjs/adapters/oz/index.d.ts +0 -1
  170. package/dist-cjs/adapters/oz/index.js +0 -8
  171. package/dist-cjs/codegen/compile-gate.d.ts +0 -33
  172. package/dist-cjs/codegen/compile-gate.js +0 -128
  173. package/dist-cjs/codegen/index.d.ts +0 -2
  174. package/dist-cjs/codegen/index.js +0 -14
  175. package/dist-cjs/codegen/template.d.ts +0 -18
  176. package/dist-cjs/codegen/template.js +0 -151
  177. package/dist-cjs/install/authority-overlap.d.ts +0 -134
  178. package/dist-cjs/install/authority-overlap.js +0 -0
  179. package/dist-cjs/install/build-install-predicate.d.ts +0 -96
  180. package/dist-cjs/install/build-install-predicate.js +0 -479
  181. package/dist-cjs/install/build-merge-policy.d.ts +0 -70
  182. package/dist-cjs/install/build-merge-policy.js +0 -134
  183. package/dist-cjs/install/plan-merge-policy.d.ts +0 -49
  184. package/dist-cjs/install/plan-merge-policy.js +0 -90
  185. package/dist-cjs/install/read-account-rules.d.ts +0 -100
  186. package/dist-cjs/install/read-account-rules.js +0 -296
  187. package/dist-cjs/ir/index.d.ts +0 -1
  188. package/dist-cjs/ir/index.js +0 -3
  189. package/dist-cjs/ir/types.d.ts +0 -140
  190. package/dist-cjs/ir/types.js +0 -12
  191. package/dist-cjs/mandate/index.d.ts +0 -2
  192. package/dist-cjs/mandate/index.js +0 -6
  193. package/dist-cjs/mandate/to-ir.d.ts +0 -3
  194. package/dist-cjs/mandate/to-ir.js +0 -63
  195. package/dist-cjs/mandate/types.d.ts +0 -20
  196. package/dist-cjs/mandate/types.js +0 -9
  197. package/dist-cjs/seams/index.d.ts +0 -1
  198. package/dist-cjs/seams/index.js +0 -3
  199. package/dist-cjs/seams/types.d.ts +0 -66
  200. package/dist-cjs/seams/types.js +0 -12
  201. package/dist-cjs/synth/deny-cases.js +0 -568
  202. package/dist-cjs/synth/evaluate.d.ts +0 -39
  203. package/dist-cjs/synth/evaluate.js +0 -554
  204. package/dist-cjs/synth/harness.d.ts +0 -28
  205. package/dist-cjs/synth/harness.js +0 -50
  206. package/dist-cjs/synth/minimize.d.ts +0 -4
  207. package/dist-cjs/synth/minimize.js +0 -41
  208. package/dist-cjs/synth/permit-context.d.ts +0 -15
  209. package/dist-cjs/synth/permit-context.js +0 -119
  210. package/dist-cjs/synth/predicate-literals.d.ts +0 -5
  211. package/dist-cjs/synth/predicate-literals.js +0 -28
  212. package/dist-cjs/synth/synthesize-from-mandate.d.ts +0 -20
  213. package/dist-cjs/synth/synthesize-from-mandate.js +0 -62
  214. package/dist-cjs/verify/envelope.d.ts +0 -15
  215. package/dist-cjs/verify/envelope.js +0 -23
  216. package/dist-cjs/verify/index.d.ts +0 -3
  217. package/dist-cjs/verify/index.js +0 -8
  218. package/dist-cjs/verify/simulate.d.ts +0 -31
  219. package/dist-cjs/verify/simulate.js +0 -261
  220. package/dist-cjs/verify/verify.d.ts +0 -21
  221. package/dist-cjs/verify/verify.js +0 -192
  222. package/src/adapters/interpreter/index.ts +0 -8
  223. package/src/adapters/oz/adapter.ts +0 -376
  224. package/src/adapters/oz/index.ts +0 -9
  225. package/src/codegen/compile-gate.ts +0 -167
  226. package/src/codegen/index.ts +0 -17
  227. package/src/codegen/template.ts +0 -165
  228. package/src/install/authority-overlap.ts +0 -0
  229. package/src/install/build-merge-policy.ts +0 -219
  230. package/src/install/plan-merge-policy.ts +0 -133
  231. package/src/install/read-account-rules.ts +0 -376
  232. package/src/ir/index.ts +0 -13
  233. package/src/ir/types.ts +0 -132
  234. package/src/mandate/index.ts +0 -4
  235. package/src/mandate/to-ir.ts +0 -71
  236. package/src/mandate/types.ts +0 -21
  237. package/src/seams/index.ts +0 -11
  238. package/src/seams/types.ts +0 -81
  239. package/src/synth/deny-cases.ts +0 -663
  240. package/src/synth/evaluate.ts +0 -613
  241. package/src/synth/harness.ts +0 -68
  242. package/src/synth/minimize.ts +0 -48
  243. package/src/synth/permit-context.ts +0 -136
  244. package/src/synth/predicate-literals.ts +0 -27
  245. package/src/synth/synthesize-from-mandate.ts +0 -82
  246. package/src/verify/envelope.ts +0 -28
  247. package/src/verify/index.ts +0 -5
  248. package/src/verify/simulate.ts +0 -311
  249. package/src/verify/verify.ts +0 -243
@@ -1,133 +0,0 @@
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
-
35
- import type { PredicateNode } from '../types.ts'
36
- import type { ObservedRule } from './authority-overlap.ts'
37
- import { type MergeResult, mergeIntoAnd } from './authority-overlap.ts'
38
-
39
- export type MergeStep = 'detach' | 'reinstall'
40
-
41
- export interface MergePlanRefused {
42
- ok: false
43
- /** Why the merge cannot proceed, in terms the caller can act on. */
44
- reason: string
45
- }
46
-
47
- export interface MergePlanAccepted {
48
- ok: true
49
- /** The conjunction to install in step 2. */
50
- predicate: PredicateNode
51
- /** OZ registry id of the interpreter policy on this rule, for
52
- * `remove_policy`. */
53
- policyId: number
54
- /** Oracle bounds to re-install with the merged predicate. Carried from the
55
- * document being replaced: they are tighten-only overrides against the wasm
56
- * defaults, so omitting them would quietly widen the policy while the
57
- * operator believed they were tightening it. */
58
- oracleParams?: {
59
- maxStalenessSeconds?: number
60
- maxDeviationBps?: number
61
- maxCrossFeedDeviationBps?: number
62
- }
63
- /** Consequences the caller must see BEFORE signing step 1, because step 1 is
64
- * the destructive one. */
65
- warnings: string[]
66
- /** What the caller should do after the requested step confirms. */
67
- followUp: string
68
- }
69
-
70
- export type MergePlan = MergePlanRefused | MergePlanAccepted
71
-
72
- /** The interpreter's registry id on a rule, or null when it is not attached
73
- * or the ids were not readable. */
74
- export function interpreterPolicyId(rule: ObservedRule, interpreterAddress: string): number | null {
75
- const index = rule.policyAddresses.indexOf(interpreterAddress)
76
- if (index < 0) return null
77
- const id = rule.policyIds?.[index]
78
- return typeof id === 'number' ? id : null
79
- }
80
-
81
- /**
82
- * Decide whether the merge can proceed, and say what it will cost.
83
- *
84
- * Refuses rather than guesses whenever the account is not in the shape the
85
- * remedy assumes: the rule must be policed by our interpreter, its predicate
86
- * must have been readable, and the ids needed to detach it must be present. A
87
- * merge built on a predicate we could not read would silently replace a rule
88
- * with something narrower or wider than its author wrote.
89
- */
90
- export function planMergePolicy(args: {
91
- rule: ObservedRule
92
- interpreterAddress: string
93
- incoming: PredicateNode
94
- step: MergeStep
95
- }): MergePlan {
96
- const policyId = interpreterPolicyId(args.rule, args.interpreterAddress)
97
- if (policyId === null) {
98
- return {
99
- ok: false,
100
- 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.`,
101
- }
102
- }
103
-
104
- const existing = args.rule.predicate
105
- if (!existing) {
106
- return {
107
- ok: false,
108
- 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`,
109
- }
110
- }
111
-
112
- const merged: MergeResult = mergeIntoAnd(existing, args.incoming)
113
- if (!merged.ok || !merged.predicate) {
114
- return { ok: false, reason: merged.reason ?? 'the two predicates cannot be conjoined' }
115
- }
116
-
117
- const warnings = [
118
- `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`,
119
- 'the rule is unpoliced between the two transactions, so a signer of it is unconstrained by this policy until step 2 confirms',
120
- ]
121
-
122
- return {
123
- ok: true,
124
- predicate: merged.predicate,
125
- policyId,
126
- ...(args.rule.oracleBounds ? { oracleParams: args.rule.oracleBounds } : {}),
127
- warnings,
128
- followUp:
129
- args.step === 'detach'
130
- ? "sign and submit this transaction, wait for it to confirm, then call again with step: 'reinstall' to install the merged predicate"
131
- : 'sign and submit this transaction; the merged predicate is then the only policy governing this rule',
132
- }
133
- }
@@ -1,376 +0,0 @@
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
-
19
- import {
20
- Account,
21
- Address,
22
- BASE_FEE,
23
- Contract,
24
- Keypair,
25
- rpc,
26
- TransactionBuilder,
27
- xdr,
28
- } from '@stellar/stellar-sdk'
29
- import { decodePredicate } from '../predicate/decode.ts'
30
- import type { SignerDraft } from '../types.ts'
31
- import type { ContextType, ObservedRule } from './authority-overlap.ts'
32
-
33
- /** `storage.rs:295` - the third element of the persistent doc key tuple. */
34
- export const K_DOC = 1
35
-
36
- /** Persistent-storage key for a rule's stored document:
37
- * `(account, rule_id, K_DOC)`, per `storage.rs:4`. */
38
- export function docKeyScVal(smartAccount: string, ruleId: number): xdr.ScVal {
39
- return xdr.ScVal.scvVec([
40
- new Address(smartAccount).toScVal(),
41
- xdr.ScVal.scvU32(ruleId),
42
- xdr.ScVal.scvU32(K_DOC),
43
- ])
44
- }
45
-
46
- /** Ledger key for the interpreter's persistent entry holding that document. */
47
- export function docLedgerKey(
48
- interpreter: string,
49
- smartAccount: string,
50
- ruleId: number
51
- ): xdr.LedgerKey {
52
- return xdr.LedgerKey.contractData(
53
- new xdr.LedgerKeyContractData({
54
- contract: new Address(interpreter).toScAddress(),
55
- key: docKeyScVal(smartAccount, ruleId),
56
- durability: xdr.ContractDataDurability.persistent(),
57
- })
58
- )
59
- }
60
-
61
- // ---- ScVal helpers -----
62
-
63
- /** Field of a `#[contracttype]` struct, which the host encodes as a map keyed
64
- * by field-name symbol. Returns undefined when the field is absent so a
65
- * caller can distinguish "not there" from "there and empty". */
66
- function mapField(v: xdr.ScVal, name: string): xdr.ScVal | undefined {
67
- if (v.switch() !== xdr.ScValType.scvMap()) return undefined
68
- for (const entry of v.map() ?? []) {
69
- const key = entry.key()
70
- if (key.switch() === xdr.ScValType.scvSymbol() && key.sym().toString() === name) {
71
- return entry.val()
72
- }
73
- }
74
- return undefined
75
- }
76
-
77
- function u32Of(v: xdr.ScVal | undefined): number | undefined {
78
- return v?.switch() === xdr.ScValType.scvU32() ? v.u32() : undefined
79
- }
80
-
81
- function addressOf(v: xdr.ScVal | undefined): string | undefined {
82
- if (!v || v.switch() !== xdr.ScValType.scvAddress()) return undefined
83
- return Address.fromScAddress(v.address()).toString()
84
- }
85
-
86
- /** An enum variant of a `#[contracttype]` enum: `ScVal::Vec([Symbol, ...args])`. */
87
- function enumVariant(v: xdr.ScVal | undefined): { tag: string; args: xdr.ScVal[] } | undefined {
88
- if (!v || v.switch() !== xdr.ScValType.scvVec()) return undefined
89
- const items = v.vec() ?? []
90
- const head = items[0]
91
- if (!head || head.switch() !== xdr.ScValType.scvSymbol()) return undefined
92
- return { tag: head.sym().toString(), args: items.slice(1) }
93
- }
94
-
95
- // ---- decoders -----
96
-
97
- /** OZ `ContextRuleType`. An unrecognised tag is reported as `default`, which
98
- * is the widest reading and therefore the safe one: it makes the rule look
99
- * like it could serve any call, so overlap is over-reported, never missed. */
100
- export function decodeContextType(v: xdr.ScVal | undefined): ContextType {
101
- const variant = enumVariant(v)
102
- if (!variant) return { kind: 'default' }
103
- if (variant.tag === 'CallContract') {
104
- const addr = addressOf(variant.args[0])
105
- return addr ? { kind: 'call_contract', address: addr } : { kind: 'default' }
106
- }
107
- if (variant.tag === 'CreateContract') {
108
- const arg = variant.args[0]
109
- const hash = arg?.switch() === xdr.ScValType.scvBytes() ? arg.bytes().toString('hex') : ''
110
- return { kind: 'create_contract', wasmHash: hash }
111
- }
112
- return { kind: 'default' }
113
- }
114
-
115
- /** OZ `Signer::Delegated(Address) | Signer::External(Address, Bytes)`. */
116
- export function decodeSigner(v: xdr.ScVal): SignerDraft | undefined {
117
- const variant = enumVariant(v)
118
- if (!variant) return undefined
119
- if (variant.tag === 'Delegated') {
120
- const addr = addressOf(variant.args[0])
121
- return addr ? { kind: 'delegated', address: addr } : undefined
122
- }
123
- if (variant.tag === 'External') {
124
- const verifier = addressOf(variant.args[0])
125
- const keyArg = variant.args[1]
126
- const keyBytes =
127
- keyArg?.switch() === xdr.ScValType.scvBytes() ? keyArg.bytes().toString('hex') : ''
128
- return verifier ? { kind: 'external', verifier, keyBytes } : undefined
129
- }
130
- return undefined
131
- }
132
-
133
- /** A full OZ `ContextRule` as returned by `get_context_rule(id)`.
134
- * `predicate` is filled in separately from the ledger entry. */
135
- export function decodeContextRule(v: xdr.ScVal): ObservedRule | undefined {
136
- const id = u32Of(mapField(v, 'id'))
137
- if (id === undefined) return undefined
138
-
139
- const signersVal = mapField(v, 'signers')
140
- const signers: SignerDraft[] = []
141
- if (signersVal?.switch() === xdr.ScValType.scvVec()) {
142
- for (const s of signersVal.vec() ?? []) {
143
- const decoded = decodeSigner(s)
144
- if (decoded) signers.push(decoded)
145
- }
146
- }
147
-
148
- const policiesVal = mapField(v, 'policies')
149
- const policyAddresses: string[] = []
150
- if (policiesVal?.switch() === xdr.ScValType.scvVec()) {
151
- for (const p of policiesVal.vec() ?? []) {
152
- const addr = addressOf(p)
153
- if (addr) policyAddresses.push(addr)
154
- }
155
- }
156
-
157
- // `policy_ids` is index-aligned with `policies` in OZ's ContextRule. Only
158
- // the ids can be passed to `remove_policy`, so a detach is impossible
159
- // without them; they are read here rather than looked up again later.
160
- const policyIdsVal = mapField(v, 'policy_ids')
161
- const policyIds: number[] = []
162
- if (policyIdsVal?.switch() === xdr.ScValType.scvVec()) {
163
- for (const pid of policyIdsVal.vec() ?? []) {
164
- const n = u32Of(pid)
165
- if (n !== undefined) policyIds.push(n)
166
- }
167
- }
168
-
169
- return {
170
- id,
171
- contextType: decodeContextType(mapField(v, 'context_type')),
172
- signers,
173
- policyAddresses,
174
- ...(policyIds.length > 0 ? { policyIds } : {}),
175
- }
176
- }
177
-
178
- /** `storage.rs:296` - the third element of the persistent nonce key tuple. */
179
- export const K_NONCE = 2
180
-
181
- /** Ledger key for a rule's stored install nonce. Read directly for the same
182
- * reason as the document: the interpreter publishes no getter. */
183
- export function nonceLedgerKey(
184
- interpreter: string,
185
- smartAccount: string,
186
- ruleId: number
187
- ): xdr.LedgerKey {
188
- return xdr.LedgerKey.contractData(
189
- new xdr.LedgerKeyContractData({
190
- contract: new Address(interpreter).toScAddress(),
191
- key: xdr.ScVal.scvVec([
192
- new Address(smartAccount).toScVal(),
193
- xdr.ScVal.scvU32(ruleId),
194
- xdr.ScVal.scvU32(K_NONCE),
195
- ]),
196
- durability: xdr.ContractDataDurability.persistent(),
197
- })
198
- )
199
- }
200
-
201
- /** Per-policy oracle bounds carried on a `StoredDoc`.
202
- *
203
- * These must survive a merge. They are tighten-only overrides against the
204
- * wasm defaults, so dropping them does not fail loudly: the rule keeps
205
- * working and silently tolerates staler prices and wider deviation than its
206
- * author chose. */
207
- export interface StoredOracleBounds {
208
- maxStalenessSeconds?: number
209
- maxDeviationBps?: number
210
- maxCrossFeedDeviationBps?: number
211
- }
212
-
213
- export function decodeStoredOracleBounds(v: xdr.ScVal): StoredOracleBounds {
214
- const read = (name: string): number | undefined => u32Of(mapField(v, name))
215
- const staleness = read('oracle_max_staleness_seconds')
216
- const deviation = read('oracle_max_deviation_bps')
217
- const xfeed = read('oracle_max_xfeed_dev_bps')
218
- return {
219
- ...(staleness !== undefined ? { maxStalenessSeconds: staleness } : {}),
220
- ...(deviation !== undefined ? { maxDeviationBps: deviation } : {}),
221
- ...(xfeed !== undefined ? { maxCrossFeedDeviationBps: xfeed } : {}),
222
- }
223
- }
224
-
225
- /** Raw predicate bytes out of a `StoredDoc` ledger entry value. */
226
- export function decodeStoredPredicateBytes(v: xdr.ScVal): Buffer | undefined {
227
- const field = mapField(v, 'predicate_bytes')
228
- if (!field || field.switch() !== xdr.ScValType.scvBytes()) return undefined
229
- return field.bytes()
230
- }
231
-
232
- // ---- collection -----
233
-
234
- /** The three reads the scan needs. Kept as an interface so the collection
235
- * below is testable without a network, matching the `InstallRpcClient`
236
- * pattern in `build-install-policy.ts`. */
237
- export interface AccountRuleReader {
238
- /** OZ `get_context_rules_count()`. */
239
- getContextRuleCount(smartAccount: string): Promise<number>
240
- /** OZ `get_context_rule(id)`. Undefined when the id is absent. */
241
- getContextRule(smartAccount: string, ruleId: number): Promise<xdr.ScVal | undefined>
242
- /** The interpreter's persistent `StoredDoc` entry, read as a ledger entry.
243
- * Undefined when no document is stored for that rule. */
244
- getStoredDoc(
245
- interpreter: string,
246
- smartAccount: string,
247
- ruleId: number
248
- ): Promise<xdr.ScVal | undefined>
249
- }
250
-
251
- /** How far the id scan will probe before giving up. OZ imposes no per-account
252
- * rule cap, so there is no exact bound to derive; this one is far above any
253
- * realistic account and keeps a malformed `Count` from spinning forever. */
254
- export const MAX_RULE_ID_SCAN = 512
255
-
256
- export interface CollectedRules {
257
- rules: ObservedRule[]
258
- /** Rule ids whose stored predicate could not be read even though the
259
- * interpreter is attached. Such a rule is reported without a predicate,
260
- * which classifies it as opaque rather than as safely narrow. */
261
- unreadablePredicateRuleIds: number[]
262
- /** True when the scan stopped before accounting for every live rule. The
263
- * result is then a SUBSET of the account's rules, so an empty overlap list
264
- * proves nothing and the caller must not present it as safety. */
265
- incomplete: boolean
266
- }
267
-
268
- /**
269
- * Every context rule on the account, with predicates filled in for the rules
270
- * our interpreter polices.
271
- *
272
- * Rule ids are NOT contiguous. OZ assigns them from a monotonic `NextId` and
273
- * decrements `Count` on removal without ever reusing an id
274
- * (`smart_account/storage.rs`: `add_context_rule` bumps `NextId`,
275
- * `remove_context_rule` only lowers `Count`), so after any removal
276
- * `Count < NextId` and the live ids have gaps. Iterating `0..Count-1` would
277
- * silently skip live rules at higher ids, and a skipped rule is a missed
278
- * overlap - the one error that reports safety which does not exist. Instead
279
- * the scan walks ids upward until it has accounted for `Count` live rules.
280
- *
281
- * A rule whose predicate cannot be read is deliberately left without one. That
282
- * demotes it to the `foreign` class, so the scan reports it as opaque instead
283
- * of assuming it is narrow.
284
- */
285
- export async function collectObservedRules(args: {
286
- reader: AccountRuleReader
287
- smartAccount: string
288
- interpreterAddress: string
289
- maxRuleIdScan?: number
290
- }): Promise<CollectedRules> {
291
- const count = await args.reader.getContextRuleCount(args.smartAccount)
292
- const limit = args.maxRuleIdScan ?? MAX_RULE_ID_SCAN
293
- const rules: ObservedRule[] = []
294
- const unreadablePredicateRuleIds: number[] = []
295
-
296
- let id = 0
297
- while (rules.length < count && id < limit) {
298
- const raw = await args.reader.getContextRule(args.smartAccount, id)
299
- id++
300
- if (!raw) continue
301
- const rule = decodeContextRule(raw)
302
- if (!rule) continue
303
-
304
- if (rule.policyAddresses.includes(args.interpreterAddress)) {
305
- const doc = await args.reader.getStoredDoc(
306
- args.interpreterAddress,
307
- args.smartAccount,
308
- rule.id
309
- )
310
- const bytes = doc ? decodeStoredPredicateBytes(doc) : undefined
311
- if (bytes) {
312
- try {
313
- rule.predicate = decodePredicate(bytes)
314
- // Carried so a merge can re-install the SAME bounds. They are
315
- // tighten-only overrides, so losing them widens the policy quietly.
316
- if (doc) rule.oracleBounds = decodeStoredOracleBounds(doc)
317
- } catch {
318
- unreadablePredicateRuleIds.push(rule.id)
319
- }
320
- } else {
321
- unreadablePredicateRuleIds.push(rule.id)
322
- }
323
- }
324
- rules.push(rule)
325
- }
326
-
327
- return { rules, unreadablePredicateRuleIds, incomplete: rules.length < count }
328
- }
329
-
330
- /**
331
- * An `AccountRuleReader` over a live RPC server.
332
- *
333
- * The two OZ getters are read-only simulations, built the same way as
334
- * `getContractVersion` in `build-install-policy.ts`: the source account is
335
- * constructed locally because a simulation never checks its sequence number,
336
- * and asking the network for a random key would 404.
337
- *
338
- * The stored document is fetched as a ledger entry rather than a contract
339
- * call, because the interpreter publishes no getter for it.
340
- */
341
- export function accountRuleReaderFromServer(
342
- server: rpc.Server,
343
- networkPassphrase: string
344
- ): AccountRuleReader {
345
- async function simulateCall(
346
- contract: string,
347
- method: string,
348
- ...args: xdr.ScVal[]
349
- ): Promise<xdr.ScVal | undefined> {
350
- const account = new Account(Keypair.random().publicKey(), '0')
351
- const tx = new TransactionBuilder(account, { fee: BASE_FEE, networkPassphrase })
352
- .addOperation(new Contract(contract).call(method, ...args))
353
- .setTimeout(30)
354
- .build()
355
- const sim = await server.simulateTransaction(tx)
356
- if (rpc.Api.isSimulationError(sim)) return undefined
357
- return sim.result?.retval
358
- }
359
-
360
- return {
361
- async getContextRuleCount(smartAccount) {
362
- const val = await simulateCall(smartAccount, 'get_context_rules_count')
363
- return u32Of(val) ?? 0
364
- },
365
- async getContextRule(smartAccount, ruleId) {
366
- return simulateCall(smartAccount, 'get_context_rule', xdr.ScVal.scvU32(ruleId))
367
- },
368
- async getStoredDoc(interpreter, smartAccount, ruleId) {
369
- const key = docLedgerKey(interpreter, smartAccount, ruleId)
370
- const res = await server.getLedgerEntries(key)
371
- const entry = res.entries?.[0]?.val
372
- if (!entry || entry.switch() !== xdr.LedgerEntryType.contractData()) return undefined
373
- return entry.contractData().val()
374
- },
375
- }
376
- }
package/src/ir/index.ts DELETED
@@ -1,13 +0,0 @@
1
- // src/ir/index.ts - re-export the PolicyIR ("Policy Tree") types.
2
-
3
- export type {
4
- IRCompare,
5
- IRCompOp,
6
- IRCondition,
7
- IRLogic,
8
- IRPolicyRule,
9
- IRScalarType,
10
- IRSelector,
11
- IRVecMode,
12
- PolicyIR,
13
- } from './types.ts'
package/src/ir/types.ts DELETED
@@ -1,132 +0,0 @@
1
- // src/ir/types.ts - the PolicyIR ("Policy Tree").
2
- //
3
- // `PolicyIR` is the custody-agnostic "Policy Tree" hub (the diagram's Policy
4
- // Tree) that every CustodyAdapter compiles FROM. It generalizes the NEAR-V2
5
- // policy schema (roles / scope filter / guard / constraint / comparison leaves /
6
- // default behaviour) into one chain-neutral shape and extends it with the
7
- // OZ-only selectors (spend window, oracle price, invocation count, time) so a
8
- // single IR can serve every backend. NEAR-V2 has no stateful spend window,
9
- // oracle, time/expiry, or invocation-count; those are marked as OZ extensions
10
- // below and are only lowered by adapters that declare support for them.
11
-
12
- /** Comparison operator. Mirrors NEAR-V2 `CompOp`. */
13
- export type IRCompOp = 'eq' | 'lt' | 'lte' | 'gt' | 'gte'
14
-
15
- /** Boolean combinator. Mirrors NEAR-V2 `LogicOp`. */
16
- export type IRLogic = 'and' | 'or'
17
-
18
- /** Vector match mode for a repeated arg. Mirrors NEAR-V2 `VecMode`. */
19
- export type IRVecMode = 'all' | 'any'
20
-
21
- /** Scalar value type. Mirrors NEAR-V2 `ScValType`, superset for OZ. */
22
- export type IRScalarType =
23
- | 'address'
24
- | 'i128'
25
- | 'u128'
26
- | 'u32'
27
- | 'u64'
28
- | 'i64'
29
- | 'symbol'
30
- | 'bytes'
31
- | 'bool'
32
-
33
- /** WHERE in the authorized call a value is read. NEAR-V2 selectors first, OZ
34
- * extensions after (an adapter that cannot express an extension flags it). */
35
- export type IRSelector =
36
- // --- NEAR-V2 selectors ---
37
- | {
38
- kind: 'arg'
39
- argIndex: number
40
- fieldIndex?: number
41
- vecMode?: IRVecMode
42
- scalarType: IRScalarType
43
- } // Stellar StellarComp
44
- | { kind: 'arg_len'; argIndex: number } // length of a vec-typed argument as u32
45
- | {
46
- kind: 'arg_field'
47
- argIndex: number
48
- element: number
49
- field: string
50
- scalarType: IRScalarType
51
- } // field of a map element within a vec-typed argument
52
- | { kind: 'calldata'; offset: number; length: number } // EVM ByteComp
53
- | { kind: 'value' } // EVM tx.value
54
- // --- OZ extensions (not in NEAR-V2; lowered only by adapters that support them) ---
55
- | { kind: 'amount'; token: string } // token amount this call moves
56
- | { kind: 'window_spent'; token: string; windowSeconds: number } // stateful cumulative spend
57
- | { kind: 'invocation_count'; windowSeconds: number }
58
- | { kind: 'now' }
59
- | { kind: 'valid_until' }
60
- | { kind: 'oracle_price'; asset: string }
61
-
62
- /** A single comparison leaf. `value` is a decimal/hex string (i128-safe;
63
- * never a JS number). */
64
- export interface IRCompare {
65
- selector: IRSelector
66
- operator: IRCompOp
67
- value: string
68
- /** Decimal basis of `value`, for selectors whose comparand is not on a basis
69
- * the contract can infer. Set for `oracle_price`, where prices normalise to
70
- * 9 dp and an undeclared basis fails OPEN. */
71
- valueDecimals?: number
72
- }
73
-
74
- /** Condition tree. NEAR-V2 guard/constraint are flat And/Or; the IR allows
75
- * nesting + `not` + `in` + `eq_seq` so the same IR can later lower to the OZ
76
- * predicate DSL. Week-1 adapters only lower the flat supported subset and flag
77
- * the rest. */
78
- export type IRCondition =
79
- | { op: 'and' | 'or'; children: IRCondition[] }
80
- | { op: 'not'; child: IRCondition }
81
- | { op: 'compare'; compare: IRCompare }
82
- | { op: 'in'; selector: IRSelector; values: string[] }
83
- /** Exact ordered sequence equality. The IR-level selector value MUST EQUAL
84
- * `values` as an ORDERED sequence (e.g. a swap hop `path`). `in` is pure
85
- * set membership and cannot express order; `eq_seq` is the construct that
86
- * does. Adapters that cannot express an exact ordered vector (OZ built-ins)
87
- * flag this as `uncovered` rather than silently dropping it. */
88
- | { op: 'eq_seq'; selector: IRSelector; values: string[] }
89
- /** A swap's output floor, expressed against its own input: the output arg
90
- * must be at least `inArgIndex * num / den`.
91
- *
92
- * It is its own construct because `compare` bounds a selector against a
93
- * CONSTANT, and a slippage floor has no constant to bound against - the
94
- * acceptable output depends on the input of the same call. Encoding the
95
- * recorded output as a constant would pin a policy to one trade size.
96
- *
97
- * `num/den` is the caller's minimum acceptable output per unit of input.
98
- * It is never derived from the recording: the recorded rate is a price at
99
- * one moment, and freezing it as policy would deny normal trades later.
100
- * Adapters that cannot express it (the OZ built-ins) flag it `uncovered`. */
101
- | {
102
- op: 'slippage_floor'
103
- outArgIndex: number
104
- inArgIndex: number
105
- num: string
106
- den: string
107
- }
108
-
109
- export interface IRPolicyRule {
110
- /** NEAR-V2 roles whitelist (empty = any; owner exempt). */
111
- roles: string[]
112
- /** NEAR-V2 scope filter; each field optional (absent = wildcard). */
113
- scope: { chainId?: number; contract?: string; method?: string }
114
- /** NEAR-V2 guard (applicability; skip the rule when it fails). */
115
- guard?: IRCondition
116
- /** NEAR-V2 constraint (AND; reject the transaction when any fails). */
117
- constraints: IRCondition[]
118
- // --- OZ extensions ---
119
- /** M-of-N approval (OZ threshold primitives). */
120
- approval?: { kind: 'threshold'; threshold: number; weights?: Record<string, number> }
121
- /** OZ context-rule expiry. */
122
- expiry?: { validUntilLedger?: number; validUntilUnixSeconds?: number }
123
- }
124
-
125
- export interface PolicyIR {
126
- /** NEAR-V2 PolicyChain. */
127
- chain: 'stellar' | 'evm'
128
- /** NEAR-V2 DefaultBehavior. OZ context rules are deny-by-default, so
129
- * `deny_all` is the OZ default fallback when no rule matches. */
130
- defaultBehavior: 'allow_all' | 'deny_all'
131
- rules: IRPolicyRule[]
132
- }
@@ -1,4 +0,0 @@
1
- // src/mandate/index.ts - re-export the Mandate source.
2
-
3
- export { mandateToPolicyIR } from './to-ir.ts'
4
- export type { MandateSpec } from './types.ts'