@crediolabs/policy-synth 0.2.0 → 0.3.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 (184) 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/adapters/interpreter/index.d.ts +1 -1
  5. package/dist/adapters/interpreter/index.js +1 -1
  6. package/dist/adapters/oz/adapter.js +1 -15
  7. package/dist/errors.d.ts +1 -1
  8. package/dist/index.d.ts +1 -4
  9. package/dist/index.js +1 -4
  10. package/dist/install/build-add-context-rule.d.ts +3 -19
  11. package/dist/install/build-add-context-rule.js +3 -98
  12. package/dist/install/build-install-policy.d.ts +4 -53
  13. package/dist/install/build-install-policy.js +44 -123
  14. package/dist/install/index.d.ts +0 -2
  15. package/dist/install/index.js +0 -7
  16. package/dist/ir/index.d.ts +1 -1
  17. package/dist/ir/types.d.ts +7 -76
  18. package/dist/ir/types.js +0 -2
  19. package/dist/predicate/decode.d.ts +1 -1
  20. package/dist/predicate/decode.js +2 -70
  21. package/dist/predicate/encode.js +45 -229
  22. package/dist/predicate/from-json.js +1 -42
  23. package/dist/record/decode.js +3 -8
  24. package/dist/review-card/builder.d.ts +4 -3
  25. package/dist/review-card/builder.js +18 -162
  26. package/dist/review-card/cross-check.js +2 -105
  27. package/dist/review-card/render-leaf.d.ts +4 -0
  28. package/dist/review-card/render-leaf.js +47 -0
  29. package/dist/run/index.d.ts +36 -139
  30. package/dist/run/index.js +125 -437
  31. package/dist/run/schemas.d.ts +168 -1929
  32. package/dist/run/schemas.js +40 -269
  33. package/dist/seams/types.d.ts +0 -2
  34. package/dist/simulate/deny-cases.d.ts +26 -0
  35. package/dist/simulate/deny-cases.js +282 -0
  36. package/dist/simulate/evaluate.d.ts +18 -0
  37. package/dist/simulate/evaluate.js +271 -0
  38. package/dist/simulate/index.d.ts +4 -0
  39. package/dist/simulate/index.js +8 -0
  40. package/dist/synth/compose-from-recording.d.ts +24 -51
  41. package/dist/synth/compose-from-recording.js +120 -282
  42. package/dist/synth/deny-cases.d.ts +5 -7
  43. package/dist/synth/deny-cases.js +23 -373
  44. package/dist/synth/evaluate.d.ts +0 -21
  45. package/dist/synth/evaluate.js +56 -336
  46. package/dist/synth/index.d.ts +0 -5
  47. package/dist/synth/index.js +0 -5
  48. package/dist/synth/permit-context.d.ts +2 -9
  49. package/dist/synth/permit-context.js +1 -82
  50. package/dist/synth/synthesize-from-recording.d.ts +1 -29
  51. package/dist/synth/synthesize-from-recording.js +41 -356
  52. package/dist/types.d.ts +8 -60
  53. package/dist/types.js +5 -2
  54. package/dist/verify/simulate.d.ts +1 -14
  55. package/dist/verify/simulate.js +2 -88
  56. package/dist/verify/verify.d.ts +1 -7
  57. package/dist/verify/verify.js +0 -8
  58. package/dist-cjs/adapters/interpreter/adapter.d.ts +19 -25
  59. package/dist-cjs/adapters/interpreter/adapter.js +56 -489
  60. package/dist-cjs/adapters/interpreter/index.d.ts +1 -1
  61. package/dist-cjs/adapters/interpreter/index.js +1 -2
  62. package/dist-cjs/adapters/oz/adapter.js +1 -15
  63. package/dist-cjs/errors.d.ts +1 -1
  64. package/dist-cjs/index.d.ts +1 -4
  65. package/dist-cjs/index.js +1 -4
  66. package/dist-cjs/install/build-add-context-rule.d.ts +3 -19
  67. package/dist-cjs/install/build-add-context-rule.js +1 -97
  68. package/dist-cjs/install/build-install-policy.d.ts +4 -53
  69. package/dist-cjs/install/build-install-policy.js +44 -122
  70. package/dist-cjs/install/index.d.ts +0 -2
  71. package/dist-cjs/install/index.js +2 -23
  72. package/dist-cjs/ir/index.d.ts +1 -1
  73. package/dist-cjs/ir/types.d.ts +7 -76
  74. package/dist-cjs/ir/types.js +0 -2
  75. package/dist-cjs/predicate/decode.d.ts +1 -1
  76. package/dist-cjs/predicate/decode.js +2 -70
  77. package/dist-cjs/predicate/encode.js +45 -229
  78. package/dist-cjs/predicate/from-json.js +1 -42
  79. package/dist-cjs/record/decode.js +3 -8
  80. package/dist-cjs/review-card/builder.d.ts +4 -3
  81. package/dist-cjs/review-card/builder.js +23 -167
  82. package/dist-cjs/review-card/cross-check.js +7 -110
  83. package/dist-cjs/review-card/render-leaf.d.ts +4 -0
  84. package/dist-cjs/review-card/render-leaf.js +52 -0
  85. package/dist-cjs/run/index.d.ts +36 -139
  86. package/dist-cjs/run/index.js +125 -444
  87. package/dist-cjs/run/schemas.d.ts +168 -1929
  88. package/dist-cjs/run/schemas.js +41 -270
  89. package/dist-cjs/seams/types.d.ts +0 -2
  90. package/dist-cjs/simulate/deny-cases.d.ts +26 -0
  91. package/dist-cjs/simulate/deny-cases.js +286 -0
  92. package/dist-cjs/simulate/evaluate.d.ts +18 -0
  93. package/dist-cjs/simulate/evaluate.js +274 -0
  94. package/dist-cjs/simulate/index.d.ts +4 -0
  95. package/dist-cjs/simulate/index.js +13 -0
  96. package/dist-cjs/synth/compose-from-recording.d.ts +24 -51
  97. package/dist-cjs/synth/compose-from-recording.js +120 -282
  98. package/dist-cjs/synth/deny-cases.d.ts +5 -7
  99. package/dist-cjs/synth/deny-cases.js +23 -374
  100. package/dist-cjs/synth/evaluate.d.ts +0 -21
  101. package/dist-cjs/synth/evaluate.js +57 -337
  102. package/dist-cjs/synth/index.d.ts +0 -5
  103. package/dist-cjs/synth/index.js +1 -11
  104. package/dist-cjs/synth/permit-context.d.ts +2 -9
  105. package/dist-cjs/synth/permit-context.js +1 -82
  106. package/dist-cjs/synth/synthesize-from-recording.d.ts +1 -29
  107. package/dist-cjs/synth/synthesize-from-recording.js +39 -354
  108. package/dist-cjs/types.d.ts +8 -60
  109. package/dist-cjs/types.js +6 -3
  110. package/dist-cjs/verify/simulate.d.ts +1 -14
  111. package/dist-cjs/verify/simulate.js +2 -88
  112. package/dist-cjs/verify/verify.d.ts +1 -7
  113. package/dist-cjs/verify/verify.js +0 -8
  114. package/package.json +4 -4
  115. package/src/adapters/interpreter/adapter.ts +76 -572
  116. package/src/errors.ts +0 -19
  117. package/src/index.ts +1 -4
  118. package/src/install/build-add-context-rule.ts +5 -139
  119. package/src/install/build-install-policy.ts +93 -214
  120. package/src/install/index.ts +0 -34
  121. package/src/predicate/decode.ts +2 -70
  122. package/src/predicate/encode.ts +49 -261
  123. package/src/predicate/from-json.ts +1 -43
  124. package/src/record/decode.ts +3 -8
  125. package/src/review-card/builder.ts +19 -168
  126. package/src/review-card/cross-check.ts +3 -105
  127. package/src/review-card/render-leaf.ts +48 -0
  128. package/src/run/index.ts +144 -572
  129. package/src/run/schemas.ts +42 -291
  130. package/src/simulate/deny-cases.ts +334 -0
  131. package/src/simulate/evaluate.ts +284 -0
  132. package/src/simulate/index.ts +11 -0
  133. package/src/synth/compose-from-recording.ts +148 -347
  134. package/src/synth/index.ts +0 -13
  135. package/src/synth/synthesize-from-recording.ts +43 -456
  136. package/src/types.ts +13 -49
  137. package/dist/install/authority-overlap.d.ts +0 -134
  138. package/dist/install/authority-overlap.js +0 -0
  139. package/dist/install/build-install-predicate.d.ts +0 -96
  140. package/dist/install/build-install-predicate.js +0 -444
  141. package/dist/install/build-merge-policy.d.ts +0 -70
  142. package/dist/install/build-merge-policy.js +0 -130
  143. package/dist/install/plan-merge-policy.d.ts +0 -49
  144. package/dist/install/plan-merge-policy.js +0 -86
  145. package/dist/install/read-account-rules.d.ts +0 -100
  146. package/dist/install/read-account-rules.js +0 -283
  147. package/dist-cjs/install/authority-overlap.d.ts +0 -134
  148. package/dist-cjs/install/authority-overlap.js +0 -0
  149. package/dist-cjs/install/build-install-predicate.d.ts +0 -96
  150. package/dist-cjs/install/build-install-predicate.js +0 -479
  151. package/dist-cjs/install/build-merge-policy.d.ts +0 -70
  152. package/dist-cjs/install/build-merge-policy.js +0 -134
  153. package/dist-cjs/install/plan-merge-policy.d.ts +0 -49
  154. package/dist-cjs/install/plan-merge-policy.js +0 -90
  155. package/dist-cjs/install/read-account-rules.d.ts +0 -100
  156. package/dist-cjs/install/read-account-rules.js +0 -296
  157. package/src/adapters/interpreter/index.ts +0 -8
  158. package/src/adapters/oz/adapter.ts +0 -376
  159. package/src/adapters/oz/index.ts +0 -9
  160. package/src/codegen/compile-gate.ts +0 -167
  161. package/src/codegen/index.ts +0 -17
  162. package/src/codegen/template.ts +0 -165
  163. package/src/install/authority-overlap.ts +0 -0
  164. package/src/install/build-merge-policy.ts +0 -219
  165. package/src/install/plan-merge-policy.ts +0 -133
  166. package/src/install/read-account-rules.ts +0 -376
  167. package/src/ir/index.ts +0 -13
  168. package/src/ir/types.ts +0 -132
  169. package/src/mandate/index.ts +0 -4
  170. package/src/mandate/to-ir.ts +0 -71
  171. package/src/mandate/types.ts +0 -21
  172. package/src/seams/index.ts +0 -11
  173. package/src/seams/types.ts +0 -81
  174. package/src/synth/deny-cases.ts +0 -663
  175. package/src/synth/evaluate.ts +0 -613
  176. package/src/synth/harness.ts +0 -68
  177. package/src/synth/minimize.ts +0 -48
  178. package/src/synth/permit-context.ts +0 -136
  179. package/src/synth/predicate-literals.ts +0 -27
  180. package/src/synth/synthesize-from-mandate.ts +0 -82
  181. package/src/verify/envelope.ts +0 -28
  182. package/src/verify/index.ts +0 -5
  183. package/src/verify/simulate.ts +0 -311
  184. package/src/verify/verify.ts +0 -243
