stellar-specguard 0.0.0-stage → 1.0.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.
@@ -0,0 +1,388 @@
1
+ // Applies the rules in docs/RULES.md to two normalized interfaces.
2
+ import { SEVERITIES } from "../model.js";
3
+ const CONSTRUCTOR = "__constructor";
4
+ export function compare(oldI, newI) {
5
+ const changes = [];
6
+ const usage = mergeUsage(usedBy(oldI), usedBy(newI));
7
+ compareFunctions(oldI.functions, newI.functions, changes);
8
+ compareTypes(oldI.types, newI.types, usedBy(oldI), usage, changes);
9
+ compareEvents(oldI.events ?? [], newI.events ?? [], changes);
10
+ compareMeta(oldI, newI, changes);
11
+ changes.sort((a, b) => SEVERITIES.indexOf(a.severity) - SEVERITIES.indexOf(b.severity));
12
+ const summary = { breaking: 0, risky: 0, compatible: 0, info: 0 };
13
+ for (const c of changes)
14
+ summary[c.severity]++;
15
+ const verdict = summary.breaking ? "breaking" : summary.risky ? "risky" : "compatible";
16
+ return {
17
+ schema: 1,
18
+ old: { source: oldI.source, wasmHash: oldI.wasmHash },
19
+ new: { source: newI.source, wasmHash: newI.wasmHash },
20
+ verdict,
21
+ summary,
22
+ changes,
23
+ };
24
+ }
25
+ // ---------------------------------------------------------------- functions
26
+ function compareFunctions(oldFns, newFns, out) {
27
+ const before = byName(oldFns);
28
+ const after = byName(newFns);
29
+ for (const [name, o] of before) {
30
+ const n = after.get(name);
31
+ if (!n) {
32
+ push(out, name, { severity: "breaking", rule: "fn-removed", path: `fn ${name}`, message: "function removed", before: signature(o) });
33
+ continue;
34
+ }
35
+ compareFunction(o, n, out);
36
+ }
37
+ for (const [name, n] of after) {
38
+ if (!before.has(name)) {
39
+ push(out, name, { severity: "compatible", rule: "fn-added", path: `fn ${name}`, message: "function added", after: signature(n) });
40
+ }
41
+ }
42
+ }
43
+ function compareFunction(o, n, out) {
44
+ const fn = `fn ${o.name}`;
45
+ if (o.inputs.length !== n.inputs.length) {
46
+ push(out, o.name, {
47
+ severity: "breaking",
48
+ rule: "fn-input-count",
49
+ path: fn,
50
+ message: `takes ${n.inputs.length} argument(s), was ${o.inputs.length}`,
51
+ before: signature(o),
52
+ after: signature(n),
53
+ });
54
+ }
55
+ else {
56
+ const oldNames = o.inputs.map((p) => p.name);
57
+ let reordered = false;
58
+ o.inputs.forEach((op, i) => {
59
+ const np = n.inputs[i];
60
+ if (op.type !== np.type) {
61
+ const optional = np.type === `Option<${op.type}>`;
62
+ push(out, o.name, {
63
+ severity: optional ? "risky" : "breaking",
64
+ rule: optional ? "fn-input-optional" : "fn-input-type",
65
+ path: `${fn}(${op.name})`,
66
+ message: optional ? "argument became optional" : "argument type changed",
67
+ before: op.type,
68
+ after: np.type,
69
+ });
70
+ }
71
+ else if (op.name !== np.name) {
72
+ const movedFrom = oldNames.indexOf(np.name);
73
+ if (movedFrom !== -1 && movedFrom !== i) {
74
+ reordered = true;
75
+ }
76
+ else {
77
+ push(out, o.name, {
78
+ severity: "risky",
79
+ rule: "fn-input-renamed",
80
+ path: `${fn}(${op.name})`,
81
+ message: "argument renamed",
82
+ before: op.name,
83
+ after: np.name,
84
+ });
85
+ }
86
+ }
87
+ });
88
+ if (reordered) {
89
+ push(out, o.name, {
90
+ severity: "breaking",
91
+ rule: "fn-input-reordered",
92
+ path: fn,
93
+ message: "arguments of the same type changed position",
94
+ before: signature(o),
95
+ after: signature(n),
96
+ });
97
+ }
98
+ }
99
+ if (o.output !== n.output) {
100
+ push(out, o.name, { severity: "breaking", rule: "fn-output-type", path: fn, message: "return type changed", before: o.output, after: n.output });
101
+ }
102
+ if (o.doc !== n.doc) {
103
+ push(out, o.name, { severity: "info", rule: "fn-doc", path: fn, message: "doc comment changed" });
104
+ }
105
+ }
106
+ // Constructor changes never reach existing callers: it only runs at deploy.
107
+ function push(out, fnName, c) {
108
+ if (fnName === CONSTRUCTOR && c.severity !== "info") {
109
+ out.push({ ...c, severity: "info", message: `${c.message} (constructor only runs at deploy)` });
110
+ }
111
+ else {
112
+ out.push(c);
113
+ }
114
+ }
115
+ function signature(f) {
116
+ const args = f.inputs.map((p) => `${p.name}: ${p.type}`).join(", ");
117
+ return f.output === "()" ? `${f.name}(${args})` : `${f.name}(${args}) -> ${f.output}`;
118
+ }
119
+ // ------------------------------------------------------------------- types
120
+ function compareTypes(oldTypes, newTypes, oldUsage, usage, out) {
121
+ const before = byName(oldTypes);
122
+ const after = byName(newTypes);
123
+ for (const [name, o] of before) {
124
+ const n = after.get(name);
125
+ const users = usage.get(name);
126
+ const tag = (c) => (users?.length ? { ...c, usedBy: users } : c);
127
+ if (!n) {
128
+ const used = (oldUsage.get(name) ?? []).length > 0;
129
+ out.push(tag({
130
+ severity: used ? "breaking" : "info",
131
+ rule: used ? "type-removed" : "type-removed-unused",
132
+ path: `${o.kind} ${name}`,
133
+ message: used ? "type removed" : "unused type removed",
134
+ }));
135
+ continue;
136
+ }
137
+ if (o.kind !== n.kind) {
138
+ out.push(tag({ severity: "breaking", rule: "type-kind", path: name, message: "type changed kind", before: o.kind, after: n.kind }));
139
+ continue;
140
+ }
141
+ const found = [];
142
+ if (o.kind === "struct")
143
+ compareStruct(o, n, found);
144
+ else if (o.kind === "union")
145
+ compareUnion(o, n, found);
146
+ else if (o.kind === "enum")
147
+ compareEnum(o, n, found);
148
+ else
149
+ compareErrors(o, n, found);
150
+ if (o.doc !== n.doc)
151
+ found.push({ severity: "info", rule: "type-doc", path: `${o.kind} ${name}`, message: "doc comment changed" });
152
+ out.push(...found.map(tag));
153
+ }
154
+ for (const [name, n] of after) {
155
+ if (!before.has(name)) {
156
+ out.push({ severity: "compatible", rule: "type-added", path: `${n.kind} ${name}`, message: "type added" });
157
+ }
158
+ }
159
+ }
160
+ function compareStruct(o, n, out) {
161
+ // Tuple structs name their fields "0", "1", ... and encode as a vector, so
162
+ // position matters. Named structs encode as a map, so only names matter.
163
+ const tuple = isTuple(o) || isTuple(n);
164
+ const key = (f, i) => (tuple ? String(i) : f.name);
165
+ const before = new Map(o.fields.map((f, i) => [key(f, i), f]));
166
+ const after = new Map(n.fields.map((f, i) => [key(f, i), f]));
167
+ const path = (f) => `struct ${o.name}.${f}`;
168
+ for (const [k, f] of before) {
169
+ const g = after.get(k);
170
+ if (!g)
171
+ out.push({ severity: "breaking", rule: "struct-field-removed", path: path(k), message: "field removed", before: f.type });
172
+ else if (f.type !== g.type)
173
+ out.push({ severity: "breaking", rule: "struct-field-type", path: path(k), message: "field type changed", before: f.type, after: g.type });
174
+ }
175
+ for (const [k, g] of after) {
176
+ if (!before.has(k))
177
+ out.push({ severity: "breaking", rule: "struct-field-added", path: path(k), message: "field added", after: g.type });
178
+ }
179
+ }
180
+ function isTuple(s) {
181
+ return s.fields.length > 0 && s.fields.every((f, i) => f.name === String(i));
182
+ }
183
+ function compareUnion(o, n, out) {
184
+ const before = byName(o.cases);
185
+ const after = byName(n.cases);
186
+ const path = (c) => `union ${o.name}::${c}`;
187
+ const show = (types) => (types.length ? `(${types.join(", ")})` : "(no data)");
188
+ for (const [name, c] of before) {
189
+ const d = after.get(name);
190
+ if (!d)
191
+ out.push({ severity: "breaking", rule: "union-case-removed", path: path(name), message: "case removed" });
192
+ else if (show(c.types) !== show(d.types)) {
193
+ out.push({ severity: "breaking", rule: "union-case-type", path: path(name), message: "case data changed", before: show(c.types), after: show(d.types) });
194
+ }
195
+ }
196
+ for (const [name] of after) {
197
+ if (!before.has(name))
198
+ out.push({ severity: "risky", rule: "union-case-added", path: path(name), message: "case added; old clients cannot decode it" });
199
+ }
200
+ }
201
+ function compareEnum(o, n, out) {
202
+ const path = (c) => `enum ${o.name}::${c}`;
203
+ const newByName = byName(n.cases);
204
+ const newByValue = new Map(n.cases.map((c) => [c.value, c]));
205
+ const oldNames = new Set(o.cases.map((c) => c.name));
206
+ const oldValues = new Set(o.cases.map((c) => c.value));
207
+ for (const c of o.cases) {
208
+ const sameName = newByName.get(c.name);
209
+ const sameValue = newByValue.get(c.value);
210
+ if (sameName && sameName.value !== c.value) {
211
+ out.push({ severity: "breaking", rule: "enum-value-changed", path: path(c.name), message: "value changed", before: String(c.value), after: String(sameName.value) });
212
+ }
213
+ else if (!sameName && sameValue && !oldNames.has(sameValue.name)) {
214
+ out.push({ severity: "risky", rule: "enum-case-renamed", path: path(c.name), message: `renamed (value ${c.value})`, before: c.name, after: sameValue.name });
215
+ }
216
+ else if (!sameName) {
217
+ out.push({ severity: "breaking", rule: "enum-case-removed", path: path(c.name), message: "value removed", before: String(c.value) });
218
+ }
219
+ }
220
+ for (const c of n.cases) {
221
+ if (!oldNames.has(c.name) && !oldValues.has(c.value)) {
222
+ out.push({ severity: "risky", rule: "enum-case-added", path: path(c.name), message: "value added; old clients cannot decode it", after: String(c.value) });
223
+ }
224
+ }
225
+ }
226
+ function compareErrors(o, n, out) {
227
+ const path = (c) => `error ${o.name}::${c}`;
228
+ const newByName = byName(n.cases);
229
+ const newByValue = new Map(n.cases.map((c) => [c.value, c]));
230
+ const oldNames = new Set(o.cases.map((c) => c.name));
231
+ const oldValues = new Set(o.cases.map((c) => c.value));
232
+ for (const c of o.cases) {
233
+ const sameName = newByName.get(c.name);
234
+ const sameValue = newByValue.get(c.value);
235
+ if (sameName && sameName.value !== c.value) {
236
+ out.push({ severity: "breaking", rule: "error-code-changed", path: path(c.name), message: "error code changed", before: String(c.value), after: String(sameName.value) });
237
+ }
238
+ else if (!sameName && sameValue && !oldNames.has(sameValue.name)) {
239
+ out.push({ severity: "info", rule: "error-renamed", path: path(c.name), message: `renamed (code ${c.value})`, before: c.name, after: sameValue.name });
240
+ }
241
+ else if (!sameName) {
242
+ out.push({ severity: "risky", rule: "error-removed", path: path(c.name), message: "error code removed", before: String(c.value) });
243
+ }
244
+ }
245
+ for (const c of n.cases) {
246
+ if (!oldNames.has(c.name) && !oldValues.has(c.value)) {
247
+ out.push({ severity: "compatible", rule: "error-added", path: path(c.name), message: "error code added", after: String(c.value) });
248
+ }
249
+ }
250
+ }
251
+ // ------------------------------------------------------------------ events
252
+ // Topics are positional: the prefix symbols, then the topic params in order.
253
+ // Data params are keyed by name when the format is a map, and positional for
254
+ // a vec or a single value. A change in either breaks anyone decoding the event.
255
+ function compareEvents(oldEvents, newEvents, out) {
256
+ const before = byName(oldEvents);
257
+ const after = byName(newEvents);
258
+ for (const [name, o] of before) {
259
+ const n = after.get(name);
260
+ const ev = `event ${name}`;
261
+ if (!n) {
262
+ out.push({ severity: "risky", rule: "event-removed", path: ev, message: "event removed; indexers stop receiving it", before: eventShape(o) });
263
+ continue;
264
+ }
265
+ if (o.topics.join(",") !== n.topics.join(",")) {
266
+ out.push({ severity: "breaking", rule: "event-topics", path: ev, message: "prefix topics changed; topic filters stop matching", before: o.topics.join(", "), after: n.topics.join(", ") });
267
+ }
268
+ if (o.format !== n.format) {
269
+ out.push({ severity: "breaking", rule: "event-format", path: ev, message: "data format changed", before: o.format, after: n.format });
270
+ }
271
+ const topics = (e) => e.params.filter((p) => p.location === "topic");
272
+ const data = (e) => e.params.filter((p) => p.location === "data");
273
+ compareParams(ev, "topic", topics(o), topics(n), false, out);
274
+ compareParams(ev, "data", data(o), data(n), o.format === "map" && n.format === "map", out);
275
+ if (o.doc !== n.doc)
276
+ out.push({ severity: "info", rule: "event-doc", path: ev, message: "doc comment changed" });
277
+ }
278
+ for (const [name, n] of after) {
279
+ if (!before.has(name)) {
280
+ out.push({ severity: "compatible", rule: "event-added", path: `event ${name}`, message: "event added", after: eventShape(n) });
281
+ }
282
+ }
283
+ }
284
+ function compareParams(ev, where, o, n, byKey, out) {
285
+ const label = (p) => (where === "topic" ? `${ev}.${p.name} (topic)` : `${ev}.${p.name}`);
286
+ if (byKey) {
287
+ const after = byName(n);
288
+ const before = byName(o);
289
+ for (const p of o) {
290
+ const q = after.get(p.name);
291
+ if (!q)
292
+ out.push({ severity: "breaking", rule: "event-field-removed", path: label(p), message: "data field removed", before: p.type });
293
+ else if (q.type !== p.type)
294
+ out.push({ severity: "breaking", rule: "event-field-type", path: label(p), message: "data field type changed", before: p.type, after: q.type });
295
+ }
296
+ for (const q of n) {
297
+ if (!before.has(q.name))
298
+ out.push({ severity: "breaking", rule: "event-field-added", path: label(q), message: "data field added", after: q.type });
299
+ }
300
+ return;
301
+ }
302
+ const len = Math.max(o.length, n.length);
303
+ for (let i = 0; i < len; i++) {
304
+ const p = o[i];
305
+ const q = n[i];
306
+ if (p && !q)
307
+ out.push({ severity: "breaking", rule: "event-field-removed", path: label(p), message: `${where} field removed`, before: p.type });
308
+ else if (!p && q)
309
+ out.push({ severity: "breaking", rule: "event-field-added", path: label(q), message: `${where} field added`, after: q.type });
310
+ else if (p && q && p.type !== q.type)
311
+ out.push({ severity: "breaking", rule: "event-field-type", path: label(p), message: `${where} field type changed`, before: p.type, after: q.type });
312
+ else if (p && q && p.name !== q.name)
313
+ out.push({ severity: "risky", rule: "event-field-renamed", path: label(p), message: `${where} field renamed`, before: p.name, after: q.name });
314
+ }
315
+ }
316
+ function eventShape(e) {
317
+ const topics = [...e.topics.map((t) => `"${t}"`), ...e.params.filter((p) => p.location === "topic").map((p) => `${p.name}: ${p.type}`)];
318
+ const data = e.params.filter((p) => p.location === "data").map((p) => `${p.name}: ${p.type}`);
319
+ return `[${topics.join(", ")}] ${e.format}(${data.join(", ")})`;
320
+ }
321
+ // ---------------------------------------------------------------- metadata
322
+ function compareMeta(o, n, out) {
323
+ const op = o.envMeta.protocol;
324
+ const np = n.envMeta.protocol;
325
+ if (op !== undefined && np !== undefined && np > op) {
326
+ out.push({ severity: "risky", rule: "env-protocol", path: "env protocol", message: `requires protocol ${np}; check the target network supports it`, before: String(op), after: String(np) });
327
+ }
328
+ else if (op !== np || o.envMeta.preRelease !== n.envMeta.preRelease) {
329
+ out.push({ severity: "info", rule: "meta-changed", path: "env protocol", message: "environment version changed", before: `${op}.${o.envMeta.preRelease}`, after: `${np}.${n.envMeta.preRelease}` });
330
+ }
331
+ for (const key of new Set([...Object.keys(o.meta), ...Object.keys(n.meta)])) {
332
+ const a = o.meta[key];
333
+ const b = n.meta[key];
334
+ if (a !== b) {
335
+ out.push({ severity: "info", rule: "meta-changed", path: `meta ${key}`, message: a === undefined ? "added" : b === undefined ? "removed" : "changed", before: a, after: b });
336
+ }
337
+ }
338
+ }
339
+ // ------------------------------------------------------------------ helpers
340
+ function byName(items) {
341
+ return new Map(items.map((x) => [x.name, x]));
342
+ }
343
+ /** For each custom type, the functions and events that reach it directly or through other types. */
344
+ function usedBy(i) {
345
+ const typeRefs = new Map(i.types.map((t) => [t.name, t.refs]));
346
+ const result = new Map();
347
+ for (const fn of i.functions) {
348
+ const seen = new Set();
349
+ const stack = [...fn.refs];
350
+ while (stack.length) {
351
+ const t = stack.pop();
352
+ if (seen.has(t))
353
+ continue;
354
+ seen.add(t);
355
+ stack.push(...(typeRefs.get(t) ?? []));
356
+ }
357
+ for (const t of seen) {
358
+ if (!result.has(t))
359
+ result.set(t, new Set());
360
+ result.get(t).add(fn.name);
361
+ }
362
+ }
363
+ // Event payloads count as uses too: a type an event carries is part of the interface.
364
+ for (const ev of i.events ?? []) {
365
+ const seen = new Set();
366
+ const stack = [...ev.refs];
367
+ while (stack.length) {
368
+ const t = stack.pop();
369
+ if (seen.has(t))
370
+ continue;
371
+ seen.add(t);
372
+ stack.push(...(typeRefs.get(t) ?? []));
373
+ }
374
+ for (const t of seen) {
375
+ if (!result.has(t))
376
+ result.set(t, new Set());
377
+ result.get(t).add(`event ${ev.name}`);
378
+ }
379
+ }
380
+ return new Map([...result].map(([k, v]) => [k, [...v].sort()]));
381
+ }
382
+ function mergeUsage(a, b) {
383
+ const out = new Map();
384
+ for (const k of new Set([...a.keys(), ...b.keys()])) {
385
+ out.set(k, [...new Set([...(a.get(k) ?? []), ...(b.get(k) ?? [])])].sort());
386
+ }
387
+ return out;
388
+ }
@@ -0,0 +1,15 @@
1
+ import type { ContractInterface, Snapshot } from "../model.ts";
2
+ export declare const RPC_URLS: Record<string, string>;
3
+ export interface Loaded {
4
+ wasm: Uint8Array<ArrayBuffer>;
5
+ label: string;
6
+ }
7
+ export declare function loadWasm(arg: string, opts: {
8
+ network?: string;
9
+ rpcUrl?: string;
10
+ }): Promise<Loaded>;
11
+ export declare function loadInterface(arg: string, opts: {
12
+ network?: string;
13
+ rpcUrl?: string;
14
+ }): Promise<ContractInterface>;
15
+ export declare function toSnapshot(i: ContractInterface): Snapshot;
@@ -0,0 +1,53 @@
1
+ // Resolves a CLI argument to a contract interface: a local Wasm file, a saved
2
+ // snapshot (.json), a deployed contract id, or a Wasm hash already uploaded to
3
+ // the network. Network access is read-only.
4
+ import { readFile } from "node:fs/promises";
5
+ import { basename } from "node:path";
6
+ import { rpc } from "@stellar/stellar-sdk";
7
+ import { interfaceFromWasm } from "./spec.js";
8
+ export const RPC_URLS = {
9
+ testnet: "https://soroban-testnet.stellar.org",
10
+ futurenet: "https://rpc-futurenet.stellar.org",
11
+ };
12
+ const CONTRACT_ID = /^C[A-Z2-7]{55}$/;
13
+ const WASM_HASH = /^[0-9a-f]{64}$/i;
14
+ export async function loadWasm(arg, opts) {
15
+ if (CONTRACT_ID.test(arg) || WASM_HASH.test(arg)) {
16
+ const server = new rpc.Server(rpcUrl(opts), { allowHttp: opts.rpcUrl?.startsWith("http://") ?? false });
17
+ const bytes = CONTRACT_ID.test(arg)
18
+ ? await server.getContractWasmByContractId(arg)
19
+ : await server.getContractWasmByHash(arg, "hex");
20
+ return { wasm: new Uint8Array(bytes), label: `${opts.network ?? "rpc"}:${arg}` };
21
+ }
22
+ const bytes = await readFile(arg).catch(() => {
23
+ throw new Error(`cannot read ${arg}`);
24
+ });
25
+ return { wasm: new Uint8Array(bytes), label: basename(arg) };
26
+ }
27
+ function rpcUrl(opts) {
28
+ if (opts.rpcUrl)
29
+ return opts.rpcUrl;
30
+ const url = opts.network ? RPC_URLS[opts.network] : undefined;
31
+ if (url)
32
+ return url;
33
+ if (opts.network)
34
+ throw new Error(`no default RPC for network "${opts.network}", pass --rpc-url`);
35
+ throw new Error("a contract id or Wasm hash needs --network or --rpc-url");
36
+ }
37
+ export async function loadInterface(arg, opts) {
38
+ if (arg.endsWith(".json")) {
39
+ const text = await readFile(arg, "utf8").catch(() => {
40
+ throw new Error(`cannot read ${arg}`);
41
+ });
42
+ const snap = JSON.parse(text);
43
+ if (snap.specguardSnapshot !== 1)
44
+ throw new Error(`${arg}: not a SpecGuard snapshot`);
45
+ const { specguardSnapshot: _, ...iface } = snap;
46
+ return { ...iface, source: basename(arg) };
47
+ }
48
+ const { wasm, label } = await loadWasm(arg, opts);
49
+ return interfaceFromWasm(wasm, label);
50
+ }
51
+ export function toSnapshot(i) {
52
+ return { specguardSnapshot: 1, ...i };
53
+ }
@@ -0,0 +1,2 @@
1
+ import type { ContractInterface } from "../model.ts";
2
+ export declare function interfaceFromWasm(wasm: Uint8Array<ArrayBuffer>, source: string): ContractInterface;
@@ -0,0 +1,96 @@
1
+ import { sha256 } from "@noble/hashes/sha2.js";
2
+ import { bytesToHex } from "@noble/hashes/utils.js";
3
+ import * as xdr from "@stellar/stellar-sdk/xdr";
4
+ import { ENV_META_SECTION, META_SECTION, SPEC_SECTION, readCustomSection } from "./wasm.js";
5
+ import { collectRefs, renderType } from "./types.js";
6
+ export function interfaceFromWasm(wasm, source) {
7
+ const specBytes = readCustomSection(wasm, SPEC_SECTION);
8
+ if (!specBytes) {
9
+ throw new Error(`${source}: no ${SPEC_SECTION} section, not a Soroban contract or built without a spec`);
10
+ }
11
+ const functions = [];
12
+ const types = [];
13
+ const events = [];
14
+ for (const entry of xdr.decodeStream(xdr.ScSpecEntry, specBytes)) {
15
+ const json = entry.toJSON();
16
+ const [kind] = Object.keys(json);
17
+ const e = json[kind];
18
+ switch (kind) {
19
+ case "function_v0":
20
+ functions.push({
21
+ name: e.name,
22
+ doc: e.doc,
23
+ inputs: e.inputs.map((i) => ({ name: i.name, type: renderType(i.type) })),
24
+ output: e.outputs.length ? renderType(e.outputs[0]) : "()",
25
+ refs: [...collectRefs({ inputs: e.inputs.map((i) => i.type), outputs: e.outputs })],
26
+ });
27
+ break;
28
+ case "udt_struct_v0":
29
+ types.push({
30
+ kind: "struct",
31
+ name: e.name,
32
+ doc: e.doc,
33
+ fields: e.fields.map((f) => ({ name: f.name, type: renderType(f.type) })),
34
+ refs: [...collectRefs(e.fields.map((f) => f.type))],
35
+ });
36
+ break;
37
+ case "udt_union_v0":
38
+ types.push({
39
+ kind: "union",
40
+ name: e.name,
41
+ doc: e.doc,
42
+ cases: e.cases.map((c) => "tuple_v0" in c
43
+ ? { name: c.tuple_v0.name, types: c.tuple_v0.type.map(renderType) }
44
+ : { name: c.void_v0.name, types: [] }),
45
+ refs: [...collectRefs(e.cases)],
46
+ });
47
+ break;
48
+ case "udt_enum_v0":
49
+ case "udt_error_enum_v0":
50
+ types.push({
51
+ kind: kind === "udt_enum_v0" ? "enum" : "error",
52
+ name: e.name,
53
+ doc: e.doc,
54
+ cases: e.cases.map((c) => ({ name: c.name, value: c.value })),
55
+ refs: [],
56
+ });
57
+ break;
58
+ case "event_v0":
59
+ events.push({
60
+ name: e.name,
61
+ doc: e.doc,
62
+ topics: e.prefix_topics,
63
+ params: e.params.map((p) => ({
64
+ name: p.name,
65
+ type: renderType(p.type),
66
+ location: p.location === "topic_list" ? "topic" : "data",
67
+ })),
68
+ format: e.data_format,
69
+ refs: [...collectRefs(e.params.map((p) => p.type))],
70
+ });
71
+ break;
72
+ }
73
+ }
74
+ const meta = {};
75
+ const metaBytes = readCustomSection(wasm, META_SECTION);
76
+ if (metaBytes) {
77
+ for (const entry of xdr.decodeStream(xdr.ScMetaEntry, metaBytes)) {
78
+ const { key, val } = entry.toJSON().sc_meta_v0;
79
+ meta[key] = val;
80
+ }
81
+ }
82
+ const envMeta = {};
83
+ const envBytes = readCustomSection(wasm, ENV_META_SECTION);
84
+ if (envBytes) {
85
+ for (const entry of xdr.decodeStream(xdr.ScEnvMetaEntry, envBytes)) {
86
+ const v = entry.toJSON().sc_env_meta_kind_interface_version;
87
+ if (v) {
88
+ envMeta.protocol = v.protocol;
89
+ envMeta.preRelease = v.pre_release;
90
+ }
91
+ }
92
+ }
93
+ // Plain-JS hash so the same code runs in the browser viewer.
94
+ const wasmHash = bytesToHex(sha256(wasm));
95
+ return { source, wasmHash, functions, types, events, meta, envMeta };
96
+ }
@@ -0,0 +1,7 @@
1
+ type Json = string | number | {
2
+ [key: string]: any;
3
+ };
4
+ export declare function renderType(t: Json): string;
5
+ /** Names of all custom types referenced anywhere inside a type. */
6
+ export declare function collectRefs(t: Json, out?: Set<string>): Set<string>;
7
+ export {};
@@ -0,0 +1,53 @@
1
+ // Spec types arrive as XDR-JSON: primitives are strings ("i128"), the rest are
2
+ // single-key objects ({ "option": { "value_type": ... } }). Rendering them in
3
+ // Rust syntax gives a stable string to compare and something readable to show.
4
+ const PRIMITIVES = {
5
+ val: "Val",
6
+ bool: "bool",
7
+ void: "()",
8
+ error: "Error",
9
+ timepoint: "Timepoint",
10
+ duration: "Duration",
11
+ bytes: "Bytes",
12
+ string: "String",
13
+ symbol: "Symbol",
14
+ address: "Address",
15
+ muxed_address: "MuxedAddress",
16
+ };
17
+ export function renderType(t) {
18
+ if (typeof t === "string")
19
+ return PRIMITIVES[t] ?? t;
20
+ if (typeof t !== "object" || t === null)
21
+ return String(t);
22
+ if ("option" in t)
23
+ return `Option<${renderType(t.option.value_type)}>`;
24
+ if ("result" in t)
25
+ return `Result<${renderType(t.result.ok_type)}, ${renderType(t.result.error_type)}>`;
26
+ if ("vec" in t)
27
+ return `Vec<${renderType(t.vec.element_type)}>`;
28
+ if ("map" in t)
29
+ return `Map<${renderType(t.map.key_type)}, ${renderType(t.map.value_type)}>`;
30
+ if ("tuple" in t)
31
+ return `(${t.tuple.value_types.map(renderType).join(", ")})`;
32
+ if ("bytes_n" in t)
33
+ return `BytesN<${t.bytes_n.n}>`;
34
+ if ("udt" in t)
35
+ return t.udt.name;
36
+ return JSON.stringify(t);
37
+ }
38
+ /** Names of all custom types referenced anywhere inside a type. */
39
+ export function collectRefs(t, out = new Set()) {
40
+ if (typeof t !== "object" || t === null)
41
+ return out;
42
+ if ("udt" in t) {
43
+ out.add(t.udt.name);
44
+ return out;
45
+ }
46
+ for (const v of Object.values(t)) {
47
+ if (Array.isArray(v))
48
+ v.forEach((x) => collectRefs(x, out));
49
+ else
50
+ collectRefs(v, out);
51
+ }
52
+ return out;
53
+ }
@@ -0,0 +1,4 @@
1
+ export declare const SPEC_SECTION = "contractspecv0";
2
+ export declare const META_SECTION = "contractmetav0";
3
+ export declare const ENV_META_SECTION = "contractenvmetav0";
4
+ export declare function readCustomSection(wasm: Uint8Array<ArrayBuffer>, name: string): Uint8Array | undefined;
@@ -0,0 +1,21 @@
1
+ // Soroban keeps the contract interface and metadata in Wasm custom sections.
2
+ // WebAssembly.Module validates the binary and exposes those sections without
3
+ // instantiating anything, so no contract code ever runs.
4
+ export const SPEC_SECTION = "contractspecv0";
5
+ export const META_SECTION = "contractmetav0";
6
+ export const ENV_META_SECTION = "contractenvmetav0";
7
+ export function readCustomSection(wasm, name) {
8
+ const mod = new WebAssembly.Module(wasm);
9
+ const sections = WebAssembly.Module.customSections(mod, name);
10
+ if (sections.length === 0)
11
+ return undefined;
12
+ // A well-formed contract has at most one of each; concatenate defensively.
13
+ const parts = sections.map((s) => new Uint8Array(s));
14
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
15
+ let offset = 0;
16
+ for (const p of parts) {
17
+ out.set(p, offset);
18
+ offset += p.length;
19
+ }
20
+ return out;
21
+ }