@crediolabs/policy-synth 0.1.12 → 0.1.13

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.
@@ -0,0 +1,431 @@
1
+ "use strict";
2
+ // src/install/build-install-policy.ts - builds the unsigned Soroban
3
+ // transaction XDR for `account.add_context_rule(...)` and
4
+ // `account.remove_context_rule(...)`.
5
+ //
6
+ // The MCP server is stateless and holds no key material (server.ts:10-12),
7
+ // so this module NEVER signs. The caller (the wallet / CLI / SDK consumer)
8
+ // wraps the returned XDR in a transaction envelope and signs that envelope
9
+ // with their wallet; the wallet signature IS the user-confirmation step.
10
+ //
11
+ // We deliberately depart from the spec in plans/phase-04 which calls for a
12
+ // two-call `install_policy`/`confirm_install` pair backed by a host-signed
13
+ // short-TTL `action_id`. That contract requires (a) a stateful store and
14
+ // (b) key material the server does not have, so we ship the simpler ONE-CALL
15
+ // shape. The wallet signature covers the change.
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`.
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.DEFAULT_GRAMMAR_VERSION = exports.Contract = void 0;
22
+ exports.rpcClientFromServer = rpcClientFromServer;
23
+ exports.buildInstallPolicyXdr = buildInstallPolicyXdr;
24
+ exports.buildRevokePolicyXdr = buildRevokePolicyXdr;
25
+ const node_crypto_1 = require("node:crypto");
26
+ const stellar_sdk_1 = require("@stellar/stellar-sdk");
27
+ Object.defineProperty(exports, "Contract", { enumerable: true, get: function () { return stellar_sdk_1.Contract; } });
28
+ const build_add_context_rule_ts_1 = require("./build-add-context-rule.js");
29
+ Object.defineProperty(exports, "DEFAULT_GRAMMAR_VERSION", { enumerable: true, get: function () { return build_add_context_rule_ts_1.DEFAULT_GRAMMAR_VERSION; } });
30
+ /** Convert a real rpc.Server into the InstallRpcClient surface. The
31
+ * `getContractVersion` lookup uses `simulateTransaction` against
32
+ * `contract.call('grammar_version')` and decodes the returned u32.
33
+ *
34
+ * The passphrase is a REQUIRED argument rather than something read off the
35
+ * server: `rpc.Server` does not carry one, so reaching for
36
+ * `server.networkPassphrase` yielded a non-string and every version probe
37
+ * died with "Invalid passphrase provided to Transaction". The caller knows
38
+ * which network it dialled; make it say so. */
39
+ function rpcClientFromServer(server, networkPassphrase) {
40
+ return {
41
+ getAccount: (address) => server.getAccount(address),
42
+ simulateTransaction: (tx) => server.simulateTransaction(tx),
43
+ getLatestLedger: () => server.getLatestLedger(),
44
+ async getContractVersion(address) {
45
+ // The source account is constructed locally rather than fetched. This is
46
+ // a read-only simulation, so the sequence number is never checked, and a
47
+ // random key does NOT exist on chain - asking the network for it returns
48
+ // 404 and the version probe fails for a reason that has nothing to do
49
+ // with the contract being probed.
50
+ const account = new stellar_sdk_2.Account(stellar_sdk_1.Keypair.random().publicKey(), '0');
51
+ const tx = new stellar_sdk_1.TransactionBuilder(account, {
52
+ fee: stellar_sdk_1.BASE_FEE,
53
+ networkPassphrase,
54
+ })
55
+ .addOperation(new stellar_sdk_1.Contract(address).call('grammar_version'))
56
+ .setTimeout(30)
57
+ .build();
58
+ const sim = await server.simulateTransaction(tx);
59
+ if (stellar_sdk_1.rpc.Api.isSimulationError(sim)) {
60
+ throw new Error(`getContractVersion: simulateTransaction failed: ${sim.error}`);
61
+ }
62
+ if (!sim.result?.retval) {
63
+ throw new Error('getContractVersion: grammar_version() returned no value');
64
+ }
65
+ const native = (0, stellar_sdk_1.scValToBigInt)(sim.result.retval);
66
+ if (typeof native !== 'bigint') {
67
+ throw new Error('getContractVersion: grammar_version() did not return an integer');
68
+ }
69
+ return Number(native);
70
+ },
71
+ };
72
+ }
73
+ 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.';
74
+ /** Build the unsigned transaction envelope for `account.add_context_rule(...)`.
75
+ * The output XDR is signed by the wallet, not by us. */
76
+ async function buildInstallPolicyXdr(args) {
77
+ // 1. Pure arg encoding first - fail closed on any limit / shape problem
78
+ // BEFORE we burn a network round-trip on a malformed call.
79
+ const callArgs = (0, build_add_context_rule_ts_1.buildAddContextRuleArgs)({
80
+ contextRuleType: args.rule.contextRuleType,
81
+ name: args.rule.name,
82
+ validUntilLedger: args.rule.validUntilLedger,
83
+ signers: args.rule.signers,
84
+ policies: args.rule.policies.map(adaptPolicyRef),
85
+ }, {
86
+ signers: args.rule.signers,
87
+ policies: args.rule.policies.map(adaptPolicyRef),
88
+ installNonce: args.installNonce,
89
+ encodedPredicate: args.encodedPredicate,
90
+ predicateHash: args.predicateHash,
91
+ ...(args.oracleParams ? { oracleParams: args.oracleParams } : {}),
92
+ ...(args.grammarVersion !== undefined ? { grammarVersion: args.grammarVersion } : {}),
93
+ });
94
+ // 2. Network pass: source account sequence + latest ledger.
95
+ const source = await args.rpc.getAccount(args.sourceAccount);
96
+ const latest = await args.rpc.getLatestLedger();
97
+ const validUntilLedger = latest.sequence + (args.authValidUntilLedgers ?? DEFAULT_AUTH_VALID_LEDGERS);
98
+ // 3. Build the unsigned transaction envelope with the bare host call.
99
+ const op = stellar_sdk_1.Operation.invokeHostFunction({
100
+ func: stellar_sdk_1.xdr.HostFunction.hostFunctionTypeInvokeContract(new stellar_sdk_1.xdr.InvokeContractArgs({
101
+ contractAddress: new stellar_sdk_1.Address(args.smartAccount).toScAddress(),
102
+ functionName: 'add_context_rule',
103
+ args: [...callArgs],
104
+ })),
105
+ auth: [],
106
+ });
107
+ const baseFee = args.baseFee !== undefined ? String(args.baseFee) : stellar_sdk_1.BASE_FEE;
108
+ const tx = buildUnsignedTx({
109
+ sourceAccount: args.sourceAccount,
110
+ sequence: source.sequenceNumber(),
111
+ fee: baseFee,
112
+ networkPassphrase: args.networkPassphrase,
113
+ op,
114
+ });
115
+ // 4. Simulation pass. Returns the auth nonce + rootInvocation the wallet
116
+ // signature binds to. We do NOT add the AuthPayload here - the wallet
117
+ // injects auth entries using its own __check_auth flow.
118
+ const recorded = await args.rpc.simulateTransaction(tx);
119
+ if (stellar_sdk_1.rpc.Api.isSimulationError(recorded)) {
120
+ // Short, stable reason. The full `simulateTransaction` error (which
121
+ // carries host + URL detail) stays in the SDK's own logs - never
122
+ // reflected back into a user-facing message where it would
123
+ // reconnoitre the RPC.
124
+ throw new Error('install_policy: simulateTransaction failed');
125
+ }
126
+ const original = (recorded.result?.auth ?? []).find((entry) => entry.credentials().switch().name === 'sorobanCredentialsAddress' &&
127
+ stellar_sdk_1.Address.fromScAddress(entry.credentials().address().address()).toString() ===
128
+ args.smartAccount);
129
+ if (!original) {
130
+ throw new Error(`install_policy: no Soroban auth entry for smart account ${args.smartAccount}; this call does not route through the smart account`);
131
+ }
132
+ // 5. Decode the structured description FROM the unsigned XDR. The human
133
+ // approval binds to the bytes the wallet will sign; deriving this from
134
+ // the input args would re-describe the caller's intent rather than the
135
+ // transaction. Re-parse the envelope we just built so the description
136
+ // reflects what the wallet actually signs, not what we thought it would.
137
+ const describes = decodeInstallCallDescribes(tx, op, args.installNonce);
138
+ return {
139
+ unsignedXdr: tx.toEnvelope().toXDR().toString('base64'),
140
+ smartAccount: args.smartAccount,
141
+ sourceAccount: args.sourceAccount,
142
+ call: { contract: args.smartAccount, fn: 'add_context_rule' },
143
+ followUp: {
144
+ contract: 'interpreter',
145
+ fn: 'install',
146
+ requiresRuleIdFromCallOne: true,
147
+ hint: FOLLOWUP_HINT,
148
+ },
149
+ describes,
150
+ authNonce: original.credentials().address().nonce().toString(),
151
+ authValidUntilLedger: validUntilLedger,
152
+ rootInvocationXdr: original.rootInvocation().toXDR().toString('base64'),
153
+ };
154
+ }
155
+ /** Build an unsigned XDR for `account.remove_context_rule(ruleId)`. The
156
+ * smart account itself handles uninstalling each attached policy (calling
157
+ * `interpreter.uninstall` for the interpreter policy); this builder only
158
+ * emits the account-side removal call.
159
+ *
160
+ * Who may authorise it is the ACCOUNT's decision, and the account's source is
161
+ * not in this repo. The interpreter's own `uninstall` is master-gated, but
162
+ * that is a different entry point from this one, so do not restate it as the
163
+ * rule for this call. What is proven on testnet is that the account's
164
+ * deployer can revoke. This builder does not pre-check the signer: it would
165
+ * be guessing at a contract it cannot read, and the chain is the authority. */
166
+ async function buildRevokePolicyXdr(args) {
167
+ const source = await args.rpc.getAccount(args.sourceAccount);
168
+ const latest = await args.rpc.getLatestLedger();
169
+ const validUntilLedger = latest.sequence + (args.authValidUntilLedgers ?? DEFAULT_AUTH_VALID_LEDGERS);
170
+ const op = stellar_sdk_1.Operation.invokeHostFunction({
171
+ func: stellar_sdk_1.xdr.HostFunction.hostFunctionTypeInvokeContract(new stellar_sdk_1.xdr.InvokeContractArgs({
172
+ contractAddress: new stellar_sdk_1.Address(args.smartAccount).toScAddress(),
173
+ functionName: 'remove_context_rule',
174
+ args: [stellar_sdk_1.xdr.ScVal.scvU32(args.ruleId)],
175
+ })),
176
+ auth: [],
177
+ });
178
+ const baseFee = args.baseFee !== undefined ? String(args.baseFee) : stellar_sdk_1.BASE_FEE;
179
+ const tx = buildUnsignedTx({
180
+ sourceAccount: args.sourceAccount,
181
+ sequence: source.sequenceNumber(),
182
+ fee: baseFee,
183
+ networkPassphrase: args.networkPassphrase,
184
+ op,
185
+ });
186
+ const recorded = await args.rpc.simulateTransaction(tx);
187
+ if (stellar_sdk_1.rpc.Api.isSimulationError(recorded)) {
188
+ // Short, stable reason. The full `simulateTransaction` error (which
189
+ // carries host + URL detail) stays in the SDK's own logs - never
190
+ // reflected back into a user-facing message where it would
191
+ // reconnoitre the RPC.
192
+ throw new Error('revoke_policy: simulateTransaction failed');
193
+ }
194
+ const original = (recorded.result?.auth ?? []).find((entry) => entry.credentials().switch().name === 'sorobanCredentialsAddress' &&
195
+ stellar_sdk_1.Address.fromScAddress(entry.credentials().address().address()).toString() ===
196
+ args.smartAccount);
197
+ if (!original) {
198
+ throw new Error(`revoke_policy: no Soroban auth entry for smart account ${args.smartAccount}; this call does not route through the smart account`);
199
+ }
200
+ return {
201
+ unsignedXdr: tx.toEnvelope().toXDR().toString('base64'),
202
+ smartAccount: args.smartAccount,
203
+ sourceAccount: args.sourceAccount,
204
+ call: { contract: args.smartAccount, fn: 'remove_context_rule', ruleId: args.ruleId },
205
+ authNonce: original.credentials().address().nonce().toString(),
206
+ authValidUntilLedger: validUntilLedger,
207
+ rootInvocationXdr: original.rootInvocation().toXDR().toString('base64'),
208
+ };
209
+ }
210
+ /** ~25 minutes at 5s/ledger. */
211
+ const DEFAULT_AUTH_VALID_LEDGERS = 300;
212
+ // ---- internals ----
213
+ /** Adapter: turn the install-policy wire `PolicyRef` shape into the core
214
+ * `PolicyRef` shape `buildAddContextRuleArgs` expects. Keeps the wire
215
+ * schema hand-rolled + flat (the strict union would need a recursive
216
+ * schema) while delegating to the proven encoder for the actual bytes. */
217
+ function adaptPolicyRef(p) {
218
+ if (p.kind === 'interpreter') {
219
+ return {
220
+ kind: 'interpreter',
221
+ interpreterAddress: p.interpreterAddress,
222
+ predicateBlobBase64: p.predicateBlobBase64,
223
+ };
224
+ }
225
+ return {
226
+ kind: 'oz_builtin',
227
+ instanceAddress: p.instanceAddress,
228
+ primitive: p.primitive,
229
+ };
230
+ }
231
+ /** Build an unsigned Soroban transaction envelope. The `sequence` is
232
+ * whatever `getAccount().sequenceNumber()` returned (a string of digits
233
+ * the SDK accepts). No signing. The returned Transaction is what
234
+ * `simulateTransaction` accepts. */
235
+ function buildUnsignedTx(args) {
236
+ const account = new stellar_sdk_2.Account(args.sourceAccount, args.sequence);
237
+ const tx = new stellar_sdk_1.TransactionBuilder(account, {
238
+ fee: args.fee,
239
+ networkPassphrase: args.networkPassphrase,
240
+ })
241
+ .addOperation(args.op)
242
+ .setTimeout(0)
243
+ .build();
244
+ // `TransactionBuilder.build()` returns a Transaction whose envelope
245
+ // has empty signatures. The wallet re-reads the unsigned XDR, appends
246
+ // its signature, and broadcasts. We do NOT sign here.
247
+ return tx;
248
+ }
249
+ /** Decode the install call's structured fields directly out of the
250
+ * built (transaction, operation) pair. The bytes are the source of
251
+ * truth: a human reviewing the install wants to see what the wallet
252
+ * will actually sign, not what we think it will. The decode is
253
+ * deliberately strict - any shape we did not build ourselves throws
254
+ * a ToolError, since that would mean the XDR was tampered with (or
255
+ * the encoder changed and this descriptor lags).
256
+ *
257
+ * `expectedInstallNonce` is a fallback for the rare case where the
258
+ * install has no interpreter policy (no `install_nonce` to read); the
259
+ * caller already knows it. */
260
+ function decodeInstallCallDescribes(tx, op, expectedInstallNonce) {
261
+ const hostFn = op.body().invokeHostFunctionOp()?.hostFunction();
262
+ if (!hostFn || hostFn.switch().name !== 'hostFunctionTypeInvokeContract') {
263
+ throw new Error('install_policy: built op is not an invokeHostFunction(invokeContract(...)) call');
264
+ }
265
+ const invokeArgs = hostFn.invokeContract();
266
+ if (!invokeArgs) {
267
+ throw new Error('install_policy: built op has no InvokeContractArgs payload');
268
+ }
269
+ const targetContract = stellar_sdk_1.Address.fromScAddress(invokeArgs.contractAddress()).toString();
270
+ const fnName = invokeArgs.functionName().toString();
271
+ if (fnName !== 'add_context_rule') {
272
+ throw new Error(`install_policy: built op fn name is "${fnName}", expected "add_context_rule"`);
273
+ }
274
+ const scvArgs = invokeArgs.args();
275
+ if (scvArgs.length !== 5) {
276
+ throw new Error(`install_policy: built op has ${scvArgs.length} args, expected 5 (context_type, name, valid_until, signers, policies)`);
277
+ }
278
+ const contextType = scvArgs[0];
279
+ const nameScv = scvArgs[1];
280
+ const validUntilScv = scvArgs[2];
281
+ const signersScv = scvArgs[3];
282
+ const policiesScv = scvArgs[4];
283
+ // The length check above pins these as defined; the local references
284
+ // satisfy noUncheckedIndexedAccess on the accessors below.
285
+ if (!nameScv || !validUntilScv || !signersScv || !policiesScv || !contextType) {
286
+ throw new Error('install_policy: built op args include an undefined slot despite length check');
287
+ }
288
+ // name
289
+ if (nameScv.switch().name !== 'scvString') {
290
+ throw new Error('install_policy: args[1] (name) is not an ScVal::String');
291
+ }
292
+ const ruleName = nameScv.str().toString();
293
+ // valid_until (Option<u32> -> void when absent)
294
+ let validUntilLedger;
295
+ if (validUntilScv.switch().name === 'scvVoid') {
296
+ validUntilLedger = null;
297
+ }
298
+ else if (validUntilScv.switch().name === 'scvU32') {
299
+ validUntilLedger = validUntilScv.u32();
300
+ }
301
+ else {
302
+ throw new Error('install_policy: args[2] (valid_until) is neither void nor u32');
303
+ }
304
+ // signers (Vec<Vec<Symbol, Address[, Bytes]>>)
305
+ if (signersScv.switch().name !== 'scvVec') {
306
+ throw new Error('install_policy: args[3] (signers) is not an ScVal::Vec');
307
+ }
308
+ const signers = [];
309
+ for (const signerScv of signersScv.vec() ?? []) {
310
+ if (signerScv.switch().name !== 'scvVec') {
311
+ throw new Error('install_policy: a signer entry is not an ScVal::Vec');
312
+ }
313
+ const tuple = signerScv.vec() ?? [];
314
+ const tag = tuple[0]?.sym().toString();
315
+ const inner = tuple[1];
316
+ if (tag === 'Delegated') {
317
+ if (!inner || inner.switch().name !== 'scvAddress') {
318
+ throw new Error('install_policy: a Delegated signer is missing its Address');
319
+ }
320
+ signers.push({
321
+ kind: 'delegated',
322
+ address: stellar_sdk_1.Address.fromScAddress(inner.address()).toString(),
323
+ });
324
+ continue;
325
+ }
326
+ if (tag === 'External') {
327
+ if (!inner || inner.switch().name !== 'scvAddress') {
328
+ throw new Error('install_policy: an External signer is missing its verifier Address');
329
+ }
330
+ signers.push({
331
+ kind: 'external',
332
+ verifier: stellar_sdk_1.Address.fromScAddress(inner.address()).toString(),
333
+ });
334
+ continue;
335
+ }
336
+ throw new Error(`install_policy: signer tag "${tag ?? '<missing>'}" is not Delegated|External`);
337
+ }
338
+ // policies (Map<Address, Val>). Re-derive an interpreter-vs-OZ primitive
339
+ // classification by inspecting the value's map keys (PolicyInstallParams
340
+ // starts with `grammar_version`/`install_nonce`/`predicate`; OZ primitive
341
+ // params start with `spending_limit`/`threshold`/`period_ledgers`).
342
+ if (policiesScv.switch().name !== 'scvMap') {
343
+ throw new Error('install_policy: args[4] (policies) is not an ScVal::Map');
344
+ }
345
+ const policies = [];
346
+ let observedInstallNonce = null;
347
+ for (const entry of policiesScv.map() ?? []) {
348
+ const key = entry.key();
349
+ if (key.switch().name !== 'scvAddress') {
350
+ throw new Error('install_policy: a policies map entry has a non-Address key');
351
+ }
352
+ const address = stellar_sdk_1.Address.fromScAddress(key.address()).toString();
353
+ const val = entry.val();
354
+ if (val.switch().name !== 'scvMap') {
355
+ throw new Error(`install_policy: policies[${address}] value is not an ScVal::Map (got ${val.switch().name})`);
356
+ }
357
+ const fields = new Map();
358
+ for (const inner of val.map() ?? []) {
359
+ const fk = inner.key();
360
+ if (fk.switch().name !== 'scvSymbol') {
361
+ throw new Error(`install_policy: policies[${address}] field key is not an ScVal::Symbol`);
362
+ }
363
+ fields.set(fk.sym().toString(), inner.val());
364
+ }
365
+ // Interpreter policy fields carry grammar_version/install_nonce/predicate.
366
+ // OZ primitives carry spending_limit/period_ledgers/threshold/signers.
367
+ if (fields.has('predicate') || fields.has('grammar_version') || fields.has('install_nonce')) {
368
+ const installNonceScv = fields.get('install_nonce');
369
+ if (!installNonceScv || installNonceScv.switch().name !== 'scvU32') {
370
+ throw new Error(`install_policy: interpreter policy ${address} is missing a u32 install_nonce`);
371
+ }
372
+ const installNonce = installNonceScv.u32();
373
+ const predicateScv = fields.get('predicate');
374
+ if (!predicateScv || predicateScv.switch().name !== 'scvBytes') {
375
+ throw new Error(`install_policy: interpreter policy ${address} is missing its bytes predicate`);
376
+ }
377
+ const predicateBytes = Buffer.from(predicateScv.bytes());
378
+ const predicateSha256OfEmbeddedBytes = (0, node_crypto_1.createHash)('sha256')
379
+ .update(predicateBytes)
380
+ .digest('hex');
381
+ const predicateHashScv = fields.get('predicate_hash');
382
+ const predicateHash = predicateHashScv && predicateHashScv.switch().name === 'scvBytes'
383
+ ? Buffer.from(predicateHashScv.bytes()).toString('hex')
384
+ : '';
385
+ policies.push({
386
+ kind: 'interpreter',
387
+ address,
388
+ installNonce,
389
+ predicateHash,
390
+ predicateSha256OfEmbeddedBytes,
391
+ });
392
+ observedInstallNonce = installNonce;
393
+ continue;
394
+ }
395
+ // OZ built-in primitive. Distinguish by the parameter shape we
396
+ // emitted; matching one of the three primitives exactly pins the
397
+ // kind we built.
398
+ if (fields.has('spending_limit') && fields.has('period_ledgers')) {
399
+ policies.push({ kind: 'oz_builtin', address, primitive: 'spending_limit' });
400
+ continue;
401
+ }
402
+ if (fields.has('threshold') && fields.has('signer_weights')) {
403
+ policies.push({ kind: 'oz_builtin', address, primitive: 'weighted_threshold' });
404
+ continue;
405
+ }
406
+ if (fields.has('threshold')) {
407
+ policies.push({ kind: 'oz_builtin', address, primitive: 'simple_threshold' });
408
+ continue;
409
+ }
410
+ throw new Error(`install_policy: policies[${address}] value has an unknown field set; the encoder may have drifted`);
411
+ }
412
+ // `observedInstallNonce` is the nonce baked into whichever interpreter
413
+ // policy is present; when none, fall back to the caller-supplied value.
414
+ const installNonce = observedInstallNonce ?? expectedInstallNonce;
415
+ // Touch `tx` so the linter does not flag it as unused - the parameter
416
+ // documents that the caller built this Transaction; we re-parse the
417
+ // operation off it as a sanity check.
418
+ void tx;
419
+ return {
420
+ targetContract,
421
+ fnName: 'add_context_rule',
422
+ ruleName,
423
+ validUntilLedger,
424
+ signers,
425
+ policies,
426
+ installNonce,
427
+ };
428
+ }
429
+ // Local re-import to avoid pulling the class from the SDK module path
430
+ // at the top of the file (avoids the unused-import lint).
431
+ const stellar_sdk_2 = require("@stellar/stellar-sdk");
@@ -0,0 +1,29 @@
1
+ import type { Network } from '../types.ts';
2
+ export interface InterpreterInfo {
3
+ /** Pinned interpreter contract address. */
4
+ pinnedAddress: string;
5
+ /** Pinned grammar version (matches SELF_VERSION in version.rs). */
6
+ pinnedGrammarVersion: number;
7
+ /** Pinned wasm sha256 (hex). */
8
+ pinnedWasmHash: string;
9
+ /** Network this pin applies to (the address + hash are network-scoped). */
10
+ network: Network;
11
+ /** Present only when the caller supplied a live `deployedGrammarVersion`. */
12
+ deployedGrammarVersion?: number;
13
+ /** True when `deployedGrammarVersion` matches `pinnedGrammarVersion`.
14
+ * Absent when no live verification was performed. */
15
+ liveMatchesPin?: boolean;
16
+ }
17
+ /** Build the interpreter-info response. When `deployedGrammarVersion` is
18
+ * supplied (after a live RPC `grammar_version()` call by the run layer),
19
+ * compares it to the pin and sets `liveMatchesPin`. When absent, returns
20
+ * the pin alone. */
21
+ export declare function getInterpreterInfo(args: {
22
+ pinnedAddress: string;
23
+ pinnedGrammarVersion: number;
24
+ pinnedWasmHash: string;
25
+ network: Network;
26
+ /** When supplied, the u32 returned by the live contract's
27
+ * `grammar_version()` RPC call. */
28
+ deployedGrammarVersion?: number;
29
+ }): InterpreterInfo;
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ // src/install/get-interpreter-info.ts - read-only fingerprint lookup for
3
+ // the interpreter contract.
4
+ //
5
+ // Returns the pinned deployment fingerprint + (optionally) compares a
6
+ // caller-supplied live `grammar_version` against the pin. No fabricated
7
+ // audit field; a real deployed-contract check is worth more than a fake
8
+ // reference.
9
+ //
10
+ // Per design decision 5: phase-04's "audit #44" is aspirational and has no
11
+ // source-of-truth in the repo. Returning a fabricated audit id would be a
12
+ // lie on a security surface. The honest outputs are:
13
+ // - the pinned address (DEPLOYMENTS.md)
14
+ // - the pinned grammar version (SELF_VERSION in version.rs)
15
+ // - the pinned wasm sha256 (DEPLOYMENTS.md)
16
+ // - an OPTIONAL `deployedGrammarVersion` returned by a live `grammar_version()`
17
+ // RPC call, with a `liveMatchesPin` boolean the caller can dispatch on. A
18
+ // mismatch means the deployed wasm is NOT the pinned artifact - the caller
19
+ // should refuse to install until they redeploy.
20
+ //
21
+ // The RPC plumbing lives in the run layer (`run/index.ts`); this module
22
+ // stays pure so it is testable without a network.
23
+ Object.defineProperty(exports, "__esModule", { value: true });
24
+ exports.getInterpreterInfo = getInterpreterInfo;
25
+ /** Build the interpreter-info response. When `deployedGrammarVersion` is
26
+ * supplied (after a live RPC `grammar_version()` call by the run layer),
27
+ * compares it to the pin and sets `liveMatchesPin`. When absent, returns
28
+ * the pin alone. */
29
+ function getInterpreterInfo(args) {
30
+ const info = {
31
+ pinnedAddress: args.pinnedAddress,
32
+ pinnedGrammarVersion: args.pinnedGrammarVersion,
33
+ pinnedWasmHash: args.pinnedWasmHash,
34
+ network: args.network,
35
+ };
36
+ if (typeof args.deployedGrammarVersion === 'number') {
37
+ return {
38
+ ...info,
39
+ deployedGrammarVersion: args.deployedGrammarVersion,
40
+ liveMatchesPin: args.deployedGrammarVersion === args.pinnedGrammarVersion,
41
+ };
42
+ }
43
+ return info;
44
+ }
@@ -1,10 +1,14 @@
1
1
  import { type ErrorCode, type PredicateNode, type ProposedPolicy, type RecordedTransaction, type ToolError, type ToolResponse } from '../index.ts';
2
+ import { type BuildInstallPolicyResult, type BuildRevokePolicyResult } from '../install/build-install-policy.ts';
3
+ import { getInterpreterInfo } from '../install/get-interpreter-info.ts';
2
4
  import type { SimulationResult } from '../verify/envelope.ts';
3
- import { type RecordTransactionInput, type SynthesizePolicyInput } from './schemas.ts';
4
- export type { RecordTransactionInput, SynthesizePolicyInput } from './schemas.ts';
5
- export { ComposeUserResponsesSchema, InterpreterOptionsSchema, MandateSpecSchema, NetworkSchema, OzAdapterConfigSchema, RecordedTransactionSchema, RecordTransactionInputSchema, SynthesizePolicyInputSchema, ToolErrorSchema, } from './schemas.ts';
5
+ import { type RecordTransactionInput, type SimulatePolicyInput, type SynthesizePolicyInput, type VerifyPolicyInput } from './schemas.ts';
6
+ export type { GetInterpreterInfoInput, InstallPolicyInput, RecordTransactionInput, RevokePolicyInput, SimulatePolicyInput, SynthesizePolicyInput, VerifyPolicyInput, } from './schemas.ts';
7
+ export { ComposeUserResponsesSchema, GetInterpreterInfoInputSchema, InstallPolicyInputSchema, InterpreterOptionsSchema, MandateSpecSchema, NetworkSchema, OraclePriceFixtureSchema, OzAdapterConfigSchema, PINNED_INTERPRETER_GRAMMAR_VERSION, PINNED_INTERPRETER_TESTNET_ADDRESS, PINNED_INTERPRETER_WASM_SHA256, PredicateLeafSchema, PredicateNodeSchema, RecordedTransactionSchema, RecordTransactionInputSchema, RevokePolicyInputSchema, SimulatePolicyInputSchema, SynthesizePolicyInputSchema, ToolErrorSchema, VerifyPolicyInputSchema, } from './schemas.ts';
6
8
  export type RunRecordTransactionInput = RecordTransactionInput;
7
9
  export type RunSynthesizePolicyInput = SynthesizePolicyInput;
10
+ export type RunSimulatePolicyInput = SimulatePolicyInput;
11
+ export type RunVerifyPolicyInput = VerifyPolicyInput;
8
12
  /** `record_transaction` body - wraps `recordTransaction`. The tool input
9
13
  * matches the core RecordInput minus the injected `fetcher` (the transport
10
14
  * layer does not own the RPC). Returns the core ToolResponse unchanged.
@@ -35,6 +39,47 @@ export declare function runSynthesizePolicy(raw: unknown): Promise<ToolResponse<
35
39
  simulation: SimulationResult;
36
40
  };
37
41
  }>;
42
+ /** `simulate_policy` body - thin wrapper over `simulatePolicy`. The engine
43
+ * already returns fail-closed `{ok:false, error}` for runtime failures
44
+ * (SIMULATION_ERROR), so the try/catch envelope is for raw SDK throws
45
+ * only - same pattern as the other two wrappers. The predicate is
46
+ * passed inline (stateless by design; no `proposed_policy_id` lookup). */
47
+ export declare function runSimulatePolicy(raw: unknown): Promise<ToolResponse<SimulationResult>>;
48
+ /** `verify_policy` body - thin wrapper over `verifyPolicy`. The engine
49
+ * already returns `{ok:false, error}` with code VERIFICATION_FAILED when
50
+ * the minimality check fails; the try/catch envelope is for raw SDK
51
+ * throws only. Mirrors `runSimulatePolicy` exactly. */
52
+ export declare function runVerifyPolicy(raw: unknown): Promise<ToolResponse<true>>;
53
+ /** `install_policy` body - thin wrapper over `buildInstallPolicyXdr`.
54
+ * Returns the unsigned Soroban transaction envelope (base64 XDR) the
55
+ * wallet signs. The wallet signature IS the user-confirmation step - no
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.
60
+ *
61
+ * Default-deny: an interpreter policy address other than the pinned
62
+ * testnet interpreter is REFUSED (the smart account would delegate to
63
+ * an interpreter the caller controls); the same applies to a non-pinned
64
+ * RPC URL (the auth nonce the wallet signs comes from the RPC). Both
65
+ * gates accept an explicit opt-in flag. */
66
+ export declare function runInstallPolicy(raw: unknown): Promise<ToolResponse<BuildInstallPolicyResult>>;
67
+ /** `revoke_policy` body - thin wrapper over `buildRevokePolicyXdr`.
68
+ * Emits an unsigned XDR for `account.remove_context_rule(ruleId)`; the
69
+ * smart account itself handles uninstalling each attached policy. Auth
70
+ * is master-only; the source account MUST be the master signer set.
71
+ *
72
+ * Same RPC pin as install: a non-pinned `rpcUrl` is refused unless
73
+ * `allowUnpinnedRpcUrl: true`. Revoke does not carry an interpreter
74
+ * policy payload, so the interpreter pin is not re-checked here. */
75
+ export declare function runRevokePolicy(raw: unknown): Promise<ToolResponse<BuildRevokePolicyResult>>;
76
+ /** `get_interpreter_info` body - thin wrapper over `getInterpreterInfo`.
77
+ * Returns the pinned deployment fingerprint + an optional live
78
+ * `grammar_version()` comparison. The audit field is deliberately
79
+ * OMITTED (phase-04's "audit #44" has no source of truth in the repo -
80
+ * fabricating it would be a lie on a security surface; the live
81
+ * mismatch check is worth MORE). */
82
+ export declare function runGetInterpreterInfo(raw: unknown): Promise<ToolResponse<ReturnType<typeof getInterpreterInfo>>>;
38
83
  /** Build a canonical ToolError for a thrown exception caught by the tool
39
84
  * envelope. The MCP SDK stringifies thrown objects as "[object Object]" by
40
85
  * default, so we extract a string-friendly message and tag the original
@@ -46,4 +91,4 @@ export declare function runSynthesizePolicy(raw: unknown): Promise<ToolResponse<
46
91
  * Exported as `_caughtError` (the leading underscore signals the test-only
47
92
  * seam) so the suite in run/index.test.ts can drive the envelope path
48
93
  * without standing up a full recordTransaction pipeline. */
49
- export declare function caughtError(toolName: 'record_transaction' | 'synthesize_policy', code: ErrorCode, e: unknown): ToolError;
94
+ export declare function caughtError(toolName: 'record_transaction' | 'synthesize_policy' | 'simulate_policy' | 'verify_policy' | 'install_policy' | 'revoke_policy' | 'get_interpreter_info', code: ErrorCode, e: unknown): ToolError;