@@ -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'
@@ -1,71 +0,0 @@
1
- // src/mandate/to-ir.ts - deterministic lowering of a MandateSpec to a PolicyIR.
2
- //
3
- // `mandateToPolicyIR` is pure and total: the same spec always lowers to a
4
- // byte-identical PolicyIR. No decoding, no inference, no clock. Each mandate
5
- // field maps to exactly one IR construct:
6
- // contract/method -> rule.scope
7
- // spendingLimit -> a `window_spent(token,window) <= limit` compare
8
- // approvalThreshold-> rule.approval.threshold
9
- // recipients -> an `in` condition on the recipient arg (flagged as not
10
- // covered by the OZ adapter; that is expected)
11
- // expiry -> rule.expiry
12
- // The top-level default is `deny_all` (OZ context rules are deny-by-default).
13
-
14
- import type { IRCondition, IRPolicyRule, IRSelector, PolicyIR } from '../ir/types.ts'
15
- import type { MandateSpec } from './types.ts'
16
-
17
- /** Arg index the recipient allowlist constrains. Pinned to the SEP-41
18
- * `transfer(from, to, amount)` convention where `to` is arg 1. This condition
19
- * is flagged as not covered by the OZ adapter (no built-in primitive expresses
20
- * an arg allowlist), so the index only needs to be deterministic in week-1. */
21
- const RECIPIENT_ARG_INDEX = 1
22
-
23
- export function mandateToPolicyIR(spec: MandateSpec): PolicyIR {
24
- const scope: IRPolicyRule['scope'] = { contract: spec.contract }
25
- if (spec.method !== undefined) scope.method = spec.method
26
-
27
- const constraints: IRCondition[] = []
28
-
29
- if (spec.spendingLimit) {
30
- constraints.push({
31
- op: 'compare',
32
- compare: {
33
- selector: {
34
- kind: 'window_spent',
35
- token: spec.spendingLimit.token,
36
- windowSeconds: spec.spendingLimit.windowSeconds,
37
- },
38
- operator: 'lte',
39
- value: spec.spendingLimit.limit,
40
- },
41
- })
42
- }
43
-
44
- if (spec.recipients && spec.recipients.length > 0) {
45
- const selector: IRSelector = {
46
- kind: 'arg',
47
- argIndex: RECIPIENT_ARG_INDEX,
48
- scalarType: 'address',
49
- }
50
- constraints.push({ op: 'in', selector, values: [...spec.recipients] })
51
- }
52
-
53
- const rule: IRPolicyRule = { roles: [], scope, constraints }
54
-
55
- if (spec.approvalThreshold !== undefined) {
56
- rule.approval = { kind: 'threshold', threshold: spec.approvalThreshold }
57
- }
58
-
59
- if (spec.expiry) {
60
- const expiry: NonNullable<IRPolicyRule['expiry']> = {}
61
- if (spec.expiry.validUntilLedger !== undefined) {
62
- expiry.validUntilLedger = spec.expiry.validUntilLedger
63
- }
64
- if (spec.expiry.validUntilUnixSeconds !== undefined) {
65
- expiry.validUntilUnixSeconds = spec.expiry.validUntilUnixSeconds
66
- }
67
- rule.expiry = expiry
68
- }
69
-
70
- return { chain: spec.chain, defaultBehavior: 'deny_all', rules: [rule] }
71
- }
@@ -1,21 +0,0 @@
1
- // src/mandate/types.ts - the deterministic Mandate source.
2
- //
3
- // A MandateSpec is a declarative policy statement: "this account may call this
4
- // contract, spending at most L per window, requiring M approvals, to these
5
- // recipients, until this expiry". It carries NO transaction to decode, NO
6
- // parseConfidence, and NO inference - it lowers deterministically to a
7
- // PolicyIR. It is the clean end-to-end demo path, co-equal with the recorder.
8
-
9
- export interface MandateSpec {
10
- chain: 'stellar'
11
- contract: string
12
- method?: string
13
- /** -> OZ `spending_limit` primitive. `limit` is an i128 decimal string. */
14
- spendingLimit?: { token: string; limit: string; windowSeconds: number }
15
- /** -> OZ `simple_threshold` / `weighted_threshold` primitive. */
16
- approvalThreshold?: number
17
- /** Recipient allowlist -> an `in` arg condition (not covered by an OZ built-in). */
18
- recipients?: string[]
19
- /** -> OZ context-rule expiry. */
20
- expiry?: { validUntilLedger?: number; validUntilUnixSeconds?: number }
21
- }
@@ -1,11 +0,0 @@
1
- // src/seams/index.ts - re-export the three custody-seam contracts.
2
-
3
- export type {
4
- ChainDecoder,
5
- CompileResult,
6
- CustodyAdapter,
7
- CustodyCapabilities,
8
- CustodyMode,
9
- PolicySource,
10
- SimulationResult,
11
- } from './types.ts'