@fengce/sdk 0.0.0-stage → 0.2.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.
package/dist/quote.js ADDED
@@ -0,0 +1,344 @@
1
+ import { hexToBytes, concat, encodeAbiParameters, encodeFunctionData, encodePacked, getAddress, keccak256, pad, toHex, zeroAddress, } from "viem";
2
+ import { XLAYER, processorAbi, proxyFactoryAbi, safeAbi } from "./abi.js";
3
+ import { CatalogArtifact, FengceGuardArtifact, FengceInspectorArtifact, PinRegistryArtifact } from "./artifacts.js";
4
+ import { catalogEntry } from "./catalog.js";
5
+ import { BINDING_SOURCES, encodeInputs, parseSchema, schemaHash, toLayout } from "./schema.js";
6
+ import { MIN_DELAYS } from "./install.js";
7
+ import { parseRefs } from "./netlist.js";
8
+ import { TIERS, tierFor } from "./tiers.js";
9
+ const MAX_CLOSURE = 64; // same bound as PinRegistry
10
+ const key = (cpu, id) => `${getAddress(cpu)}:${id}`;
11
+ /** Reads circuitInfo + netlist for every circuit reached through REF, with a cache. */
12
+ async function load(client, block, cpu, id, cache) {
13
+ const k = key(cpu, id);
14
+ if (!cache.has(k)) {
15
+ const [info, netlist] = await Promise.all([
16
+ client.readContract({ address: cpu, abi: processorAbi, functionName: "circuitInfo", args: [id], blockNumber: block }),
17
+ client.readContract({ address: cpu, abi: processorAbi, functionName: "netlist", args: [id], blockNumber: block }),
18
+ ]);
19
+ cache.set(k, { info, netlist: netlist, refs: parseRefs(netlist).refs });
20
+ }
21
+ return cache.get(k);
22
+ }
23
+ async function tree(client, block, cpu, id, cache, depth = 0) {
24
+ if (depth > MAX_CLOSURE)
25
+ throw new Error("REF tree deeper than MAX_CLOSURE");
26
+ const c = await load(client, block, cpu, id, cache);
27
+ const [nIn, nOut, nState, gateCount] = c.info;
28
+ const refs = [];
29
+ for (const r of c.refs)
30
+ refs.push(await tree(client, block, r.cpu, r.id, cache, depth + 1));
31
+ return { processor: getAddress(cpu), circuitId: id.toString(), netlistHash: keccak256(c.netlist), nIn, nOut, nState, gateCount, refs };
32
+ }
33
+ /** Breadth-first closure hash, exactly as PinRegistry._closure computes it. */
34
+ async function closure(client, block, root, id, cache) {
35
+ const order = [];
36
+ const seen = new Set();
37
+ const processors = [getAddress(root)];
38
+ const rootC = await load(client, block, root, id, cache);
39
+ order.push({ cpu: getAddress(root), id, hash: keccak256(rootC.netlist) });
40
+ seen.add(key(root, id));
41
+ for (let head = 0; head < order.length; head++) {
42
+ const c = await load(client, block, order[head].cpu, order[head].id, cache);
43
+ for (const r of c.refs) {
44
+ const k = key(r.cpu, r.id);
45
+ if (seen.has(k))
46
+ continue;
47
+ if (order.length === MAX_CLOSURE)
48
+ throw new Error("closure larger than MAX_CLOSURE");
49
+ seen.add(k);
50
+ const rc = await load(client, block, r.cpu, r.id, cache);
51
+ order.push({ cpu: getAddress(r.cpu), id: r.id, hash: keccak256(rc.netlist) });
52
+ if (!processors.includes(getAddress(r.cpu)))
53
+ processors.push(getAddress(r.cpu));
54
+ }
55
+ }
56
+ const parts = order.slice(1).map((e) => encodePacked(["address", "uint256", "bytes32"], [e.cpu, e.id, e.hash]));
57
+ return { refClosureHash: keccak256(parts.length ? concat(parts) : "0x"), processors };
58
+ }
59
+ /** The circuit and every circuit it references (REF), as a tree. */
60
+ export async function circuitTree(client, processor, circuitId, blockNumber) {
61
+ const block = blockNumber ?? (await client.getBlockNumber());
62
+ return tree(client, block, processor, circuitId, new Map());
63
+ }
64
+ /**
65
+ * The dependency closure of a circuit, computed exactly as PinRegistry.pin does: breadth-first over
66
+ * REF records, distinct (processor, id) pairs, root excluded from the hash.
67
+ */
68
+ export async function refClosure(client, processor, circuitId, blockNumber) {
69
+ const block = blockNumber ?? (await client.getBlockNumber());
70
+ return closure(client, block, processor, circuitId, new Map());
71
+ }
72
+ /** Canonical JSON: keys sorted at every level, no whitespace. certificateHash = keccak256 of it. */
73
+ export function canonicalJson(v) {
74
+ if (Array.isArray(v))
75
+ return `[${v.map(canonicalJson).join(",")}]`;
76
+ if (v && typeof v === "object") {
77
+ const o = v;
78
+ return `{${Object.keys(o).sort().map((k) => `${JSON.stringify(k)}:${canonicalJson(o[k])}`).join(",")}}`;
79
+ }
80
+ return JSON.stringify(v);
81
+ }
82
+ export function certificateHash(cert) {
83
+ return keccak256(toHex(canonicalJson(cert)));
84
+ }
85
+ const fieldsType = [
86
+ {
87
+ type: "tuple[]",
88
+ components: [
89
+ { name: "kind", type: "uint8" },
90
+ { name: "offset", type: "uint32" },
91
+ { name: "width", type: "uint32" },
92
+ { name: "fixedValue", type: "uint256" },
93
+ ],
94
+ },
95
+ ];
96
+ /** A probe layout covering every input bit with uint fields of up to 256 bits, all fed from the
97
+ * native value of the probe transfer. For nIn <= 256 the transfer value is the input itself; for
98
+ * wider circuits only the all-zero probe can use the full path. */
99
+ function probeLayout(netlistHash, nIn, input) {
100
+ const fields = [];
101
+ if (nIn <= 256) {
102
+ // Every input bit is a flag fixed to the probe input, so the pre-check and the outcome check (which runs
103
+ // with the transaction fields at zero) evaluate the same input.
104
+ const v = inputToInt(input);
105
+ for (let i = 0; i < nIn; i++)
106
+ fields.push({ kind: 2, offset: i, width: 1, fixedValue: (v >> BigInt(i)) & 1n });
107
+ return { layout: { netlistHash, nIn, fields }, schemaHash: schemaHash({ netlistHash, nIn, fields }), bindings: [] };
108
+ }
109
+ // Wide circuits: uint chunks fed from the transfer value (0), so only the all-zero probe fits.
110
+ for (let off = 0; off < nIn; off += 256)
111
+ fields.push({ kind: 0, offset: off, width: Math.min(256, nIn - off), fixedValue: 0n });
112
+ return { layout: { netlistHash, nIn, fields }, schemaHash: schemaHash({ netlistHash, nIn, fields }), bindings: fields.map(() => ({ source: 1, param: 0n })) };
113
+ }
114
+ /** Reads packed input bytes (LSB first) as an integer. */
115
+ function inputToInt(input) {
116
+ const bytes = hexToBytes(input);
117
+ let v = 0n;
118
+ for (let i = bytes.length - 1; i >= 0; i--)
119
+ v = (v << 8n) | BigInt(bytes[i]);
120
+ return v;
121
+ }
122
+ /**
123
+ * Builds the certificate for (processor, circuitId) on the fork, measures gas on the real
124
+ * Safe v1.5.0 -> FengceGuard -> circuit path, then pins the circuit on the fork with the resulting
125
+ * certificateHash and reads it back from PinRegistry.
126
+ */
127
+ export async function quote(env, processor, circuitId, opts = {}) {
128
+ const { fork, wallet, account } = env;
129
+ const block = await fork.getBlockNumber();
130
+ const cache = new Map();
131
+ const root = await tree(fork, block, processor, circuitId, cache);
132
+ const { refClosureHash, processors } = await closure(fork, block, processor, circuitId, cache);
133
+ const inLen = Math.ceil(root.nIn / 8);
134
+ let probeInput = toHex(new Uint8Array(inLen));
135
+ let probeSource = "zero";
136
+ let probeSchemaHash = null;
137
+ // With a schema that has bindings, Quote measures that exact schema: the guard is configured with its layout and
138
+ // bindings, and the probe is a native transfer whose value produces the given field values. Only the Value and
139
+ // Amount sources are supported (for a native transfer both equal the value), and all bound values must be equal.
140
+ let realProbe = null;
141
+ if (opts.schema) {
142
+ const sch = parseSchema(opts.schema);
143
+ if (sch.netlistHash !== root.netlistHash || sch.nIn !== root.nIn)
144
+ throw new Error("schema is bound to a different circuit (netlistHash or nIn differs)");
145
+ probeInput = encodeInputs(sch, opts.values ?? {});
146
+ probeSource = "schema";
147
+ probeSchemaHash = schemaHash(sch);
148
+ if (sch.bindings) {
149
+ const order = sch.fields.filter((f) => f.kind !== "flag").map((f) => f.name);
150
+ const bound = order.map((name) => sch.bindings.find((b) => b.field === name));
151
+ if (bound.some((b) => b.source !== "Value" && b.source !== "Amount")) {
152
+ throw new Error("a schema measured on the full path may bind fields only to Value or Amount (a native transfer carries them)");
153
+ }
154
+ const vals = new Set(order.map((n) => BigInt((opts.values ?? {})[n])));
155
+ if (vals.size !== 1)
156
+ throw new Error("all bound field values must be equal (they all come from the transfer value)");
157
+ realProbe = {
158
+ layout: toLayout(sch),
159
+ bindings: bound.map((b) => ({ source: BINDING_SOURCES.indexOf(b.source), param: BigInt(b.param ?? 0) })),
160
+ schemaHash: probeSchemaHash,
161
+ txValue: [...vals][0],
162
+ };
163
+ }
164
+ }
165
+ else if (opts.input) {
166
+ const b = hexToBytes(opts.input);
167
+ if (b.length !== inLen)
168
+ throw new Error(`input must be exactly ${inLen} byte(s) for nIn ${root.nIn}`);
169
+ if (root.nIn % 8 !== 0 && b[inLen - 1] >> root.nIn % 8 !== 0)
170
+ throw new Error("input has non-zero padding bits");
171
+ probeInput = opts.input;
172
+ probeSource = "input";
173
+ }
174
+ const send = async (req) => {
175
+ const hash = await wallet.writeContract({ account, chain: null, ...req });
176
+ const r = await fork.waitForTransactionReceipt({ hash });
177
+ if (r.status !== "success")
178
+ throw new Error(`tx failed: ${req.functionName}`);
179
+ return r;
180
+ };
181
+ const deploy = async (name, args) => {
182
+ const a = name === "PinRegistry" ? PinRegistryArtifact : name === "Catalog" ? CatalogArtifact : name === "FengceInspector" ? FengceInspectorArtifact : FengceGuardArtifact;
183
+ const hash = await wallet.deployContract({ abi: a.abi, bytecode: a.bytecode, args: args, account, chain: null });
184
+ const r = await fork.waitForTransactionReceipt({ hash });
185
+ if (!r.contractAddress)
186
+ throw new Error(`deploy failed: ${name}`);
187
+ return { address: r.contractAddress, abi: a.abi };
188
+ };
189
+ const registry = await deploy("PinRegistry", [XLAYER.tapeoutFactory]);
190
+ const guard = await deploy("FengceGuard", [registry.address, 30000000n]);
191
+ const inspector = await deploy("FengceInspector", [[guard.address]]);
192
+ let gas = {
193
+ method: "eth_estimateGas",
194
+ path: "full Safe path: Safe v1.5.0 execTransaction (native transfer carrying the probe) -> FengceGuard pre-check (PinRegistry.isPinned -> eval of the probe input) -> execution -> FengceInspector outcome check (snapshot, verify, eval)",
195
+ probeInput,
196
+ probeSource,
197
+ probeSchemaHash,
198
+ probeAllowed: null,
199
+ fullPath: null,
200
+ safeOverhead: null,
201
+ preCheck: null,
202
+ outcomeCheck: null,
203
+ evalCall: null,
204
+ intentEval: null,
205
+ outcomeEval: null,
206
+ tierBasis: null,
207
+ };
208
+ let tier;
209
+ let tierReason;
210
+ if (root.nState > 0) {
211
+ tier = "Unsupported";
212
+ tierReason = "circuit has state (LATCH): eval reverts with 'has latch: use step'; it runs as a stateful policy through Tick (step()), so it gets no eval-path gas tier";
213
+ }
214
+ else {
215
+ gas.evalCall = (await fork.estimateContractGas({ address: processor, abi: processorAbi, functionName: "eval", args: [circuitId, probeInput], account })).toString();
216
+ // Probe pin (certificateHash 0); Safes owned by the anvil account.
217
+ const p = realProbe ?? { ...probeLayout(root.netlistHash, root.nIn, probeInput), txValue: 0n };
218
+ const pinR = await send({ address: registry.address, abi: registry.abi, functionName: "pin", args: [processor, circuitId, p.schemaHash, pad("0x", { size: 32 })] });
219
+ const pinId = pinR.logs.find((l) => l.address.toLowerCase() === registry.address.toLowerCase()).topics[1];
220
+ const sig = concat([pad(account, { size: 32 }), pad("0x", { size: 32 }), "0x01"]);
221
+ const execArgs = (to, data, value = 0n) => [to, value, data, 0, 0n, 0n, 0n, zeroAddress, zeroAddress, sig];
222
+ const recipient = getAddress("0x00000000000000000000000000000000000f3c3e");
223
+ const newSafe = async (tag) => {
224
+ const init = encodeFunctionData({ abi: safeAbi, functionName: "setup", args: [[account], 1n, zeroAddress, "0x", XLAYER.fallbackHandler, zeroAddress, 0n, zeroAddress] });
225
+ const salt = BigInt(keccak256(toHex(`fengce-quote-${processor}-${circuitId}-${block}-${tag}`)));
226
+ const sim = await fork.simulateContract({ address: XLAYER.safeProxyFactory, abi: proxyFactoryAbi, functionName: "createProxyWithNonce", args: [XLAYER.safeL2, init, salt], account });
227
+ await send({ address: XLAYER.safeProxyFactory, abi: proxyFactoryAbi, functionName: "createProxyWithNonce", args: [XLAYER.safeL2, init, salt] });
228
+ await fork.request({ method: "anvil_setBalance", params: [sim.result, toHex(p.txValue + 10n ** 18n)] });
229
+ return sim.result;
230
+ };
231
+ const cfg = {
232
+ pinId, layout: p.layout, bindings: p.bindings, ...MIN_DELAYS,
233
+ preflightTokens: [], preflightSpenders: [], acceptExistingApprovals: false, acceptExistingModules: false,
234
+ };
235
+ const setGuardAbi = [{ type: "function", name: "setGuard", inputs: [{ name: "g", type: "address" }], outputs: [], stateMutability: "nonpayable" }];
236
+ const install = async (safe, withInspector) => {
237
+ if (withInspector) {
238
+ // The Inspector watches native currency (the probe is a native transfer).
239
+ const watch = encodeAbiParameters([{ type: "address[]" }, { type: "address[]" }], [[zeroAddress], []]);
240
+ await send({ address: safe, abi: safeAbi, functionName: "execTransaction", args: execArgs(guard.address, encodeFunctionData({ abi: guard.abi, functionName: "configureInspector", args: [inspector.address, watch] })) });
241
+ }
242
+ await send({ address: safe, abi: safeAbi, functionName: "execTransaction", args: execArgs(guard.address, encodeFunctionData({ abi: guard.abi, functionName: "configure", args: [cfg] })) });
243
+ await send({ address: safe, abi: safeAbi, functionName: "execTransaction", args: execArgs(safe, encodeFunctionData({ abi: setGuardAbi, functionName: "setGuard", args: [guard.address] })) });
244
+ };
245
+ const estimate = async (safe) => fork.estimateContractGas({ address: safe, abi: safeAbi, functionName: "execTransaction", args: execArgs(recipient, "0x", p.txValue), account });
246
+ // Three measurements of the same transfer: no guard; guard pre-check only; pre-check + outcome check.
247
+ const safeA = await newSafe("pre");
248
+ const overhead = await estimate(safeA);
249
+ gas.safeOverhead = overhead.toString();
250
+ const fullPathPossible = realProbe !== null || root.nIn <= 256 || inputToInt(probeInput) === 0n;
251
+ try {
252
+ if (!fullPathPossible)
253
+ throw new Error("wide input");
254
+ await install(safeA, false);
255
+ const pre = await estimate(safeA);
256
+ const safeB = await newSafe("full");
257
+ await install(safeB, true);
258
+ const full = await estimate(safeB);
259
+ gas.fullPath = full.toString();
260
+ gas.preCheck = (pre - overhead).toString();
261
+ gas.outcomeCheck = (full - pre).toString();
262
+ gas.probeAllowed = true;
263
+ }
264
+ catch {
265
+ // The circuit denies the probe input (the Safe transaction reverts and cannot be estimated), or a non-zero
266
+ // input is wider than 256 bits. Fall back to the guard's evaluation path, which returns instead of reverting.
267
+ gas.probeAllowed = fullPathPossible ? false : null;
268
+ gas.path = fullPathPossible
269
+ ? "FengceGuard.evaluate (PinRegistry.isPinned -> eval); the full Safe path reverts because the circuit denies the probe input"
270
+ : "FengceGuard.evaluate (PinRegistry.isPinned -> eval); a non-zero probe wider than 256 inputs is not supported on the full path";
271
+ gas.fullPath = (await fork.estimateContractGas({ address: guard.address, abi: guard.abi, functionName: "evaluate", args: [pinId, probeInput], account })).toString();
272
+ }
273
+ const safe = safeA;
274
+ // Each evaluation alone: intent (pin checks + eval) and outcome (the same circuit on outcome facts).
275
+ gas.intentEval = (await fork.estimateContractGas({ address: guard.address, abi: guard.abi, functionName: "evaluate", args: [pinId, probeInput], account })).toString();
276
+ const outcomeFacts = {
277
+ kind: 3, to: zeroAddress, value: 0n, token: zeroAddress, amount: 0n, selector: "0x00000000", account: safe, actor: zeroAddress,
278
+ tokenOut: zeroAddress, minAmountOut: 0n, recipient: zeroAddress, deadline: 0n, action: 0, outflow: 0n, allowanceIncrease: 0n,
279
+ };
280
+ try {
281
+ gas.outcomeEval = (await fork.estimateContractGas({ address: guard.address, abi: guard.abi, functionName: "checkContext", args: [safe, outcomeFacts], account })).toString();
282
+ }
283
+ catch {
284
+ gas.outcomeEval = gas.intentEval; // the circuit denies the zero outcome; its evaluation cost equals the intent pass
285
+ }
286
+ if (gas.probeAllowed) {
287
+ gas.tierBasis = "full Safe path";
288
+ tier = tierFor(BigInt(gas.fullPath));
289
+ tierReason = `full Safe path: ${gas.fullPath} gas = Safe execution overhead ${gas.safeOverhead} + pre-check ${gas.preCheck} + outcome check ${gas.outcomeCheck}`;
290
+ }
291
+ else {
292
+ const total = BigInt(gas.intentEval) + BigInt(gas.outcomeEval);
293
+ gas.tierBasis = "eval gas: intentEval + outcomeEval (full Safe path not measurable with this probe)";
294
+ tier = tierFor(total);
295
+ tierReason = `intent ${gas.intentEval} + outcome ${gas.outcomeEval} = ${total} gas (the full Safe path could not be estimated with this probe)`;
296
+ }
297
+ }
298
+ const cert = {
299
+ format: "fengce-quote/1",
300
+ chainId: await fork.getChainId(),
301
+ block: block.toString(),
302
+ processor: getAddress(processor),
303
+ circuitId: circuitId.toString(),
304
+ circuit: { nIn: root.nIn, nOut: root.nOut, nState: root.nState, gateCount: root.gateCount, netlistHash: root.netlistHash },
305
+ refClosureHash,
306
+ processors,
307
+ dependencyTree: root,
308
+ gas,
309
+ tier,
310
+ tierReason,
311
+ tierThresholds: { greenMaxGas: TIERS.greenMaxGas.toString(), amberMaxGas: TIERS.amberMaxGas.toString() },
312
+ };
313
+ const certHash = certificateHash(cert);
314
+ // Cross-check: pin with this certificateHash on the fork and read back what PinRegistry stored.
315
+ const r = await send({ address: registry.address, abi: registry.abi, functionName: "pin", args: [processor, circuitId, pad("0x", { size: 32 }), certHash] });
316
+ const pinIdCheck = r.logs.find((l) => l.address.toLowerCase() === registry.address.toLowerCase()).topics[1];
317
+ const stored = await fork.readContract({ address: registry.address, abi: registry.abi, functionName: "circuitPin", args: [pinIdCheck] });
318
+ // Catalog: list the pin with the probe as a test vector (run on-chain at listing), read it back through
319
+ // the SDK reader, and compare its certificate hash and tier with this certificate.
320
+ let catalogCheck = { skipped: "circuit has state; eval-based listing does not apply" };
321
+ if (root.nState === 0) {
322
+ const catalog = await deploy("Catalog", [registry.address, 30000000n, account]);
323
+ const out = (await fork.readContract({ address: guard.address, abi: guard.abi, functionName: "evaluate", args: [pinIdCheck, probeInput] }));
324
+ const manifest = {
325
+ pinId: pinIdCheck, description: "", schemaHash: pad("0x", { size: 32 }), vectors: [{ input: probeInput, expectedOutput: out, state: "0x" }],
326
+ designer: account, installFee: 0n, uri: "",
327
+ };
328
+ await send({ address: catalog.address, abi: catalog.abi, functionName: "list", args: [manifest] });
329
+ const entry = await catalogEntry(fork, catalog.address, pinIdCheck);
330
+ catalogCheck = {
331
+ certificateHash: entry.certificateHash, tier: entry.tier, measuredEvalGas: entry.measuredGas.toString(),
332
+ certificateHashMatches: entry.certificateHash === certHash, tierMatchesQuote: entry.tier === cert.tier,
333
+ };
334
+ }
335
+ const check = {
336
+ catalog: catalogCheck,
337
+ pinIdOnFork: pinIdCheck,
338
+ certificateHashStored: stored.certificateHash,
339
+ refClosureHashStored: stored.refClosureHash,
340
+ netlistHashStored: stored.netlistHash,
341
+ allMatch: stored.certificateHash === certHash && stored.refClosureHash === refClosureHash && stored.netlistHash === root.netlistHash,
342
+ };
343
+ return { certificate: cert, certificateHash: certHash, forkCheck: check };
344
+ }
@@ -0,0 +1,77 @@
1
+ import { type Hex } from "viem";
2
+ /**
3
+ * Schema file format "fengce-schema/1": the typed input layout of one circuit.
4
+ *
5
+ * {
6
+ * "format": "fengce-schema/1",
7
+ * "netlistHash": "0x…", // keccak256 of the circuit netlist the layout is bound to
8
+ * "nIn": 2, // circuit input count
9
+ * "fields": [
10
+ * { "name": "overLimit", "kind": "bool", "offset": 0, "width": 1 },
11
+ * { "name": "one", "kind": "flag", "offset": 1, "width": 1, "value": 1 }
12
+ * ],
13
+ * "bindings": [ { "field": "overLimit", "source": "AmountGt", "param": "100" } ] // optional, FengceGuard only
14
+ * }
15
+ *
16
+ * Kinds: "uint" (1..256 bits, value < 2^width), "bool" (1 bit, 0 or 1), "flag" (1 bit fixed by the
17
+ * schema in "value"; takes no caller value). Bits are packed least significant first (TAP-02).
18
+ * Every input bit must belong to exactly one field.
19
+ *
20
+ * schemaHash = keccak256(abi.encode(netlistHash, nIn, fields)) with fields as
21
+ * (uint8 kind, uint32 offset, uint32 width, uint256 fixedValue)[], kind uint=0 bool=1 flag=2.
22
+ * This equals Schema.hash in src/core/Schema.sol and is what PinRegistry stores as schemaHash.
23
+ * Field names and bindings are not part of the hash.
24
+ */
25
+ export type FieldKind = "uint" | "bool" | "flag";
26
+ export interface SchemaField {
27
+ name: string;
28
+ kind: FieldKind;
29
+ offset: number;
30
+ width: number;
31
+ value?: number | string;
32
+ }
33
+ /** FengceGuard fact sources (TxFacts.Source in src/core/TxFacts.sol), in enum order. */
34
+ export declare const BINDING_SOURCES: readonly ["To", "Value", "Token", "Amount", "Kind", "AmountGt", "ToIs", "TokenIs", "Selector", "Actor", "ActorIs", "TokenOut", "MinAmountOut", "Recipient", "RecipientIsForeign", "Deadline", "Action", "Outflow", "OutflowGt", "AllowanceIncrease", "AllowanceIncreaseGt"];
35
+ export type BindingSource = (typeof BINDING_SOURCES)[number];
36
+ export interface SchemaBinding {
37
+ field: string;
38
+ source: BindingSource;
39
+ param?: string | number;
40
+ }
41
+ export interface SchemaFile {
42
+ format: "fengce-schema/1";
43
+ netlistHash: Hex;
44
+ nIn: number;
45
+ fields: SchemaField[];
46
+ bindings?: SchemaBinding[];
47
+ }
48
+ /** The on-chain Schema.Layout struct, ready for viem calls. */
49
+ export interface Layout {
50
+ netlistHash: Hex;
51
+ nIn: number;
52
+ fields: {
53
+ kind: number;
54
+ offset: number;
55
+ width: number;
56
+ fixedValue: bigint;
57
+ }[];
58
+ }
59
+ export declare class SchemaError extends Error {
60
+ }
61
+ /** Parses and validates a schema (same rules as Schema.validate on-chain). Throws SchemaError. */
62
+ export declare function parseSchema(input: unknown): SchemaFile;
63
+ /** The on-chain Schema.Layout for this schema. */
64
+ export declare function toLayout(schema: SchemaFile): Layout;
65
+ /** keccak256(abi.encode(netlistHash, nIn, fields)), equal to Schema.hash on-chain. */
66
+ export declare function schemaHash(schema: SchemaFile | Layout): Hex;
67
+ /**
68
+ * Strict encoder: one value per non-flag field (by name), packed LSB first into exactly ceil(nIn/8)
69
+ * bytes. Throws on a missing or unknown name, a value wider than its field, or a bool that is not 0/1.
70
+ * It never truncates.
71
+ */
72
+ export declare function encodeInputs(schema: SchemaFile, values: Record<string, bigint | number | boolean | string>): Hex;
73
+ /**
74
+ * What a TapeOut processor actually reads from a value written into a field: only the low `width`
75
+ * bits (TAP-02 reads input leniently). Exposed to show the truncation that encodeInputs refuses.
76
+ */
77
+ export declare function lenientFieldValue(value: bigint, width: number): bigint;
package/dist/schema.js ADDED
@@ -0,0 +1,170 @@
1
+ import { encodeAbiParameters, isHex, keccak256, toHex } from "viem";
2
+ /** FengceGuard fact sources (TxFacts.Source in src/core/TxFacts.sol), in enum order. */
3
+ export const BINDING_SOURCES = [
4
+ "To",
5
+ "Value",
6
+ "Token",
7
+ "Amount",
8
+ "Kind",
9
+ "AmountGt",
10
+ "ToIs",
11
+ "TokenIs",
12
+ "Selector",
13
+ // policy context version 1 (docs/POLICY-INTERFACE.md)
14
+ "Actor",
15
+ "ActorIs",
16
+ "TokenOut",
17
+ "MinAmountOut",
18
+ "Recipient",
19
+ "RecipientIsForeign",
20
+ "Deadline",
21
+ "Action",
22
+ // policy context version 2: outcome facts (FengceInspector)
23
+ "Outflow",
24
+ "OutflowGt",
25
+ "AllowanceIncrease",
26
+ "AllowanceIncreaseGt",
27
+ ];
28
+ export class SchemaError extends Error {
29
+ }
30
+ const KIND_ID = { uint: 0, bool: 1, flag: 2 };
31
+ const MAX_IN = 65_536;
32
+ /** Parses and validates a schema (same rules as Schema.validate on-chain). Throws SchemaError. */
33
+ export function parseSchema(input) {
34
+ const s = (typeof input === "string" ? JSON.parse(input) : input);
35
+ if (!s || s.format !== "fengce-schema/1")
36
+ throw new SchemaError('format must be "fengce-schema/1"');
37
+ if (!isHex(s.netlistHash) || s.netlistHash.length !== 66)
38
+ throw new SchemaError("netlistHash must be a 32-byte hex string");
39
+ if (!Number.isInteger(s.nIn) || s.nIn < 0 || s.nIn > MAX_IN)
40
+ throw new SchemaError(`nIn must be an integer in 0..${MAX_IN}`);
41
+ if (!Array.isArray(s.fields))
42
+ throw new SchemaError("fields must be an array");
43
+ const names = new Set();
44
+ const taken = new Uint8Array(s.nIn);
45
+ let sum = 0;
46
+ s.fields.forEach((f, k) => {
47
+ if (typeof f.name !== "string" || !f.name)
48
+ throw new SchemaError(`field ${k}: name required`);
49
+ if (names.has(f.name))
50
+ throw new SchemaError(`field ${k}: duplicate name "${f.name}"`);
51
+ names.add(f.name);
52
+ if (!(f.kind in KIND_ID))
53
+ throw new SchemaError(`field ${f.name}: unknown kind "${f.kind}"`);
54
+ if (!Number.isInteger(f.offset) || f.offset < 0)
55
+ throw new SchemaError(`field ${f.name}: bad offset`);
56
+ if (f.kind === "uint") {
57
+ if (!Number.isInteger(f.width) || f.width < 1 || f.width > 256)
58
+ throw new SchemaError(`field ${f.name}: uint width must be 1..256`);
59
+ if (f.value !== undefined)
60
+ throw new SchemaError(`field ${f.name}: only flags have a value`);
61
+ }
62
+ else {
63
+ if (f.width !== 1)
64
+ throw new SchemaError(`field ${f.name}: ${f.kind} width must be 1`);
65
+ if (f.kind === "bool" && f.value !== undefined)
66
+ throw new SchemaError(`field ${f.name}: only flags have a value`);
67
+ if (f.kind === "flag" && !(BigInt(f.value ?? -1) === 0n || BigInt(f.value ?? -1) === 1n)) {
68
+ throw new SchemaError(`field ${f.name}: flag value must be 0 or 1`);
69
+ }
70
+ }
71
+ if (f.offset + f.width > s.nIn)
72
+ throw new SchemaError(`field ${f.name}: bits ${f.offset}..${f.offset + f.width - 1} are outside nIn ${s.nIn}`);
73
+ for (let b = f.offset; b < f.offset + f.width; b++) {
74
+ if (taken[b])
75
+ throw new SchemaError(`field ${f.name}: bit ${b} overlaps another field`);
76
+ taken[b] = 1;
77
+ }
78
+ sum += f.width;
79
+ });
80
+ if (sum < s.nIn)
81
+ throw new SchemaError(`unmapped bits: fields cover ${sum} of ${s.nIn} inputs`);
82
+ if (sum > s.nIn)
83
+ throw new SchemaError(`width mismatch: fields cover ${sum} bits, nIn is ${s.nIn}`);
84
+ for (const b of s.bindings ?? []) {
85
+ const f = s.fields.find((x) => x.name === b.field);
86
+ if (!f)
87
+ throw new SchemaError(`binding: unknown field "${b.field}"`);
88
+ if (f.kind === "flag")
89
+ throw new SchemaError(`binding: flag "${b.field}" takes no binding`);
90
+ if (!BINDING_SOURCES.includes(b.source))
91
+ throw new SchemaError(`binding ${b.field}: unknown source "${b.source}"`);
92
+ }
93
+ if (s.bindings) {
94
+ const bound = new Set(s.bindings.map((b) => b.field));
95
+ const need = s.fields.filter((f) => f.kind !== "flag");
96
+ if (bound.size !== s.bindings.length || need.some((f) => !bound.has(f.name)) || bound.size !== need.length) {
97
+ throw new SchemaError("bindings must cover every non-flag field exactly once");
98
+ }
99
+ }
100
+ return s;
101
+ }
102
+ /** The on-chain Schema.Layout for this schema. */
103
+ export function toLayout(schema) {
104
+ return {
105
+ netlistHash: schema.netlistHash,
106
+ nIn: schema.nIn,
107
+ fields: schema.fields.map((f) => ({
108
+ kind: KIND_ID[f.kind],
109
+ offset: f.offset,
110
+ width: f.width,
111
+ fixedValue: f.kind === "flag" ? BigInt(f.value) : 0n,
112
+ })),
113
+ };
114
+ }
115
+ const FIELDS_TYPE = {
116
+ type: "tuple[]",
117
+ components: [
118
+ { name: "kind", type: "uint8" },
119
+ { name: "offset", type: "uint32" },
120
+ { name: "width", type: "uint32" },
121
+ { name: "fixedValue", type: "uint256" },
122
+ ],
123
+ };
124
+ /** keccak256(abi.encode(netlistHash, nIn, fields)), equal to Schema.hash on-chain. */
125
+ export function schemaHash(schema) {
126
+ const l = "format" in schema ? toLayout(parseSchema(schema)) : schema;
127
+ return keccak256(encodeAbiParameters([{ type: "bytes32" }, { type: "uint32" }, FIELDS_TYPE], [l.netlistHash, l.nIn, l.fields]));
128
+ }
129
+ /**
130
+ * Strict encoder: one value per non-flag field (by name), packed LSB first into exactly ceil(nIn/8)
131
+ * bytes. Throws on a missing or unknown name, a value wider than its field, or a bool that is not 0/1.
132
+ * It never truncates.
133
+ */
134
+ export function encodeInputs(schema, values) {
135
+ const s = parseSchema(schema);
136
+ const bytes = new Uint8Array(Math.ceil(s.nIn / 8));
137
+ const known = new Set(s.fields.filter((f) => f.kind !== "flag").map((f) => f.name));
138
+ for (const k of Object.keys(values))
139
+ if (!known.has(k))
140
+ throw new SchemaError(`unknown or fixed field "${k}"`);
141
+ for (const f of s.fields) {
142
+ let v;
143
+ if (f.kind === "flag")
144
+ v = BigInt(f.value);
145
+ else {
146
+ if (!(f.name in values))
147
+ throw new SchemaError(`missing value for "${f.name}"`);
148
+ const raw = values[f.name];
149
+ v = typeof raw === "boolean" ? (raw ? 1n : 0n) : BigInt(raw);
150
+ if (v < 0n)
151
+ throw new SchemaError(`"${f.name}": negative value`);
152
+ if (v >> BigInt(f.width) !== 0n)
153
+ throw new SchemaError(`"${f.name}": value ${v} does not fit in ${f.width} bit(s)`);
154
+ }
155
+ for (let b = 0; b < f.width; b++) {
156
+ if ((v >> BigInt(b)) & 1n) {
157
+ const bit = f.offset + b;
158
+ bytes[bit >> 3] |= 1 << (bit & 7);
159
+ }
160
+ }
161
+ }
162
+ return toHex(bytes);
163
+ }
164
+ /**
165
+ * What a TapeOut processor actually reads from a value written into a field: only the low `width`
166
+ * bits (TAP-02 reads input leniently). Exposed to show the truncation that encodeInputs refuses.
167
+ */
168
+ export function lenientFieldValue(value, width) {
169
+ return value & ((1n << BigInt(width)) - 1n);
170
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Budget tiers in gas. The thresholds come from src/tiers.json, the same file the Catalog contract's
3
+ * constants are checked against (test/unit/TiersShared.t.sol), so the SDK and the chain agree.
4
+ * Quote applies them to the full Safe -> guard -> circuit path; the Catalog applies them to the gas of
5
+ * the circuit evaluation (pin checks included) measured on-chain at listing.
6
+ */
7
+ export declare const TIERS: {
8
+ readonly greenMaxGas: bigint;
9
+ readonly amberMaxGas: bigint;
10
+ };
11
+ export type Tier = "Green" | "Amber" | "Red";
12
+ export declare function tierFor(gas: bigint): Tier;
package/dist/tiers.js ADDED
@@ -0,0 +1,18 @@
1
+ import shared from "./tiers.json" with { type: "json" };
2
+ /**
3
+ * Budget tiers in gas. The thresholds come from src/tiers.json, the same file the Catalog contract's
4
+ * constants are checked against (test/unit/TiersShared.t.sol), so the SDK and the chain agree.
5
+ * Quote applies them to the full Safe -> guard -> circuit path; the Catalog applies them to the gas of
6
+ * the circuit evaluation (pin checks included) measured on-chain at listing.
7
+ */
8
+ export const TIERS = {
9
+ greenMaxGas: BigInt(shared.greenMaxGas),
10
+ amberMaxGas: BigInt(shared.amberMaxGas),
11
+ };
12
+ export function tierFor(gas) {
13
+ if (gas <= TIERS.greenMaxGas)
14
+ return "Green";
15
+ if (gas <= TIERS.amberMaxGas)
16
+ return "Amber";
17
+ return "Red";
18
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "greenMaxGas": 1000000,
3
+ "amberMaxGas": 3500000
4
+ }