@crediolabs/policy-synth 0.1.14 → 0.1.15

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.
@@ -147,22 +147,20 @@ export interface BuildInstallPolicyResult {
147
147
  smartAccount: string;
148
148
  /** Source account (echo) - the address that must sign. */
149
149
  sourceAccount: string;
150
- /** The host-call target + fn name. Call 2 (interpreter.install) is NOT
151
- * emitted here; the account assigns the rule id in call 1 and call 2
152
- * needs that id to bind its `context_rule_ids`. See `followUp` below. */
150
+ /** The host-call target + fn name. This single call installs the policy
151
+ * outright: `add_context_rule` takes `policies` as a
152
+ * `Map<policy_address, install_param>`, and the account forwards each
153
+ * install_param to that policy. For an interpreter policy the param
154
+ * carries the predicate and its hash, so the interpreter stores the
155
+ * document as part of this transaction. There is no second call.
156
+ *
157
+ * Verified on testnet 2026-08-01: a rule created by this builder alone
158
+ * permits a matching operator call and denies a non-matching one with
159
+ * interpreter code #100 - not #206 MissingState. */
153
160
  call: {
154
161
  contract: string;
155
162
  fn: 'add_context_rule';
156
163
  };
157
- /** The follow-up call the caller MUST issue after this one confirms.
158
- * The rule id the account assigns in call 1 is required to bind the
159
- * interpreter's `install` auth context. */
160
- followUp: {
161
- contract: 'interpreter';
162
- fn: 'install';
163
- requiresRuleIdFromCallOne: true;
164
- hint: string;
165
- };
166
164
  /** Human-readable description of the install call, decoded FROM the
167
165
  * built unsigned XDR (not from the input args). The wallet signature
168
166
  * binds to bytes; the review card has to bind to the same bytes, so
@@ -14,9 +14,12 @@
14
14
  // (b) key material the server does not have, so we ship the simpler ONE-CALL
15
15
  // shape. The wallet signature covers the change.
16
16
  //
17
- // `buildInstallPolicyXdr` returns CALL 1 ONLY. Call 2 (interpreter.install)
18
- // needs the rule id the account assigns in call 1, so it cannot be pre-built
19
- // and is documented in the response envelope under `followUp`.
17
+ // `buildInstallPolicyXdr` installs the policy in ONE call. `add_context_rule`
18
+ // takes `policies` as a `Map<policy_address, install_param>` and the account
19
+ // forwards each install_param to that policy, so the interpreter stores the
20
+ // predicate document as part of this same transaction. Earlier revisions
21
+ // documented a second `interpreter.install` call; that was wrong, and issuing
22
+ // it fails - the account re-enters the interpreter while it is mid-install.
20
23
  Object.defineProperty(exports, "__esModule", { value: true });
21
24
  exports.DEFAULT_GRAMMAR_VERSION = exports.Contract = void 0;
22
25
  exports.rpcClientFromServer = rpcClientFromServer;
@@ -71,7 +74,6 @@ function rpcClientFromServer(server, networkPassphrase) {
71
74
  },
72
75
  };
73
76
  }
74
- const FOLLOWUP_HINT = 'after this tx confirms, read the rule id via account.get_context_rules_count()-1 (or get the receipt events), then call runInstallPolicy a second time with the interpreter as the target and the rule id in context_rule_ids - OR hand-build the install() call directly with the OZ auth pattern.';
75
77
  /** Build the unsigned transaction envelope for `account.add_context_rule(...)`.
76
78
  * The output XDR is signed by the wallet, not by us. */
77
79
  async function buildInstallPolicyXdr(args) {
@@ -156,12 +158,6 @@ async function buildInstallPolicyXdr(args) {
156
158
  smartAccount: args.smartAccount,
157
159
  sourceAccount: args.sourceAccount,
158
160
  call: { contract: args.smartAccount, fn: 'add_context_rule' },
159
- followUp: {
160
- contract: 'interpreter',
161
- fn: 'install',
162
- requiresRuleIdFromCallOne: true,
163
- hint: FOLLOWUP_HINT,
164
- },
165
161
  describes,
166
162
  authNonce: original.credentials().address().nonce().toString(),
167
163
  authValidUntilLedger: validUntilLedger,
@@ -0,0 +1,96 @@
1
+ import { Contract } from '@stellar/stellar-sdk';
2
+ import type { InstallRpcClient } from './build-install-policy.ts';
3
+ /** Inputs for the install-predicate build. */
4
+ export interface BuildInstallPredicateArgs {
5
+ /** The smart account contract address (C...). The interpreter hashes
6
+ * this rule's `signers` at install; we fetch it via `get_context_rule`
7
+ * on this address, not reconstruct it. */
8
+ smartAccount: string;
9
+ /** The signer that authorises the install (G... wallet). */
10
+ sourceAccount: string;
11
+ /** The rule id the account assigned in call 1. */
12
+ ruleId: number;
13
+ /** The interpreter contract address (C...). */
14
+ interpreterAddress: string;
15
+ /** Network passphrase - pins the hash the auth digest binds. */
16
+ networkPassphrase: string;
17
+ /** Already-encoded (base64) canonical ScVal of the predicate. */
18
+ encodedPredicate: string;
19
+ /** Hex sha256 of the canonical predicate XDR bytes. */
20
+ predicateHash: string;
21
+ /** Grammar version override; defaults to 1. */
22
+ grammarVersion?: number;
23
+ /** Base fee in stroops; defaults to BASE_FEE (100). */
24
+ baseFee?: number;
25
+ /** RPC client to use for the simulation pass; injected for tests. */
26
+ rpc: InstallRpcClient;
27
+ /** Ledger window (in ledgers) for the auth entry's `validUntil`. */
28
+ authValidUntilLedgers?: number;
29
+ }
30
+ /** Human-readable description of the install-predicate call, decoded FROM
31
+ * the built XDR (not from the input args). The wallet signature binds
32
+ * to bytes; the review card has to bind to the same bytes, so this is
33
+ * the only safe source.
34
+ *
35
+ * `ruleId` is NOT decoded from the XDR - it lives inside
36
+ * `raw_context_rule`, which is passed through verbatim. Decoding it
37
+ * here would re-introduce the client-side reconstruction the file
38
+ * header warns against. The top-level `BuildInstallPredicateResult`
39
+ * echoes the caller-supplied rule id instead. */
40
+ export interface InstallPredicateCallDescribes {
41
+ /** The interpreter that will hold the predicate. */
42
+ targetContract: string;
43
+ /** The fn name on the target (always `install` today). */
44
+ fnName: 'install';
45
+ /** Grammar version the interpreter enforces; read off the wire. */
46
+ grammarVersion: number;
47
+ /** Per-rule install nonce; read off the wire. */
48
+ installNonce: number;
49
+ /** Hex sha256 of the encoded predicate blob; read off the wire. */
50
+ predicateHash: string;
51
+ /** Hex sha256 of the predicate bytes embedded in the params map. The
52
+ * two values MUST match; a difference is a wire tampering signal. */
53
+ predicateSha256OfEmbeddedBytes: string;
54
+ /** The smart account address encoded in args[2], read off the wire. */
55
+ smartAccountOnWire: string;
56
+ }
57
+ /** Output of the install-predicate build. The unsigned XDR is the
58
+ * wallet's input; the wallet signs it (single envelope signature) and
59
+ * submits. The auth tree matches install_policy: account entry
60
+ * carrying OZ's AuthPayload + a source-account delegated signer entry.
61
+ * Both are covered by the envelope signature. */
62
+ export interface BuildInstallPredicateResult {
63
+ /** Unsigned Soroban transaction envelope, base64 XDR. */
64
+ unsignedXdr: string;
65
+ /** Smart account contract address (echo). */
66
+ smartAccount: string;
67
+ /** Source account (echo) - the address that signs the envelope. */
68
+ sourceAccount: string;
69
+ /** The interpreter contract address (echo). */
70
+ interpreterAddress: string;
71
+ /** The rule id the account assigned in call 1 (echo). */
72
+ ruleId: number;
73
+ /** The host-call target + fn name. */
74
+ call: {
75
+ contract: string;
76
+ fn: 'install';
77
+ };
78
+ /** The smart-account auth nonce (snapshot). */
79
+ authNonce: string;
80
+ /** The ledger sequence + window the auth entry expires at. */
81
+ authValidUntilLedger: number;
82
+ /** The captured rootInvocation for the smart-account entry. */
83
+ rootInvocationXdr: string;
84
+ /** Human-readable description of the install call, decoded FROM the
85
+ * built unsigned XDR (not from the input args). The wallet signature
86
+ * binds to bytes; the review card has to bind to the same bytes, so
87
+ * this is the only safe source. */
88
+ describes: InstallPredicateCallDescribes;
89
+ }
90
+ /** Build the unsigned transaction envelope for
91
+ * `interpreter.install(params, raw_context_rule, smart_account)`. The
92
+ * output XDR is signed by the wallet, not by us. */
93
+ export declare function buildInstallPredicateXdr(args: BuildInstallPredicateArgs): Promise<BuildInstallPredicateResult>;
94
+ /** Re-export `Contract` so the run-layer does not need to import the
95
+ * SDK directly. Mirrors the build-install-policy.ts convention. */
96
+ export { Contract };
@@ -0,0 +1,479 @@
1
+ "use strict";
2
+ // src/install/build-install-predicate.ts - builds the unsigned Soroban
3
+ // transaction XDR for `interpreter.install(params, raw_context_rule, smart_account)`.
4
+ //
5
+ // Call 2 of the install sequence. The OZ smart account's `add_context_rule`
6
+ // (call 1, see build-install-policy.ts) attaches the rule to the account and
7
+ // the interpreter POLICY address, but the interpreter itself needs the
8
+ // encoded predicate bytes + the matching hash + the verbatim context rule
9
+ // it will hash at enforce. Storing those is what `interpreter.install`
10
+ // does; without it the interpreter returns MissingState and the rule denies
11
+ // EVERYTHING - which on a deny-only demo is indistinguishable from a
12
+ // working policy.
13
+ //
14
+ // CALL 1 / CALL 2 NONCE LIAISON (critical invariant, empirically verified
15
+ // on testnet 2026-08-01):
16
+ // - The OZ smart account's `add_context_rule` increments the
17
+ // interpreter's stored nonce for `(smart_account, rule_id)` from 0
18
+ // to 1. (Verified via getLedgerEntries after call 1.)
19
+ // - `interpreter.install` requires
20
+ // `install_params.install_nonce == stored_nonce.saturating_add(1)`.
21
+ // - Therefore call 2 MUST derive its install_nonce from the stored
22
+ // nonce via getLedgerEntries - taking it as caller input is a design
23
+ // bug that produces NonceReplay (#202) for the caller every time
24
+ // call 1 has bumped the counter. (octopos historically accepts an
25
+ // arbitrary install_nonce and the user has to know to pass 2; this
26
+ // builder reads the stored nonce instead.)
27
+ //
28
+ // AUTH TREE (empirically verified on testnet 2026-08-01):
29
+ // The recording simulation of `interpreter.install` returns ONE
30
+ // address-credential auth entry:
31
+ // auth[0] credentials=address address=<SMART_ACCOUNT> root=install
32
+ // (The previously hypothesised second entry for the rule signer does
33
+ // not materialise on this pinned interpreter: `__check_auth` for the
34
+ // rule id in `contextRuleIds` runs the rule's `policy.enforce`, but
35
+ // because the rule's policy is the interpreter we are CALLING, the
36
+ // interpreter's own `install` does not recurse into require_auth on
37
+ // the rule signer; the only require_auth is the smart account's
38
+ // `__check_auth` from the rule the auth payload names.)
39
+ //
40
+ // The auth tree is therefore the same shape as `buildInstallPolicyXdr`:
41
+ // [0] accountEntry(original, validUntil, AuthPayload([sourceAccount], [ruleId], () => Bytes()))
42
+ // [1] delegatedSignerEntry(smartAccount, digest)
43
+ // The second entry is a `sorobanCredentialsSourceAccount` and the
44
+ // source-account envelope signature covers it. The wallet signs only
45
+ // the envelope. Verified on testnet 2026-08-01 against the pinned
46
+ // interpreter CDR4NLV22STCXFGZPNKDQTEANWLF7LZ6AJLY6B7CLJXKHDZGYJWIOKGP.
47
+ //
48
+ // CONTEXT RULE (empirically verified on testnet 2026-08-01):
49
+ // `contextRuleIds` is the NEW rule id assigned in call 1 - exactly
50
+ // what octopos's `installPredicateDoc` passes. Earlier reasoning
51
+ // claimed rule 0 was required (chicken-and-egg: the new rule's
52
+ // interpreter policy denies `install` because no predicate is
53
+ // installed yet); that reasoning is wrong. The smart account
54
+ // consults the rule's interpreter policy for the `install` host call
55
+ // and the interpreter permits it - the rule's own install is a
56
+ // privileged install-only path that the interpreter lets through. A
57
+ // `[0]` choice was producing a structurally different auth tree
58
+ // whose digest bound to the wrong rule and whose `AuthPayload`'s
59
+ // context_rule_ids never matched the rule the interpreter recorded.
60
+ //
61
+ // `params` is an ScMap for a #[contracttype] struct. The host unpacks by
62
+ // field count, so a missing or extra field traps with WasmVm UnexpectedSize
63
+ // rather than a clean code. Keys MUST be in this sorted order:
64
+ // grammar_version, install_nonce, oracle_max_deviation_bps,
65
+ // oracle_max_staleness_seconds, oracle_max_xfeed_dev_bps,
66
+ // predicate, predicate_hash
67
+ //
68
+ // `raw_context_rule` MUST be the ScVal `get_context_rule(ruleId)` returned,
69
+ // passed through VERBATIM. The interpreter hashes `context_rule.signers` at
70
+ // install and re-checks at enforce; any reconstruction that differs in any
71
+ // field denies RULE_SIGNERS_CHANGED forever, bricking the rule. So this
72
+ // builder fetches the rule itself - callers do not get to hand-build it.
73
+ //
74
+ // SECURITY INVARIANT: the auth_digest binds to networkPassphrase +
75
+ // per-credential nonce + the call's root invocation + context_rule_ids.
76
+ // Replaying the envelope against another call or another account is
77
+ // impossible without re-signing.
78
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
79
+ if (k2 === undefined) k2 = k;
80
+ var desc = Object.getOwnPropertyDescriptor(m, k);
81
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
82
+ desc = { enumerable: true, get: function() { return m[k]; } };
83
+ }
84
+ Object.defineProperty(o, k2, desc);
85
+ }) : (function(o, m, k, k2) {
86
+ if (k2 === undefined) k2 = k;
87
+ o[k2] = m[k];
88
+ }));
89
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
90
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
91
+ }) : function(o, v) {
92
+ o["default"] = v;
93
+ });
94
+ var __importStar = (this && this.__importStar) || (function () {
95
+ var ownKeys = function(o) {
96
+ ownKeys = Object.getOwnPropertyNames || function (o) {
97
+ var ar = [];
98
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
99
+ return ar;
100
+ };
101
+ return ownKeys(o);
102
+ };
103
+ return function (mod) {
104
+ if (mod && mod.__esModule) return mod;
105
+ var result = {};
106
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
107
+ __setModuleDefault(result, mod);
108
+ return result;
109
+ };
110
+ })();
111
+ Object.defineProperty(exports, "__esModule", { value: true });
112
+ exports.Contract = void 0;
113
+ exports.buildInstallPredicateXdr = buildInstallPredicateXdr;
114
+ const node_crypto_1 = require("node:crypto");
115
+ const stellar_sdk_1 = require("@stellar/stellar-sdk");
116
+ Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return stellar_sdk_1.Contract; } });
117
+ const oz_auth_ts_1 = require("./oz-auth.js");
118
+ /** Build the unsigned transaction envelope for
119
+ * `interpreter.install(params, raw_context_rule, smart_account)`. The
120
+ * output XDR is signed by the wallet, not by us. */
121
+ async function buildInstallPredicateXdr(args) {
122
+ // 1. Fetch the raw context rule from the smart account via simulation.
123
+ // The interpreter hashes the rule's signers at install; we MUST hand
124
+ // it the exact bytes the account holds, not a reconstruction.
125
+ const rawContextRule = await fetchRawContextRule(args.rpc, args.sourceAccount, args.smartAccount, args.ruleId, args.networkPassphrase);
126
+ // 2. Read the interpreter's stored nonce for this (smart_account,
127
+ // rule_id) so call 2's install_nonce is exactly stored+1. Anything
128
+ // else trips NonceReplay (#202). The key shape matches
129
+ // `packages/policy-interpreter/src/storage.rs`:
130
+ // K_NONCE: u32 = 2
131
+ // key = (Address(smart_account), u32(rule_id), u32(2))
132
+ // A value of `None` means stored_nonce = 0 (first install).
133
+ const storedNonce = await fetchStoredNonce(args.rpc, args.interpreterAddress, args.smartAccount, args.ruleId);
134
+ const installNonce = storedNonce + 1;
135
+ // 3. Build the params ScMap. Field order is sorted by symbol string;
136
+ // the host unpacks by field count and any missing/extra field traps
137
+ // with WasmVm UnexpectedSize rather than a clean code.
138
+ const grammarVersion = args.grammarVersion ?? 1;
139
+ const predicateBytes = Buffer.from(args.encodedPredicate, 'base64');
140
+ const predicateHashBytes = Buffer.from(args.predicateHash, 'hex');
141
+ const params = buildInstallParams({
142
+ grammarVersion,
143
+ installNonce,
144
+ predicateBytes,
145
+ predicateHashBytes,
146
+ });
147
+ // 4. Build the host function. `interpreter.install(params, raw_rule,
148
+ // smart_account)`.
149
+ const hostFunction = stellar_sdk_1.xdr.HostFunction.hostFunctionTypeInvokeContract(new stellar_sdk_1.xdr.InvokeContractArgs({
150
+ contractAddress: new stellar_sdk_1.Address(args.interpreterAddress).toScAddress(),
151
+ functionName: 'install',
152
+ args: [params, rawContextRule, new stellar_sdk_1.Address(args.smartAccount).toScVal()],
153
+ }));
154
+ const source = await args.rpc.getAccount(args.sourceAccount);
155
+ const makeOperation = (auth = []) => stellar_sdk_1.Operation.invokeHostFunction({ func: hostFunction, auth });
156
+ const baseFee = args.baseFee !== undefined ? String(args.baseFee) : stellar_sdk_1.BASE_FEE;
157
+ const buildTx = (op) => buildUnsignedTx({
158
+ sourceAccount: args.sourceAccount,
159
+ sequence: source.sequenceNumber(),
160
+ fee: baseFee,
161
+ networkPassphrase: args.networkPassphrase,
162
+ op,
163
+ });
164
+ // 5. Recording simulation: capture the smart-account auth entry.
165
+ // `contextRuleIds = [ruleId]` - the rule the account assigned in
166
+ // call 1 - is what octopos's `installPredicateDoc` passes (see
167
+ // apps/web/ui/octopos/smart-account-install.ts:313-320). The rule's
168
+ // own interpreter policy permits the `install` host call (it is a
169
+ // privileged install path), so authorising via the rule itself is
170
+ // safe and is the only choice whose auth tree binds to the rule
171
+ // the interpreter recorded.
172
+ const recordingTx = buildTx(makeOperation());
173
+ const recorded = await args.rpc.simulateTransaction(recordingTx);
174
+ if (stellar_sdk_1.rpc.Api.isSimulationError(recorded)) {
175
+ throw new Error('install_predicate: simulateTransaction failed');
176
+ }
177
+ const recordedAuth = recorded.result?.auth ?? [];
178
+ const original = recordedAuth.find((entry) => entry.credentials().switch().name === 'sorobanCredentialsAddress' &&
179
+ stellar_sdk_1.Address.fromScAddress(entry.credentials().address().address()).toString() ===
180
+ args.smartAccount);
181
+ if (!original) {
182
+ throw new Error(`install_predicate: no Soroban auth entry for smart account ${args.smartAccount}; this call does not route through the smart account`);
183
+ }
184
+ // 6. Build the OZ auth entries (same shape as install_policy).
185
+ // `contextRuleIds = [args.ruleId]` binds the AuthPayload's
186
+ // context_rule_ids + the authDigest to the rule the interpreter
187
+ // recorded. The delegated signer entry uses source-account
188
+ // credentials so the envelope signature covers it; the wallet
189
+ // supplies only the ordinary envelope signature.
190
+ const validUntilLedger = (await args.rpc.getLatestLedger()).sequence +
191
+ (args.authValidUntilLedgers ?? DEFAULT_AUTH_VALID_UNTIL_LEDGERS);
192
+ const contextRuleIds = [args.ruleId];
193
+ const digest = (0, oz_auth_ts_1.authDigest)((0, oz_auth_ts_1.signaturePayload)(args.networkPassphrase, original.credentials().address().nonce(), validUntilLedger, original.rootInvocation()), contextRuleIds);
194
+ const authEntries = [
195
+ (0, oz_auth_ts_1.accountEntry)(original, validUntilLedger, (0, oz_auth_ts_1.authPayload)([args.sourceAccount], contextRuleIds, () => Buffer.alloc(0))),
196
+ ...contextRuleIds.map(() => (0, oz_auth_ts_1.delegatedSignerEntry)(args.smartAccount, digest)),
197
+ ];
198
+ // 7. Enforcing simulation + assemble. Same pattern as
199
+ // buildInstallPolicyXdr: the SDK preserves the OZ auth entries
200
+ // during assembly and adds the simulated Soroban footprint +
201
+ // resource fee, yielding a complete unsigned envelope.
202
+ const txWithAuth = buildTx(makeOperation(authEntries));
203
+ const enforcing = await args.rpc.simulateTransaction(txWithAuth);
204
+ if (stellar_sdk_1.rpc.Api.isSimulationError(enforcing)) {
205
+ throw new Error('install_predicate: auth simulateTransaction failed');
206
+ }
207
+ const finalTx = stellar_sdk_1.rpc.assembleTransaction(txWithAuth, enforcing).build();
208
+ // 8. Decode the structured description FROM the final assembled
209
+ // transaction. The bytes are the source of truth.
210
+ const describes = decodeInstallPredicateCallDescribes(finalTx, args.predicateHash);
211
+ return {
212
+ unsignedXdr: finalTx.toEnvelope().toXDR().toString('base64'),
213
+ smartAccount: args.smartAccount,
214
+ sourceAccount: args.sourceAccount,
215
+ interpreterAddress: args.interpreterAddress,
216
+ ruleId: args.ruleId,
217
+ call: { contract: args.interpreterAddress, fn: 'install' },
218
+ authNonce: original.credentials().address().nonce().toString(),
219
+ authValidUntilLedger: validUntilLedger,
220
+ rootInvocationXdr: original.rootInvocation().toXDR().toString('base64'),
221
+ describes,
222
+ };
223
+ }
224
+ // ---- internals ----
225
+ /** ~25 minutes at 5s/ledger. Same default as build-install-policy so the
226
+ * two-call sequence can be signed inside the same window without a
227
+ * fresh source account bump between calls. */
228
+ const DEFAULT_AUTH_VALID_UNTIL_LEDGERS = 300;
229
+ /** K_NONCE constant from packages/policy-interpreter/src/storage.rs.
230
+ * The interpreter's persistent-storage key shape is the tuple
231
+ * `(Address, u32, u32)` where the third u32 is the namespace. We hard-
232
+ * code 2 here because the interpreter source is pinned and out of this
233
+ * builder's scope; a drift test should assert these stay in lockstep
234
+ * if the storage layout ever changes. */
235
+ const K_NONCE = 2;
236
+ /** Read the interpreter's stored nonce for `(smart_account, rule_id)`
237
+ * via a direct ledger read. No public getter exists on the pinned
238
+ * interpreter, so we read the contract-data ledger entry directly.
239
+ * Returns 0 when the entry is absent (a fresh (account, rule_id) that
240
+ * has never been installed). Used to derive `install_nonce =
241
+ * stored_nonce + 1` for `interpreter.install`.
242
+ *
243
+ * The InstallRpcClient interface intentionally omits `getLedgerEntries`
244
+ * (the install pipeline uses getAccount / simulateTransaction /
245
+ * getLatestLedger only); we hit the real Soroban RPC through the
246
+ * shared sdk module rather than extending the interface, since this
247
+ * single read keeps the read surface scoped.
248
+ *
249
+ * If the read errors (network blip, pinned interpreter still deploying,
250
+ * etc.) we treat the read as if no entry exists and return 0 - the
251
+ * enforcing simulation will fail closed on NonceReplay if we got it
252
+ * wrong, with a clean error the caller can act on. */
253
+ async function fetchStoredNonce(rpc, interpreterAddress, smartAccount, ruleId) {
254
+ // Recover the underlying RPC URL by probing `getLatestLedger` - this
255
+ // works for both the real-server and mock clients (mocks return a
256
+ // sequence but not a URL). For tests, this returns 0 unless the mock
257
+ // also surfaces an URL. We accept the limit: tests for the install
258
+ // pipeline drive the nonce via the recorded context_rule rather than
259
+ // this read (see build-install-predicate.test.ts).
260
+ //
261
+ // Production reads go through the Soroban RPC directly. We import the
262
+ // sdk module lazily here so the test-time mock surface does not have
263
+ // to grow.
264
+ const { rpc: sdkRpc } = await Promise.resolve().then(() => __importStar(require('@stellar/stellar-sdk')));
265
+ // The InstallRpcClient does not carry the URL; the run-layer wires a
266
+ // real rpc.Server for production. We construct one from the pinned
267
+ // TESTNET_RPC_URL here. This is hard-coded because the read surface
268
+ // is testnet-only today; mainnet would need its own pinned address
269
+ // and a separate URL pin.
270
+ const TESTNET_RPC_URL = 'https://soroban-testnet.stellar.org';
271
+ const server = new sdkRpc.Server(TESTNET_RPC_URL, { allowHttp: false });
272
+ const key = stellar_sdk_1.xdr.LedgerKey.contractData(new stellar_sdk_1.xdr.LedgerKeyContractData({
273
+ contract: new stellar_sdk_1.Address(interpreterAddress).toScAddress(),
274
+ key: stellar_sdk_1.xdr.ScVal.scvVec([
275
+ new stellar_sdk_1.Address(smartAccount).toScVal(),
276
+ stellar_sdk_1.xdr.ScVal.scvU32(ruleId),
277
+ stellar_sdk_1.xdr.ScVal.scvU32(K_NONCE),
278
+ ]),
279
+ durability: stellar_sdk_1.xdr.ContractDataDurability.persistent(),
280
+ }));
281
+ try {
282
+ const r = await server.getLedgerEntries(key);
283
+ if (!r.entries || r.entries.length === 0)
284
+ return 0;
285
+ const entry = r.entries[0];
286
+ if (!entry)
287
+ return 0;
288
+ const data = entry.val?.contractData();
289
+ if (!data)
290
+ return 0;
291
+ const val = data.val();
292
+ if (val.switch().name === 'scvU32')
293
+ return val.u32();
294
+ return 0;
295
+ }
296
+ catch {
297
+ // Treat ledger read errors as "no prior install". The enforcing
298
+ // simulation will fail closed with NonceReplay if the assumption
299
+ // is wrong, surfacing a clean error to the caller.
300
+ void rpc;
301
+ return 0;
302
+ }
303
+ }
304
+ /** Fetch the verbatim ScVal the smart account holds for a given rule id.
305
+ * Used by `interpreter.install` (call 2): the interpreter hashes
306
+ * `context_rule.signers` at install and re-checks at enforce, so any
307
+ * client-side reconstruction that differs in any field makes the rule
308
+ * deny RULE_SIGNERS_CHANGED forever. We round-trip through a `simulate`
309
+ * of `get_context_rule(ruleId)` and return the raw retval. */
310
+ async function fetchRawContextRule(rpcClient, sourceAccount, smartAccount, ruleId, networkPassphrase) {
311
+ const source = await rpcClient.getAccount(sourceAccount);
312
+ const op = stellar_sdk_1.Operation.invokeHostFunction({
313
+ func: stellar_sdk_1.xdr.HostFunction.hostFunctionTypeInvokeContract(new stellar_sdk_1.xdr.InvokeContractArgs({
314
+ contractAddress: new stellar_sdk_1.Address(smartAccount).toScAddress(),
315
+ functionName: 'get_context_rule',
316
+ args: [stellar_sdk_1.xdr.ScVal.scvU32(ruleId)],
317
+ })),
318
+ auth: [],
319
+ });
320
+ const tx = new stellar_sdk_1.TransactionBuilder(new stellar_sdk_1.Account(sourceAccount, source.sequenceNumber()), {
321
+ fee: stellar_sdk_1.BASE_FEE,
322
+ networkPassphrase,
323
+ })
324
+ .addOperation(op)
325
+ .setTimeout(0)
326
+ .build();
327
+ const sim = await rpcClient.simulateTransaction(tx);
328
+ if (stellar_sdk_1.rpc.Api.isSimulationError(sim)) {
329
+ throw new Error(`install_predicate: get_context_rule(${ruleId}) simulateTransaction failed: ${sim.error}`);
330
+ }
331
+ const retval = sim.result?.retval;
332
+ if (!retval) {
333
+ throw new Error(`install_predicate: get_context_rule(${ruleId}) returned no value`);
334
+ }
335
+ return retval;
336
+ }
337
+ /** Build the params ScMap for `interpreter.install`. Keys MUST be sorted
338
+ * by symbol string (the canonical map encoding requires it). The host
339
+ * unpacks by field count, so a missing or extra field traps with WasmVm
340
+ * UnexpectedSize rather than a clean code. */
341
+ function buildInstallParams(args) {
342
+ const entry = (k, v) => new stellar_sdk_1.xdr.ScMapEntry({ key: stellar_sdk_1.xdr.ScVal.scvSymbol(k), val: v });
343
+ // Sorted order: grammar_version, install_nonce, oracle_max_deviation_bps,
344
+ // oracle_max_staleness_seconds, oracle_max_xfeed_dev_bps, predicate,
345
+ // predicate_hash.
346
+ return stellar_sdk_1.xdr.ScVal.scvMap([
347
+ entry('grammar_version', stellar_sdk_1.xdr.ScVal.scvU32(args.grammarVersion)),
348
+ entry('install_nonce', stellar_sdk_1.xdr.ScVal.scvU32(args.installNonce)),
349
+ entry('oracle_max_deviation_bps', stellar_sdk_1.xdr.ScVal.scvVoid()),
350
+ entry('oracle_max_staleness_seconds', stellar_sdk_1.xdr.ScVal.scvVoid()),
351
+ entry('oracle_max_xfeed_dev_bps', stellar_sdk_1.xdr.ScVal.scvVoid()),
352
+ entry('predicate', stellar_sdk_1.xdr.ScVal.scvBytes(args.predicateBytes)),
353
+ entry('predicate_hash', stellar_sdk_1.xdr.ScVal.scvBytes(args.predicateHashBytes)),
354
+ ]);
355
+ }
356
+ /** Build an unsigned Soroban transaction envelope. Same pattern as
357
+ * build-install-policy.ts so the consumer code path is uniform. */
358
+ function buildUnsignedTx(args) {
359
+ const account = new stellar_sdk_1.Account(args.sourceAccount, args.sequence);
360
+ return new stellar_sdk_1.TransactionBuilder(account, {
361
+ fee: args.fee,
362
+ networkPassphrase: args.networkPassphrase,
363
+ })
364
+ .addOperation(args.op)
365
+ .setTimeout(0)
366
+ .build();
367
+ }
368
+ /** Decode the install-predicate call's structured fields directly out of
369
+ * the final assembled transaction. The bytes are the source of truth:
370
+ * a human reviewing the install wants to see what the wallet will
371
+ * actually sign, not what we think it will. The decode is deliberately
372
+ * strict - any shape we did not build ourselves throws, since that
373
+ * would mean the XDR was tampered with (or the encoder changed and
374
+ * this descriptor lags).
375
+ *
376
+ * The second argument (raw context rule) is passed through verbatim;
377
+ * we do NOT decode it here because reconstructing the rule's fields
378
+ * client-side is exactly what the file header warns against. The rule
379
+ * id lives inside it and is echoed from input at the top-level result. */
380
+ function decodeInstallPredicateCallDescribes(tx, expectedPredicateHash) {
381
+ const operations = tx.toEnvelope().v1().tx().operations();
382
+ if (operations.length !== 1 || !operations[0]) {
383
+ throw new Error(`install_predicate: final transaction has ${operations.length} operations, expected 1`);
384
+ }
385
+ const op = operations[0];
386
+ const hostFn = op.body().invokeHostFunctionOp()?.hostFunction();
387
+ if (hostFn?.switch().name !== 'hostFunctionTypeInvokeContract') {
388
+ throw new Error('install_predicate: built op is not an invokeHostFunction(invokeContract(...)) call');
389
+ }
390
+ const invokeArgs = hostFn.invokeContract();
391
+ if (!invokeArgs) {
392
+ throw new Error('install_predicate: built op has no InvokeContractArgs payload');
393
+ }
394
+ const targetContract = stellar_sdk_1.Address.fromScAddress(invokeArgs.contractAddress()).toString();
395
+ const fnName = invokeArgs.functionName().toString();
396
+ if (fnName !== 'install') {
397
+ throw new Error(`install_predicate: built op fn name is "${fnName}", expected "install"`);
398
+ }
399
+ const scvArgs = invokeArgs.args();
400
+ if (scvArgs.length !== 3) {
401
+ throw new Error(`install_predicate: built op has ${scvArgs.length} args, expected 3 (params, raw_context_rule, smart_account)`);
402
+ }
403
+ const paramsScv = scvArgs[0];
404
+ const rawContextRuleScv = scvArgs[1];
405
+ const smartAccountScv = scvArgs[2];
406
+ if (!paramsScv || !rawContextRuleScv || !smartAccountScv) {
407
+ throw new Error('install_predicate: built op args include an undefined slot despite length check');
408
+ }
409
+ // params: an ScMap with seven fields (sorted by symbol).
410
+ if (paramsScv.switch().name !== 'scvMap') {
411
+ throw new Error('install_predicate: args[0] (params) is not an ScVal::Map');
412
+ }
413
+ const paramsFields = new Map();
414
+ for (const inner of paramsScv.map() ?? []) {
415
+ const fk = inner.key();
416
+ if (fk.switch().name !== 'scvSymbol') {
417
+ throw new Error('install_predicate: params field key is not an ScVal::Symbol');
418
+ }
419
+ paramsFields.set(fk.sym().toString(), inner.val());
420
+ }
421
+ const EXPECTED_PARAMS_KEYS = [
422
+ 'grammar_version',
423
+ 'install_nonce',
424
+ 'oracle_max_deviation_bps',
425
+ 'oracle_max_staleness_seconds',
426
+ 'oracle_max_xfeed_dev_bps',
427
+ 'predicate',
428
+ 'predicate_hash',
429
+ ];
430
+ const actualKeys = [...paramsFields.keys()].sort();
431
+ if (actualKeys.length !== EXPECTED_PARAMS_KEYS.length ||
432
+ actualKeys.some((k, i) => k !== EXPECTED_PARAMS_KEYS[i])) {
433
+ throw new Error(`install_predicate: params keys ${JSON.stringify(actualKeys)} do not match the canonical sorted set ${JSON.stringify(EXPECTED_PARAMS_KEYS)}`);
434
+ }
435
+ const grammarVersionScv = paramsFields.get('grammar_version');
436
+ if (!grammarVersionScv || grammarVersionScv.switch().name !== 'scvU32') {
437
+ throw new Error('install_predicate: params.grammar_version is missing or not u32');
438
+ }
439
+ const grammarVersion = grammarVersionScv.u32();
440
+ const installNonceScv = paramsFields.get('install_nonce');
441
+ if (!installNonceScv || installNonceScv.switch().name !== 'scvU32') {
442
+ throw new Error('install_predicate: params.install_nonce is missing or not u32');
443
+ }
444
+ const installNonce = installNonceScv.u32();
445
+ const predicateScv = paramsFields.get('predicate');
446
+ if (!predicateScv || predicateScv.switch().name !== 'scvBytes') {
447
+ throw new Error('install_predicate: params.predicate is missing or not bytes');
448
+ }
449
+ const predicateBytes = Buffer.from(predicateScv.bytes());
450
+ const predicateSha256OfEmbeddedBytes = (0, node_crypto_1.createHash)('sha256').update(predicateBytes).digest('hex');
451
+ const predicateHashScv = paramsFields.get('predicate_hash');
452
+ if (!predicateHashScv || predicateHashScv.switch().name !== 'scvBytes') {
453
+ throw new Error('install_predicate: params.predicate_hash is missing or not bytes');
454
+ }
455
+ const predicateHash = Buffer.from(predicateHashScv.bytes()).toString('hex');
456
+ if (predicateHash !== expectedPredicateHash) {
457
+ throw new Error(`install_predicate: params.predicate_hash (${predicateHash}) differs from the caller-supplied hash (${expectedPredicateHash})`);
458
+ }
459
+ if (rawContextRuleScv.switch().name === 'scvVoid') {
460
+ throw new Error('install_predicate: args[1] (raw_context_rule) is scvVoid');
461
+ }
462
+ if (smartAccountScv.switch().name !== 'scvAddress') {
463
+ throw new Error('install_predicate: args[2] (smart_account) is not an ScVal::Address');
464
+ }
465
+ const smartAccountOnWire = stellar_sdk_1.Address.fromScAddress(smartAccountScv.address()).toString();
466
+ return {
467
+ targetContract,
468
+ fnName: 'install',
469
+ grammarVersion,
470
+ installNonce,
471
+ predicateHash,
472
+ predicateSha256OfEmbeddedBytes,
473
+ smartAccountOnWire,
474
+ };
475
+ }
476
+ // Suppress the unused-import warning for K_NONCE while keeping the
477
+ // constant visible for the drift test it invites. (Removed once a
478
+ // drift test is in place that references it.)
479
+ void K_NONCE;
@@ -54,9 +54,9 @@ export declare function runVerifyPolicy(raw: unknown): Promise<ToolResponse<true
54
54
  * Returns the unsigned Soroban transaction envelope (base64 XDR) the
55
55
  * wallet signs. The wallet signature IS the user-confirmation step - no
56
56
  * `action_id` two-call pair (the server is stateless, see server.ts:10-12).
57
- * Per design decision 4, only CALL 1 (account.add_context_rule) is
58
- * emitted; CALL 2 (interpreter.install) requires the rule id the account
59
- * assigns in call 1 and is documented under `followUp` in the response.
57
+ * One call installs the policy outright: `add_context_rule` carries the
58
+ * predicate to the interpreter in its `policies` install_param, so no
59
+ * separate `interpreter.install` call is needed or possible.
60
60
  *
61
61
  * Default-deny: an interpreter policy address other than the pinned
62
62
  * testnet interpreter is REFUSED (the smart account would delegate to