@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,41 @@
1
+ import { type Address, type Hex, type PublicClient } from "viem";
2
+ /** Tier names in Catalog.Tier order. */
3
+ export declare const CATALOG_TIERS: readonly ["Green", "Amber", "Red"];
4
+ export type CatalogTier = (typeof CATALOG_TIERS)[number];
5
+ export interface CatalogVector {
6
+ input: Hex;
7
+ expectedOutput: Hex;
8
+ /** stateful circuits only (run with step()); "0x" otherwise */
9
+ state: Hex;
10
+ }
11
+ /** Catalog.Manifest: what a lister submits. Every vector is run on-chain at listing. */
12
+ export interface CatalogManifest {
13
+ pinId: Hex;
14
+ description: string;
15
+ schemaHash: Hex;
16
+ vectors: CatalogVector[];
17
+ designer: Address;
18
+ installFee: bigint;
19
+ uri: string;
20
+ }
21
+ export interface CatalogEntry {
22
+ pinId: Hex;
23
+ certificateHash: Hex;
24
+ schemaHash: Hex;
25
+ vectorsHash: Hex;
26
+ allowVectors: number;
27
+ denyVectors: number;
28
+ measuredGas: bigint;
29
+ tier: CatalogTier;
30
+ lister: Address;
31
+ designer: Address;
32
+ installFee: bigint;
33
+ listedAt: bigint;
34
+ active: boolean;
35
+ description: string;
36
+ uri: string;
37
+ }
38
+ /** Reads every entry of a Catalog contract. */
39
+ export declare function readCatalog(client: PublicClient, catalog: Address): Promise<CatalogEntry[]>;
40
+ /** Reads one entry by pin id (lister is the zero address if it is not listed). */
41
+ export declare function catalogEntry(client: PublicClient, catalog: Address, pinId: Hex): Promise<CatalogEntry>;
@@ -0,0 +1,19 @@
1
+ import { CatalogArtifact } from "./artifacts.js";
2
+ /** Tier names in Catalog.Tier order. */
3
+ export const CATALOG_TIERS = ["Green", "Amber", "Red"];
4
+ function toEntry(e) {
5
+ return { ...e, tier: CATALOG_TIERS[Number(e.tier)] };
6
+ }
7
+ /** Reads every entry of a Catalog contract. */
8
+ export async function readCatalog(client, catalog) {
9
+ const n = (await client.readContract({ address: catalog, abi: CatalogArtifact.abi, functionName: "count" }));
10
+ const out = [];
11
+ for (let i = 0n; i < n; i++) {
12
+ out.push(toEntry(await client.readContract({ address: catalog, abi: CatalogArtifact.abi, functionName: "entryAt", args: [i] })));
13
+ }
14
+ return out;
15
+ }
16
+ /** Reads one entry by pin id (lister is the zero address if it is not listed). */
17
+ export async function catalogEntry(client, catalog, pinId) {
18
+ return toEntry(await client.readContract({ address: catalog, abi: CatalogArtifact.abi, functionName: "entryOf", args: [pinId] }));
19
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * fengce-quote: build a Quote certificate for a TapeOut circuit on X Layer.
4
+ *
5
+ * fengce-quote <processor> <circuitId> [--rpc URL] [--port N] [--out FILE]
6
+ * [--input 0xBYTES] [--schema FILE --values JSON]
7
+ *
8
+ * Starts a local anvil fork (needs `anvil` from Foundry on PATH), deploys PinRegistry and
9
+ * FengceGuard on the fork, measures gas on the real Safe -> guard -> circuit path, prints the
10
+ * certificate JSON and stops anvil. Nothing is sent to the real chain.
11
+ * --input / --schema: probe input to use when the circuit denies all-zero input.
12
+ */
13
+ import { spawn } from "node:child_process";
14
+ import { readFileSync, writeFileSync } from "node:fs";
15
+ import { createPublicClient, createWalletClient, getAddress, http } from "viem";
16
+ import { XLAYER } from "../abi.js";
17
+ import { canonicalJson, quote } from "../quote.js";
18
+ import { parseSchema } from "../schema.js";
19
+ function arg(name, def) {
20
+ const i = process.argv.indexOf(name);
21
+ return i > 0 ? process.argv[i + 1] : def;
22
+ }
23
+ const USAGE = "usage: fengce-quote <processor> <circuitId> [--rpc URL] [--port N] [--out FILE] [--input 0xBYTES] [--schema FILE --values JSON]";
24
+ async function main() {
25
+ const [processor, id] = process.argv.slice(2);
26
+ if (!processor || !id || processor.startsWith("--"))
27
+ throw new Error(USAGE);
28
+ const rpc = arg("--rpc", XLAYER.rpc);
29
+ const port = arg("--port", "8547");
30
+ const out = arg("--out");
31
+ const opts = {};
32
+ const input = arg("--input");
33
+ const schemaFile = arg("--schema");
34
+ if (input)
35
+ opts.input = input;
36
+ if (schemaFile) {
37
+ opts.schema = parseSchema(readFileSync(schemaFile, "utf8"));
38
+ opts.values = JSON.parse(arg("--values", "{}"));
39
+ }
40
+ const anvil = spawn("anvil", ["--fork-url", rpc, "--port", port, "--silent"], { stdio: "ignore" });
41
+ anvil.on("error", (e) => {
42
+ console.error(`could not start anvil (install Foundry): ${e.message}`);
43
+ process.exit(1);
44
+ });
45
+ const url = `http://127.0.0.1:${port}`;
46
+ try {
47
+ const fork = createPublicClient({ transport: http(url) });
48
+ for (let i = 0;; i++) {
49
+ try {
50
+ await fork.getBlockNumber();
51
+ break;
52
+ }
53
+ catch {
54
+ if (i > 120)
55
+ throw new Error("anvil did not start");
56
+ await new Promise((r) => setTimeout(r, 250));
57
+ }
58
+ }
59
+ const [account] = (await fork.request({ method: "eth_accounts" }));
60
+ const wallet = createWalletClient({ transport: http(url) });
61
+ const result = await quote({ fork: fork, wallet, account: getAddress(account) }, getAddress(processor), BigInt(id), opts);
62
+ const text = JSON.stringify(JSON.parse(canonicalJson(result)), null, 2);
63
+ if (out)
64
+ writeFileSync(out, text + "\n");
65
+ console.log(text);
66
+ }
67
+ finally {
68
+ anvil.kill();
69
+ }
70
+ }
71
+ main().catch((e) => {
72
+ console.error(e instanceof Error ? e.message : e);
73
+ process.exit(1);
74
+ });
@@ -0,0 +1,124 @@
1
+ import { type Address, type Hex, type PublicClient } from "viem";
2
+ import { type SchemaFile } from "./schema.js";
3
+ /** One decoded netlist record (TAP-02 section 2). */
4
+ export type NetRecord = {
5
+ op: "nand";
6
+ a: number;
7
+ b: number;
8
+ } | {
9
+ op: "latch";
10
+ d: number;
11
+ } | {
12
+ op: "ref";
13
+ cpu: Address;
14
+ id: bigint;
15
+ nIns: number;
16
+ nOuts: number;
17
+ ins: number[];
18
+ };
19
+ export interface LoadedCircuit {
20
+ cpu: Address;
21
+ id: bigint;
22
+ nIn: number;
23
+ nOut: number;
24
+ nState: number;
25
+ records: NetRecord[];
26
+ }
27
+ /** Strict full decoder (same rules as src/core/Netlist.sol). */
28
+ export declare function parseNetlist(netlist: Hex): NetRecord[];
29
+ /** Loads a circuit and, recursively, every circuit it references, from chain (cached). */
30
+ export declare function loadCircuit(client: PublicClient, cpu: Address, id: bigint, cache?: Map<string, LoadedCircuit>, blockNumber?: bigint): Promise<Map<string, LoadedCircuit>>;
31
+ /**
32
+ * Evaluates a circuit locally from its on-chain netlist bytes, the same way the processor's step() does.
33
+ * `input` and `state` are packed bit 0 first (missing bytes read as 0, extra bits ignored, as on chain).
34
+ * Returns the packed outputs and new state (exactly ceil(n/8) bytes, zero padding).
35
+ */
36
+ export declare function evaluateLocally(client: PublicClient, processor: Address, circuitId: bigint, input: Hex, state?: Hex, cache?: Map<string, LoadedCircuit>): Promise<{
37
+ output: Hex;
38
+ newState: Hex;
39
+ }>;
40
+ /** One record of a traced beat. Signal indices follow TAP-02: 0 = constant 0, 1 = constant 1, 2.. = inputs, then one
41
+ * signal per NAND or LATCH and nOuts signals per REF, in record order. */
42
+ export interface TraceRecord {
43
+ op: "nand" | "latch" | "ref";
44
+ /** signal indices read by this record (NAND: a, b; LATCH: d, read after the beat; REF: its inputs) */
45
+ ins: number[];
46
+ /** signal indices this record writes */
47
+ outs: number[];
48
+ /** topological level: 1 + the highest level of the signals it reads (constants, inputs and latch outputs are level 0) */
49
+ level: number;
50
+ /** REF only: the referenced circuit and its own trace for this beat */
51
+ ref?: {
52
+ cpu: Address;
53
+ id: bigint;
54
+ trace: CircuitTrace;
55
+ };
56
+ }
57
+ export interface CircuitTrace {
58
+ cpu: Address;
59
+ id: bigint;
60
+ nIn: number;
61
+ nOut: number;
62
+ nState: number;
63
+ /** value (0 or 1) of every signal */
64
+ values: number[];
65
+ /** level of every signal (0 for constants, inputs and latch outputs) */
66
+ levels: number[];
67
+ records: TraceRecord[];
68
+ /** signal indices of the outputs (the last nOut signals) */
69
+ outputs: number[];
70
+ /** highest level in this circuit */
71
+ depth: number;
72
+ newState: number[];
73
+ }
74
+ /**
75
+ * Evaluates a circuit like {@link evaluateLocally} and also returns every gate's output and its topological level
76
+ * (REF sub-circuits nested), for gate-by-gate display. `output` and `newState` are packed exactly as evaluateLocally
77
+ * returns them.
78
+ */
79
+ export declare function evaluateTrace(client: PublicClient, processor: Address, circuitId: bigint, input: Hex, state?: Hex, cache?: Map<string, LoadedCircuit>): Promise<{
80
+ output: Hex;
81
+ newState: Hex;
82
+ trace: CircuitTrace;
83
+ }>;
84
+ /** Facts for a plain native transfer, an ERC-20 transfer or an ERC-20 approve (the offline subset of TxFacts.decode). */
85
+ export declare function localFacts(account: Address, tx: {
86
+ to: Address;
87
+ value?: bigint;
88
+ data?: Hex;
89
+ }): {
90
+ account: `0x${string}`;
91
+ to: `0x${string}`;
92
+ value: bigint;
93
+ token: Address;
94
+ amount: bigint;
95
+ selector: string;
96
+ kind: number;
97
+ };
98
+ /**
99
+ * Before signing: decode the Safe transaction into facts, encode the circuit input with the policy schema,
100
+ * and evaluate the pinned circuit locally. Returns what the guard will decide (output bit 0), with no RPC
101
+ * write and no simulation contract. Covers the offline subset of facts; outcome facts are 0 here.
102
+ */
103
+ export declare function preSign(client: PublicClient, policy: {
104
+ processor: Address;
105
+ circuitId: bigint;
106
+ schema: SchemaFile;
107
+ }, account: Address, tx: {
108
+ to: Address;
109
+ value?: bigint;
110
+ data?: Hex;
111
+ }): Promise<{
112
+ facts: {
113
+ account: `0x${string}`;
114
+ to: `0x${string}`;
115
+ value: bigint;
116
+ token: Address;
117
+ amount: bigint;
118
+ selector: string;
119
+ kind: number;
120
+ };
121
+ input: `0x${string}`;
122
+ output: `0x${string}`;
123
+ decision: "allow" | "deny";
124
+ }>;
@@ -0,0 +1,221 @@
1
+ import { decodeFunctionData, getAddress, hexToBytes, parseAbi, toHex } from "viem";
2
+ import { processorAbi } from "./abi.js";
3
+ import { BINDING_SOURCES, encodeInputs, parseSchema } from "./schema.js";
4
+ /** Strict full decoder (same rules as src/core/Netlist.sol). */
5
+ export function parseNetlist(netlist) {
6
+ const b = hexToBytes(netlist);
7
+ const u24 = (i) => (b[i] << 16) | (b[i + 1] << 8) | b[i + 2];
8
+ const out = [];
9
+ let i = 0;
10
+ while (i < b.length) {
11
+ const op = b[i];
12
+ if (op === 0) {
13
+ if (b.length - i < 7)
14
+ throw new Error(`netlist truncated at ${i}`);
15
+ out.push({ op: "nand", a: u24(i + 1), b: u24(i + 4) });
16
+ i += 7;
17
+ }
18
+ else if (op === 1) {
19
+ if (b.length - i < 4)
20
+ throw new Error(`netlist truncated at ${i}`);
21
+ out.push({ op: "latch", d: u24(i + 1) });
22
+ i += 4;
23
+ }
24
+ else if (op === 2) {
25
+ if (b.length - i < 31)
26
+ throw new Error(`netlist truncated at ${i}`);
27
+ const nIns = b[i + 29];
28
+ const len = 31 + 3 * nIns;
29
+ if (b.length - i < len)
30
+ throw new Error(`netlist truncated at ${i}`);
31
+ const cpu = getAddress(toHex(b.slice(i + 1, i + 21)));
32
+ const id = BigInt(toHex(b.slice(i + 21, i + 29)));
33
+ const ins = [...Array(nIns).keys()].map((k) => u24(i + 31 + 3 * k));
34
+ out.push({ op: "ref", cpu, id, nIns, nOuts: b[i + 30], ins });
35
+ i += len;
36
+ }
37
+ else {
38
+ throw new Error(`bad opcode 0x${op.toString(16)} at ${i}`);
39
+ }
40
+ }
41
+ return out;
42
+ }
43
+ /** Loads a circuit and, recursively, every circuit it references, from chain (cached). */
44
+ export async function loadCircuit(client, cpu, id, cache = new Map(), blockNumber) {
45
+ const key = `${getAddress(cpu)}:${id}`;
46
+ if (cache.has(key))
47
+ return cache;
48
+ const [info, netlist] = await Promise.all([
49
+ client.readContract({ address: cpu, abi: processorAbi, functionName: "circuitInfo", args: [id], blockNumber }),
50
+ client.readContract({ address: cpu, abi: processorAbi, functionName: "netlist", args: [id], blockNumber }),
51
+ ]);
52
+ const [nIn, nOut, nState] = info;
53
+ const records = parseNetlist(netlist);
54
+ cache.set(key, { cpu: getAddress(cpu), id, nIn, nOut, nState, records });
55
+ for (const r of records)
56
+ if (r.op === "ref")
57
+ await loadCircuit(client, r.cpu, r.id, cache, blockNumber);
58
+ return cache;
59
+ }
60
+ const unpack = (hex, n) => {
61
+ const b = hexToBytes(hex);
62
+ return [...Array(n).keys()].map((i) => (i >> 3 < b.length ? (b[i >> 3] >> (i & 7)) & 1 : 0)); // lenient read, like the contracts
63
+ };
64
+ const pack = (bits) => {
65
+ const out = new Uint8Array(Math.ceil(bits.length / 8));
66
+ bits.forEach((v, i) => v && (out[i >> 3] |= 1 << (i & 7)));
67
+ return toHex(out);
68
+ };
69
+ /** One beat (TAP-02 section 4) on bit arrays. */
70
+ function beat(c, state, inputs, all) {
71
+ const s = [0, 1, ...inputs];
72
+ const newState = [...state];
73
+ const latches = [];
74
+ let st = 0;
75
+ for (const r of c.records) {
76
+ if (r.op === "nand")
77
+ s.push(1 - (s[r.a] & s[r.b]));
78
+ else if (r.op === "latch") {
79
+ latches.push({ stateIx: st, d: r.d });
80
+ s.push(state[st]);
81
+ st += 1;
82
+ }
83
+ else {
84
+ const sub = all.get(`${r.cpu}:${r.id}`);
85
+ const block = state.slice(st, st + sub.nState);
86
+ const res = beat(sub, block, r.ins.map((ix) => s[ix]), all);
87
+ res.newState.forEach((v, k) => (newState[st + k] = v));
88
+ s.push(...res.outputs);
89
+ st += sub.nState;
90
+ }
91
+ }
92
+ for (const l of latches)
93
+ newState[l.stateIx] = s[l.d];
94
+ return { newState, outputs: s.slice(s.length - c.nOut) };
95
+ }
96
+ /**
97
+ * Evaluates a circuit locally from its on-chain netlist bytes, the same way the processor's step() does.
98
+ * `input` and `state` are packed bit 0 first (missing bytes read as 0, extra bits ignored, as on chain).
99
+ * Returns the packed outputs and new state (exactly ceil(n/8) bytes, zero padding).
100
+ */
101
+ export async function evaluateLocally(client, processor, circuitId, input, state = "0x", cache) {
102
+ const all = await loadCircuit(client, processor, circuitId, cache);
103
+ const c = all.get(`${getAddress(processor)}:${circuitId}`);
104
+ const r = beat(c, unpack(state, c.nState), unpack(input, c.nIn), all);
105
+ return { output: pack(r.outputs), newState: pack(r.newState) };
106
+ }
107
+ function traceBeat(c, state, inputs, all) {
108
+ const values = [0, 1, ...inputs];
109
+ const levels = values.map(() => 0);
110
+ const newState = [...state];
111
+ const records = [];
112
+ const latches = [];
113
+ let st = 0;
114
+ let depth = 0;
115
+ for (const r of c.records) {
116
+ if (r.op === "nand") {
117
+ const level = 1 + Math.max(levels[r.a], levels[r.b]);
118
+ records.push({ op: "nand", ins: [r.a, r.b], outs: [values.length], level });
119
+ values.push(1 - (values[r.a] & values[r.b]));
120
+ levels.push(level);
121
+ depth = Math.max(depth, level);
122
+ }
123
+ else if (r.op === "latch") {
124
+ latches.push({ stateIx: st, d: r.d });
125
+ records.push({ op: "latch", ins: [r.d], outs: [values.length], level: 0 });
126
+ values.push(state[st]);
127
+ levels.push(0);
128
+ st += 1;
129
+ }
130
+ else {
131
+ const sub = all.get(`${r.cpu}:${r.id}`);
132
+ const t = traceBeat(sub, state.slice(st, st + sub.nState), r.ins.map((ix) => values[ix]), all);
133
+ t.newState.forEach((v, k) => (newState[st + k] = v));
134
+ const level = 1 + Math.max(0, ...r.ins.map((ix) => levels[ix]));
135
+ const outs = t.outputs.map((_, k) => values.length + k);
136
+ records.push({ op: "ref", ins: r.ins, outs, level, ref: { cpu: r.cpu, id: r.id, trace: t } });
137
+ for (const o of t.outputs) {
138
+ values.push(t.values[o]);
139
+ levels.push(level);
140
+ }
141
+ st += sub.nState;
142
+ depth = Math.max(depth, level);
143
+ }
144
+ }
145
+ for (const l of latches)
146
+ newState[l.stateIx] = values[l.d];
147
+ const outputs = [...Array(c.nOut).keys()].map((k) => values.length - c.nOut + k);
148
+ return { cpu: c.cpu, id: c.id, nIn: c.nIn, nOut: c.nOut, nState: c.nState, values, levels, records, outputs, depth, newState };
149
+ }
150
+ /**
151
+ * Evaluates a circuit like {@link evaluateLocally} and also returns every gate's output and its topological level
152
+ * (REF sub-circuits nested), for gate-by-gate display. `output` and `newState` are packed exactly as evaluateLocally
153
+ * returns them.
154
+ */
155
+ export async function evaluateTrace(client, processor, circuitId, input, state = "0x", cache) {
156
+ const all = await loadCircuit(client, processor, circuitId, cache);
157
+ const c = all.get(`${getAddress(processor)}:${circuitId}`);
158
+ const trace = traceBeat(c, unpack(state, c.nState), unpack(input, c.nIn), all);
159
+ return { output: pack(trace.outputs.map((o) => trace.values[o])), newState: pack(trace.newState), trace };
160
+ }
161
+ // ------------------------------------------------------------------ pre-sign check
162
+ const tokenAbi = parseAbi(["function transfer(address,uint256)", "function approve(address,uint256)"]);
163
+ /** Facts for a plain native transfer, an ERC-20 transfer or an ERC-20 approve (the offline subset of TxFacts.decode). */
164
+ export function localFacts(account, tx) {
165
+ const value = tx.value ?? 0n;
166
+ const data = tx.data ?? "0x";
167
+ const base = { account, to: tx.to, value, token: "0x0000000000000000000000000000000000000000", amount: value, selector: "0x00000000", kind: 0 };
168
+ if (data === "0x")
169
+ return base;
170
+ if (value !== 0n || data.length !== 2 + 68 * 2)
171
+ throw new Error("preSign handles native transfers, ERC-20 transfer and approve only; use the simulator for other calls");
172
+ const d = decodeFunctionData({ abi: tokenAbi, data });
173
+ const [who, amount] = d.args;
174
+ return { ...base, to: who, token: tx.to, amount, selector: data.slice(0, 10), kind: d.functionName === "transfer" ? 1 : 2 };
175
+ }
176
+ function sourceValue(f, source, param) {
177
+ switch (source) {
178
+ case "To": return BigInt(f.to);
179
+ case "Value": return f.value;
180
+ case "Token": return BigInt(f.token);
181
+ case "Amount": return f.amount;
182
+ case "Kind": return BigInt(f.kind);
183
+ case "AmountGt": return f.amount > param ? 1n : 0n;
184
+ case "ToIs": return BigInt(f.to) === param ? 1n : 0n;
185
+ case "TokenIs": return BigInt(f.token) === param ? 1n : 0n;
186
+ case "Selector": return BigInt(f.selector);
187
+ case "Actor":
188
+ case "TokenOut":
189
+ case "MinAmountOut":
190
+ case "Recipient":
191
+ case "Deadline":
192
+ case "Action":
193
+ case "Outflow":
194
+ case "AllowanceIncrease": return 0n;
195
+ case "ActorIs": return 0n;
196
+ case "RecipientIsForeign":
197
+ case "OutflowGt":
198
+ case "AllowanceIncreaseGt": return 0n;
199
+ default: throw new Error(`unknown source ${source}`);
200
+ }
201
+ }
202
+ /**
203
+ * Before signing: decode the Safe transaction into facts, encode the circuit input with the policy schema,
204
+ * and evaluate the pinned circuit locally. Returns what the guard will decide (output bit 0), with no RPC
205
+ * write and no simulation contract. Covers the offline subset of facts; outcome facts are 0 here.
206
+ */
207
+ export async function preSign(client, policy, account, tx) {
208
+ const schema = parseSchema(policy.schema);
209
+ if (!schema.bindings)
210
+ throw new Error("schema has no bindings");
211
+ if (!BINDING_SOURCES.length)
212
+ throw new Error("no sources");
213
+ const facts = localFacts(account, tx);
214
+ const values = {};
215
+ for (const b of schema.bindings)
216
+ values[b.field] = sourceValue(facts, b.source, BigInt(b.param ?? 0));
217
+ const input = encodeInputs(schema, values);
218
+ const { output } = await evaluateLocally(client, policy.processor, policy.circuitId, input);
219
+ const allow = (hexToBytes(output)[0] & 1) === 1;
220
+ return { facts, input, output, decision: allow ? "allow" : "deny" };
221
+ }
@@ -0,0 +1,9 @@
1
+ export { quote, refClosure, circuitTree, certificateHash, canonicalJson, type Certificate, type TreeNode, type QuoteEnv, type QuoteOptions } from "./quote.js";
2
+ export { parseRefs, type Ref } from "./netlist.js";
3
+ export { TIERS, tierFor, type Tier } from "./tiers.js";
4
+ export { parseSchema, toLayout, schemaHash, encodeInputs, lenientFieldValue, SchemaError, BINDING_SOURCES, type SchemaFile, type SchemaField, type SchemaBinding, type BindingSource, type FieldKind, type Layout, } from "./schema.js";
5
+ export { buildInstall, configInput, enabledModules, toMultiSend, domainSeparatorOf, InstallError, MIN_DELAYS, MULTI_SEND_CALL_ONLY, EXTENSIBLE_FALLBACK_HANDLER, PERMIT2, type InstallOptions, type SafeCall, } from "./install.js";
6
+ export { PinRegistryArtifact, FengceGuardArtifact, FengceSignatureVerifierArtifact, FengceStrictHandlerArtifact, CatalogArtifact, PolicySimulatorArtifact, TickArtifact, } from "./artifacts.js";
7
+ export { readCatalog, catalogEntry, CATALOG_TIERS, type CatalogEntry, type CatalogTier, type CatalogManifest, type CatalogVector } from "./catalog.js";
8
+ export { XLAYER, processorAbi } from "./abi.js";
9
+ export { parseNetlist, loadCircuit, evaluateLocally, evaluateTrace, preSign, localFacts, type NetRecord, type LoadedCircuit, type CircuitTrace, type TraceRecord, } from "./evaluate.js";
package/dist/index.js ADDED
@@ -0,0 +1,9 @@
1
+ export { quote, refClosure, circuitTree, certificateHash, canonicalJson } from "./quote.js";
2
+ export { parseRefs } from "./netlist.js";
3
+ export { TIERS, tierFor } from "./tiers.js";
4
+ export { parseSchema, toLayout, schemaHash, encodeInputs, lenientFieldValue, SchemaError, BINDING_SOURCES, } from "./schema.js";
5
+ export { buildInstall, configInput, enabledModules, toMultiSend, domainSeparatorOf, InstallError, MIN_DELAYS, MULTI_SEND_CALL_ONLY, EXTENSIBLE_FALLBACK_HANDLER, PERMIT2, } from "./install.js";
6
+ export { PinRegistryArtifact, FengceGuardArtifact, FengceSignatureVerifierArtifact, FengceStrictHandlerArtifact, CatalogArtifact, PolicySimulatorArtifact, TickArtifact, } from "./artifacts.js";
7
+ export { readCatalog, catalogEntry, CATALOG_TIERS } from "./catalog.js";
8
+ export { XLAYER, processorAbi } from "./abi.js";
9
+ export { parseNetlist, loadCircuit, evaluateLocally, evaluateTrace, preSign, localFacts, } from "./evaluate.js";
@@ -0,0 +1,80 @@
1
+ import { type Address, type Hex, type PublicClient } from "viem";
2
+ import { type SchemaFile } from "./schema.js";
3
+ /** MultiSendCallOnly v1.5.0 (same address on every chain with canonical Safe deployments). */
4
+ export declare const MULTI_SEND_CALL_ONLY: Address;
5
+ /** Safe ExtensibleFallbackHandler v1.5.0 (keeps a default path for unknown signature domains). */
6
+ export declare const EXTENSIBLE_FALLBACK_HANDLER: Address;
7
+ export declare const PERMIT2: Address;
8
+ /** EIP-712 domain separator of Permit2 or of an EIP-2612 token, read from the contract. */
9
+ export declare function domainSeparatorOf(client: PublicClient, contract: Address): Promise<Hex>;
10
+ export interface InstallOptions {
11
+ safe: Address;
12
+ guard: Address;
13
+ pinId: Hex;
14
+ schema: SchemaFile;
15
+ recoveryDelay: bigint;
16
+ recoveryWindow: bigint;
17
+ adminDelay: bigint;
18
+ preflightTokens?: Address[];
19
+ preflightSpenders?: Address[];
20
+ acceptExistingApprovals?: boolean;
21
+ /** configure() reverts if the Safe has modules enabled unless this is set (then emits a warning per module). */
22
+ acceptExistingModules?: boolean;
23
+ /**
24
+ * Off-chain signature path: install `handler` as the Safe's fallback handler and delegate each domain
25
+ * (Permit2 and EIP-2612 token domains, see domainSeparatorOf) to the Fengce verifier. Use
26
+ * FengceStrictHandler for Strict Signatures mode (unknown domains rejected), or
27
+ * EXTENSIBLE_FALLBACK_HANDLER to keep Safe's default path for other domains.
28
+ */
29
+ signatures?: {
30
+ handler: Address;
31
+ verifier: Address;
32
+ domains: Hex[];
33
+ };
34
+ }
35
+ export interface SafeCall {
36
+ to: Address;
37
+ value: bigint;
38
+ data: Hex;
39
+ operation: 0 | 1;
40
+ description: string;
41
+ }
42
+ export declare class InstallError extends Error {
43
+ }
44
+ /** On-chain minimums (src/safe/FengceLimits.sol); configure reverts below them. Seconds. */
45
+ export declare const MIN_DELAYS: {
46
+ readonly recoveryDelay: 172800n;
47
+ readonly recoveryWindow: 86400n;
48
+ readonly adminDelay: 86400n;
49
+ };
50
+ /** The FengceGuard.ConfigInput struct for `configure`, from a schema file with bindings. */
51
+ export declare function configInput(o: InstallOptions): {
52
+ pinId: `0x${string}`;
53
+ layout: import("./schema.js").Layout;
54
+ bindings: {
55
+ source: number;
56
+ param: bigint;
57
+ }[];
58
+ recoveryDelay: bigint;
59
+ recoveryWindow: bigint;
60
+ adminDelay: bigint;
61
+ preflightTokens: `0x${string}`[];
62
+ preflightSpenders: `0x${string}`[];
63
+ acceptExistingApprovals: boolean;
64
+ acceptExistingModules: boolean;
65
+ };
66
+ /** Modules currently enabled on a Safe (reads up to 50). */
67
+ export declare function enabledModules(client: PublicClient, safe: Address): Promise<Address[]>;
68
+ /**
69
+ * Builds the Safe transactions that install Fengce, in order: configure (Safe -> guard), optionally
70
+ * setFallbackHandler + setDomainVerifier per domain, then setGuard(guard), setModuleGuard(guard).
71
+ * It only builds calldata; it sends nothing.
72
+ * Refuses a Safe that already has modules enabled: a module can act before the module guard is
73
+ * installed, and Fengce's checks assume the owners know every module.
74
+ */
75
+ export declare function buildInstall(client: PublicClient, o: InstallOptions): Promise<{
76
+ calls: SafeCall[];
77
+ multiSend: SafeCall;
78
+ }>;
79
+ /** Packs plain calls into one delegatecall to MultiSendCallOnly. */
80
+ export declare function toMultiSend(calls: SafeCall[]): SafeCall;