@fengce/sdk 0.0.0-stage → 0.1.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,115 @@
1
+ import { concat, encodeFunctionData, encodePacked, getAddress, parseAbi, size, } from "viem";
2
+ import { FengceGuardArtifact } from "./artifacts.js";
3
+ import { BINDING_SOURCES, parseSchema, toLayout } from "./schema.js";
4
+ /** MultiSendCallOnly v1.5.0 (same address on every chain with canonical Safe deployments). */
5
+ export const MULTI_SEND_CALL_ONLY = "0xA83c336B20401Af773B6219BA5027174338D1836";
6
+ const SENTINEL = "0x0000000000000000000000000000000000000001";
7
+ const safeReadAbi = parseAbi([
8
+ "function getModulesPaginated(address start, uint256 pageSize) view returns (address[] array, address next)",
9
+ ]);
10
+ const safeAdminAbi = parseAbi([
11
+ "function setGuard(address guard)",
12
+ "function setModuleGuard(address moduleGuard)",
13
+ "function setFallbackHandler(address handler)",
14
+ "function setDomainVerifier(bytes32 domainSeparator, address verifier)",
15
+ ]);
16
+ const domainAbi = parseAbi(["function DOMAIN_SEPARATOR() view returns (bytes32)"]);
17
+ /** Safe ExtensibleFallbackHandler v1.5.0 (keeps a default path for unknown signature domains). */
18
+ export const EXTENSIBLE_FALLBACK_HANDLER = "0x85a8ca358D388530ad0fB95D0cb89Dd44Fc242c3";
19
+ export const PERMIT2 = "0x000000000022D473030F116dDEE9F6B43aC78BA3";
20
+ /** EIP-712 domain separator of Permit2 or of an EIP-2612 token, read from the contract. */
21
+ export async function domainSeparatorOf(client, contract) {
22
+ return client.readContract({ address: contract, abi: domainAbi, functionName: "DOMAIN_SEPARATOR" });
23
+ }
24
+ const multiSendAbi = parseAbi(["function multiSend(bytes transactions)"]);
25
+ export class InstallError extends Error {
26
+ }
27
+ /** On-chain minimums (src/safe/FengceLimits.sol); configure reverts below them. Seconds. */
28
+ export const MIN_DELAYS = { recoveryDelay: 172800n, recoveryWindow: 86400n, adminDelay: 86400n };
29
+ /** The FengceGuard.ConfigInput struct for `configure`, from a schema file with bindings. */
30
+ export function configInput(o) {
31
+ const s = parseSchema(o.schema);
32
+ if (!s.bindings)
33
+ throw new InstallError("schema has no bindings; FengceGuard needs one binding per non-flag field");
34
+ const order = s.fields.filter((f) => f.kind !== "flag").map((f) => f.name);
35
+ const bindings = order.map((name) => {
36
+ const b = s.bindings.find((x) => x.field === name);
37
+ return { source: BINDING_SOURCES.indexOf(b.source), param: BigInt(b.param ?? 0) };
38
+ });
39
+ for (const k of ["recoveryDelay", "recoveryWindow", "adminDelay"]) {
40
+ if (o[k] < MIN_DELAYS[k])
41
+ throw new InstallError(`${k} must be at least ${MIN_DELAYS[k]} seconds (on-chain minimum)`);
42
+ }
43
+ return {
44
+ pinId: o.pinId,
45
+ layout: toLayout(s),
46
+ bindings,
47
+ recoveryDelay: o.recoveryDelay,
48
+ recoveryWindow: o.recoveryWindow,
49
+ adminDelay: o.adminDelay,
50
+ preflightTokens: o.preflightTokens ?? [],
51
+ preflightSpenders: o.preflightSpenders ?? [],
52
+ acceptExistingApprovals: o.acceptExistingApprovals ?? false,
53
+ acceptExistingModules: o.acceptExistingModules ?? false,
54
+ };
55
+ }
56
+ /** Modules currently enabled on a Safe (reads up to 50). */
57
+ export async function enabledModules(client, safe) {
58
+ const [modules] = await client.readContract({ address: safe, abi: safeReadAbi, functionName: "getModulesPaginated", args: [SENTINEL, 50n] });
59
+ return [...modules];
60
+ }
61
+ /**
62
+ * Builds the Safe transactions that install Fengce, in order: configure (Safe -> guard), optionally
63
+ * setFallbackHandler + setDomainVerifier per domain, then setGuard(guard), setModuleGuard(guard).
64
+ * It only builds calldata; it sends nothing.
65
+ * Refuses a Safe that already has modules enabled: a module can act before the module guard is
66
+ * installed, and Fengce's checks assume the owners know every module.
67
+ */
68
+ export async function buildInstall(client, o) {
69
+ const modules = await enabledModules(client, o.safe);
70
+ if (modules.length > 0)
71
+ throw new InstallError(`Safe ${o.safe} has modules enabled (${modules.join(", ")}); disable them before installing Fengce`);
72
+ const guard = getAddress(o.guard);
73
+ const safe = getAddress(o.safe);
74
+ const calls = [
75
+ {
76
+ to: guard,
77
+ value: 0n,
78
+ data: encodeFunctionData({ abi: FengceGuardArtifact.abi, functionName: "configure", args: [configInput(o)] }),
79
+ operation: 0,
80
+ description: "FengceGuard.configure (called by the Safe)",
81
+ },
82
+ ];
83
+ // Handler and domain verifiers go in before the guard: afterwards each change needs the admin timelock.
84
+ if (o.signatures) {
85
+ if (o.signatures.domains.length === 0)
86
+ throw new InstallError("signatures.domains is empty");
87
+ calls.push({
88
+ to: safe, value: 0n, operation: 0, description: "Safe.setFallbackHandler",
89
+ data: encodeFunctionData({ abi: safeAdminAbi, functionName: "setFallbackHandler", args: [getAddress(o.signatures.handler)] }),
90
+ });
91
+ for (const d of o.signatures.domains) {
92
+ calls.push({
93
+ to: safe, value: 0n, operation: 0, description: `setDomainVerifier ${d.slice(0, 10)}…`,
94
+ data: encodeFunctionData({ abi: safeAdminAbi, functionName: "setDomainVerifier", args: [d, getAddress(o.signatures.verifier)] }),
95
+ });
96
+ }
97
+ }
98
+ calls.push({ to: safe, value: 0n, data: encodeFunctionData({ abi: safeAdminAbi, functionName: "setGuard", args: [guard] }), operation: 0, description: "Safe.setGuard" }, { to: safe, value: 0n, data: encodeFunctionData({ abi: safeAdminAbi, functionName: "setModuleGuard", args: [guard] }), operation: 0, description: "Safe.setModuleGuard" });
99
+ return { calls, multiSend: toMultiSend(calls) };
100
+ }
101
+ /** Packs plain calls into one delegatecall to MultiSendCallOnly. */
102
+ export function toMultiSend(calls) {
103
+ const packed = concat(calls.map((c) => {
104
+ if (c.operation !== 0)
105
+ throw new InstallError("MultiSendCallOnly accepts calls only");
106
+ return encodePacked(["uint8", "address", "uint256", "uint256", "bytes"], [0, c.to, c.value, BigInt(size(c.data)), c.data]);
107
+ }));
108
+ return {
109
+ to: MULTI_SEND_CALL_ONLY,
110
+ value: 0n,
111
+ data: encodeFunctionData({ abi: multiSendAbi, functionName: "multiSend", args: [packed] }),
112
+ operation: 1,
113
+ description: `MultiSendCallOnly batch of ${calls.length} calls`,
114
+ };
115
+ }
@@ -0,0 +1,18 @@
1
+ import { type Address, type Hex } from "viem";
2
+ /** One REF record of a TapeOut netlist (TAP-02 section 2). */
3
+ export interface Ref {
4
+ cpu: Address;
5
+ id: bigint;
6
+ nIns: number;
7
+ nOuts: number;
8
+ }
9
+ /**
10
+ * Strict netlist decoder, same rules as src/core/Netlist.sol:
11
+ * NAND 0x00 (7 bytes), LATCH 0x01 (4 bytes), REF 0x02 (31 + 3*nIns bytes); big-endian.
12
+ * Throws on an unknown opcode or a truncated record.
13
+ */
14
+ export declare function parseRefs(netlist: Hex): {
15
+ refs: Ref[];
16
+ nand: number;
17
+ latch: number;
18
+ };
@@ -0,0 +1,44 @@
1
+ import { bytesToHex, getAddress, hexToBytes } from "viem";
2
+ /**
3
+ * Strict netlist decoder, same rules as src/core/Netlist.sol:
4
+ * NAND 0x00 (7 bytes), LATCH 0x01 (4 bytes), REF 0x02 (31 + 3*nIns bytes); big-endian.
5
+ * Throws on an unknown opcode or a truncated record.
6
+ */
7
+ export function parseRefs(netlist) {
8
+ const b = hexToBytes(netlist);
9
+ const refs = [];
10
+ let nand = 0;
11
+ let latch = 0;
12
+ let i = 0;
13
+ while (i < b.length) {
14
+ const op = b[i];
15
+ if (op === 0x00) {
16
+ if (b.length - i < 7)
17
+ throw new Error(`netlist truncated at ${i}`);
18
+ nand++;
19
+ i += 7;
20
+ }
21
+ else if (op === 0x01) {
22
+ if (b.length - i < 4)
23
+ throw new Error(`netlist truncated at ${i}`);
24
+ latch++;
25
+ i += 4;
26
+ }
27
+ else if (op === 0x02) {
28
+ if (b.length - i < 31)
29
+ throw new Error(`netlist truncated at ${i}`);
30
+ const nIns = b[i + 29];
31
+ const len = 31 + 3 * nIns;
32
+ if (b.length - i < len)
33
+ throw new Error(`netlist truncated at ${i}`);
34
+ const cpu = getAddress(bytesToHex(b.slice(i + 1, i + 21)));
35
+ const id = BigInt(bytesToHex(b.slice(i + 21, i + 29)));
36
+ refs.push({ cpu, id, nIns, nOuts: b[i + 30] });
37
+ i += len;
38
+ }
39
+ else {
40
+ throw new Error(`bad opcode 0x${op.toString(16)} at ${i}`);
41
+ }
42
+ }
43
+ return { refs, nand, latch };
44
+ }
@@ -0,0 +1,94 @@
1
+ import { type Address, type Hex, type PublicClient, type WalletClient } from "viem";
2
+ import { type SchemaFile } from "./schema.js";
3
+ import { type Tier } from "./tiers.js";
4
+ export interface TreeNode {
5
+ processor: Address;
6
+ circuitId: string;
7
+ netlistHash: Hex;
8
+ nIn: number;
9
+ nOut: number;
10
+ nState: number;
11
+ gateCount: number;
12
+ refs: TreeNode[];
13
+ }
14
+ export interface Certificate {
15
+ format: "fengce-quote/1";
16
+ chainId: number;
17
+ block: string;
18
+ processor: Address;
19
+ circuitId: string;
20
+ circuit: {
21
+ nIn: number;
22
+ nOut: number;
23
+ nState: number;
24
+ gateCount: number;
25
+ netlistHash: Hex;
26
+ };
27
+ refClosureHash: Hex;
28
+ processors: Address[];
29
+ dependencyTree: TreeNode;
30
+ gas: {
31
+ method: string;
32
+ path: string;
33
+ probeInput: Hex;
34
+ probeSource: "zero" | "input" | "schema";
35
+ probeSchemaHash: Hex | null;
36
+ probeAllowed: boolean | null;
37
+ fullPath: string | null;
38
+ safeOverhead: string | null;
39
+ preCheck: string | null;
40
+ outcomeCheck: string | null;
41
+ evalCall: string | null;
42
+ intentEval: string | null;
43
+ outcomeEval: string | null;
44
+ tierBasis: string | null;
45
+ };
46
+ tier: Tier | "Unsupported";
47
+ tierReason: string;
48
+ tierThresholds: {
49
+ greenMaxGas: string;
50
+ amberMaxGas: string;
51
+ };
52
+ }
53
+ /** The circuit and every circuit it references (REF), as a tree. */
54
+ export declare function circuitTree(client: PublicClient, processor: Address, circuitId: bigint, blockNumber?: bigint): Promise<TreeNode>;
55
+ /**
56
+ * The dependency closure of a circuit, computed exactly as PinRegistry.pin does: breadth-first over
57
+ * REF records, distinct (processor, id) pairs, root excluded from the hash.
58
+ */
59
+ export declare function refClosure(client: PublicClient, processor: Address, circuitId: bigint, blockNumber?: bigint): Promise<{
60
+ refClosureHash: `0x${string}`;
61
+ processors: `0x${string}`[];
62
+ }>;
63
+ /** Canonical JSON: keys sorted at every level, no whitespace. certificateHash = keccak256 of it. */
64
+ export declare function canonicalJson(v: unknown): string;
65
+ export declare function certificateHash(cert: Certificate): Hex;
66
+ export interface QuoteOptions {
67
+ /** Probe input bytes (exactly ceil(nIn/8), zero padding). Used when the circuit denies all-zero input. */
68
+ input?: Hex;
69
+ /** Or: a schema for this circuit plus field values; the encoded bytes become the probe input. */
70
+ schema?: SchemaFile;
71
+ values?: Record<string, bigint | number | boolean | string>;
72
+ }
73
+ export interface QuoteEnv {
74
+ fork: PublicClient;
75
+ wallet: WalletClient;
76
+ account: Address;
77
+ }
78
+ /**
79
+ * Builds the certificate for (processor, circuitId) on the fork, measures gas on the real
80
+ * Safe v1.5.0 -> FengceGuard -> circuit path, then pins the circuit on the fork with the resulting
81
+ * certificateHash and reads it back from PinRegistry.
82
+ */
83
+ export declare function quote(env: QuoteEnv, processor: Address, circuitId: bigint, opts?: QuoteOptions): Promise<{
84
+ certificate: Certificate;
85
+ certificateHash: `0x${string}`;
86
+ forkCheck: {
87
+ catalog: Record<string, unknown>;
88
+ pinIdOnFork: `0x${string}`;
89
+ certificateHashStored: Hex;
90
+ refClosureHashStored: Hex;
91
+ netlistHashStored: Hex;
92
+ allMatch: boolean;
93
+ };
94
+ }>;
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
+ }