@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/CHANGELOG.md +20 -0
- package/LICENSE +21 -0
- package/README.md +117 -2
- package/dist/abi.d.ts +142 -0
- package/dist/abi.js +21 -0
- package/dist/artifacts.d.ts +5341 -0
- package/dist/artifacts.js +53 -0
- package/dist/catalog.d.ts +41 -0
- package/dist/catalog.js +19 -0
- package/dist/check.d.ts +38 -0
- package/dist/check.js +121 -0
- package/dist/cli/quote.d.ts +2 -0
- package/dist/cli/quote.js +74 -0
- package/dist/evaluate.d.ts +124 -0
- package/dist/evaluate.js +221 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +10 -0
- package/dist/install.d.ts +80 -0
- package/dist/install.js +115 -0
- package/dist/netlist.d.ts +18 -0
- package/dist/netlist.js +44 -0
- package/dist/quote.d.ts +94 -0
- package/dist/quote.js +344 -0
- package/dist/schema.d.ts +77 -0
- package/dist/schema.js +170 -0
- package/dist/tiers.d.ts +12 -0
- package/dist/tiers.js +18 -0
- package/dist/tiers.json +4 -0
- package/package.json +55 -4
|
@@ -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>;
|
package/dist/catalog.js
ADDED
|
@@ -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
|
+
// All entries in parallel (one round of calls; a batching transport sends them together), in listing order.
|
|
11
|
+
const reads = [];
|
|
12
|
+
for (let i = 0n; i < n; i++)
|
|
13
|
+
reads.push(client.readContract({ address: catalog, abi: CatalogArtifact.abi, functionName: "entryAt", args: [i] }));
|
|
14
|
+
return (await Promise.all(reads)).map(toEntry);
|
|
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
|
+
}
|
package/dist/check.d.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type Address, type Hex, type PublicClient } from "viem";
|
|
2
|
+
/** Reason codes. FengceGuardV3 reverts with FengceRefused(code); v2 errors are mapped to the same names. */
|
|
3
|
+
export type ReasonCode = "MAX_PER_BUY" | "CIRCUIT" | "TRADES_PER_HOUR" | "QUIET_HOURS" | "HOLD_LOCK" | "TILT_SHIELD" | "AGENT_CAP" | "NOT_CONFIGURED" | "DELEGATECALL" | "ADMIN" | "OTHER";
|
|
4
|
+
/** FengceGuardV3 reason codes (FengceRulesV3). */
|
|
5
|
+
export declare const V3_REASONS: Record<number, ReasonCode>;
|
|
6
|
+
export interface CheckTx {
|
|
7
|
+
to: Address;
|
|
8
|
+
value?: bigint;
|
|
9
|
+
data?: Hex;
|
|
10
|
+
/** 0 call (default), 1 delegatecall (MultiSendCallOnly batches) */
|
|
11
|
+
operation?: 0 | 1;
|
|
12
|
+
}
|
|
13
|
+
export interface CheckResult {
|
|
14
|
+
allowed: boolean;
|
|
15
|
+
reason: ReasonCode | null;
|
|
16
|
+
/** FengceGuardV3 numeric reason code, when there is one */
|
|
17
|
+
code?: number;
|
|
18
|
+
/** the Safe's transaction guard (null: no guard, nothing is checked) */
|
|
19
|
+
guard: Address | null;
|
|
20
|
+
/** for MAX_PER_BUY: the cap, in the token's base units (USDT0 has 6 decimals) */
|
|
21
|
+
limit?: bigint;
|
|
22
|
+
/** the call the guard refused (inside a batch it is the first refused call) */
|
|
23
|
+
refusedTo?: Address;
|
|
24
|
+
/** decoded revert, for logs */
|
|
25
|
+
detail?: string;
|
|
26
|
+
}
|
|
27
|
+
/** Pin of the max-per-buy circuit (processor 0x839b…574e #2) with its [over cap, paying USDT0] schema. */
|
|
28
|
+
export declare const MAX_BUY_PIN = "0xf503c66d7d2a5e35c0dc09c37631ecc68bc871684c478857f4b72ed62afeabda";
|
|
29
|
+
/**
|
|
30
|
+
* Would `safe` allow `tx`? Runs the Safe's guard on it (one eth_call; nothing is sent, no signature needed).
|
|
31
|
+
* `sender` is who would submit the Safe transaction (defaults to the first owner).
|
|
32
|
+
*
|
|
33
|
+
* const r = await check(client, safe, { to: USDT0, data: transferCalldata })
|
|
34
|
+
* // { allowed: false, reason: "MAX_PER_BUY", limit: 2000000n, guard: "0x…" }
|
|
35
|
+
*/
|
|
36
|
+
export declare function check(client: PublicClient, safe: Address, tx: CheckTx, opts?: {
|
|
37
|
+
sender?: Address;
|
|
38
|
+
}): Promise<CheckResult>;
|
package/dist/check.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// check(): would this Safe allow this transaction, and if not, why. One eth_call, nothing is sent.
|
|
2
|
+
//
|
|
3
|
+
// It runs the Safe's own guard (FengceGuard v2 or FengceGuardV3) exactly as the Safe would before executing:
|
|
4
|
+
// guard.checkTransaction(...) called with the Safe as msg.sender. State changes in an eth_call are discarded.
|
|
5
|
+
import { decodeErrorResult, encodeAbiParameters, getAddress, hexToBigInt, keccak256, numberToHex, pad, parseAbi } from "viem";
|
|
6
|
+
/** FengceGuardV3 reason codes (FengceRulesV3). */
|
|
7
|
+
export const V3_REASONS = { 1: "CIRCUIT", 2: "TRADES_PER_HOUR", 3: "QUIET_HOURS", 4: "HOLD_LOCK", 5: "TILT_SHIELD", 6: "AGENT_CAP", 7: "OTHER" };
|
|
8
|
+
/** keccak256("guard_manager.guard.address") */
|
|
9
|
+
const GUARD_SLOT = "0x4a204f620c8c5ccdca3fd54d003badd85ba500436a431f0cbda4f558c93c34c8";
|
|
10
|
+
/** Pin of the max-per-buy circuit (processor 0x839b…574e #2) with its [over cap, paying USDT0] schema. */
|
|
11
|
+
export const MAX_BUY_PIN = "0xf503c66d7d2a5e35c0dc09c37631ecc68bc871684c478857f4b72ed62afeabda";
|
|
12
|
+
const guardAbi = parseAbi([
|
|
13
|
+
"function checkTransaction(address to, uint256 value, bytes data, uint8 operation, uint256 safeTxGas, uint256 baseGas, uint256 gasPrice, address gasToken, address refundReceiver, bytes signatures, address msgSender)",
|
|
14
|
+
"function configOf(address safe) view returns (bool set, bytes32 pinId, uint64 recoveryDelay, uint64 recoveryWindow, uint64 adminDelay, address tick, bytes32 tickGroup)",
|
|
15
|
+
]);
|
|
16
|
+
const safeAbi = parseAbi(["function getOwners() view returns (address[])"]);
|
|
17
|
+
const errors = parseAbi([
|
|
18
|
+
"error FengceRefused(uint8 reason, address safe, address to)",
|
|
19
|
+
"error FengceDenied(address safe, address to)",
|
|
20
|
+
"error TickDenied(bytes32 groupId, address account)",
|
|
21
|
+
"error FengceNotConfigured(address safe)",
|
|
22
|
+
"error FengceDelegateCallDenied(address to)",
|
|
23
|
+
"error FengceSafeCallDenied(bytes4 selector)",
|
|
24
|
+
"error FengceGuardCallDenied(bytes4 selector)",
|
|
25
|
+
"error FengceInnerAdminDenied(address to)",
|
|
26
|
+
"error FengceModuleAdminDenied(address to)",
|
|
27
|
+
"error AdminNotReady(bytes32 id)",
|
|
28
|
+
"error RecoveryNotReady(address safe)",
|
|
29
|
+
"error RecoveryExpired(address safe)",
|
|
30
|
+
"error FengceNotAllOwners()",
|
|
31
|
+
]);
|
|
32
|
+
function revertData(e) {
|
|
33
|
+
let c = e;
|
|
34
|
+
for (let i = 0; i < 8 && c; i++) {
|
|
35
|
+
if (typeof c.data === "string" && c.data.startsWith("0x"))
|
|
36
|
+
return c.data;
|
|
37
|
+
if (c.data?.data && typeof c.data.data === "string")
|
|
38
|
+
return c.data.data;
|
|
39
|
+
c = c.cause;
|
|
40
|
+
}
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
/** The AmountGt threshold of a Safe's policy (the max per buy), read from the guard's storage (slot 5, bindings at +5). */
|
|
44
|
+
async function maxPerBuy(client, guard, safe) {
|
|
45
|
+
const base = hexToBigInt(keccak256(encodeAbiParameters([{ type: "address" }, { type: "uint256" }], [safe, 5n])));
|
|
46
|
+
const lenSlot = base + 5n;
|
|
47
|
+
const at = async (s) => hexToBigInt((await client.getStorageAt({ address: guard, slot: numberToHex(s, { size: 32 }) })) ?? "0x0");
|
|
48
|
+
const len = Number(await at(lenSlot));
|
|
49
|
+
if (!len || len > 32)
|
|
50
|
+
return undefined;
|
|
51
|
+
const data = hexToBigInt(keccak256(pad(numberToHex(lenSlot), { size: 32 })));
|
|
52
|
+
for (let i = 0; i < len; i++) {
|
|
53
|
+
const source = Number((await at(data + BigInt(2 * i))) & 0xffn);
|
|
54
|
+
if (source === 5)
|
|
55
|
+
return at(data + BigInt(2 * i + 1)); // TxFacts.Source.AmountGt
|
|
56
|
+
}
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Would `safe` allow `tx`? Runs the Safe's guard on it (one eth_call; nothing is sent, no signature needed).
|
|
61
|
+
* `sender` is who would submit the Safe transaction (defaults to the first owner).
|
|
62
|
+
*
|
|
63
|
+
* const r = await check(client, safe, { to: USDT0, data: transferCalldata })
|
|
64
|
+
* // { allowed: false, reason: "MAX_PER_BUY", limit: 2000000n, guard: "0x…" }
|
|
65
|
+
*/
|
|
66
|
+
export async function check(client, safe, tx, opts = {}) {
|
|
67
|
+
safe = getAddress(safe);
|
|
68
|
+
const raw = await client.getStorageAt({ address: safe, slot: GUARD_SLOT });
|
|
69
|
+
const guardWord = raw ? hexToBigInt(raw) : 0n;
|
|
70
|
+
if (guardWord === 0n)
|
|
71
|
+
return { allowed: true, reason: null, guard: null, detail: "no guard installed: the Safe checks nothing" };
|
|
72
|
+
const guard = getAddress(numberToHex(guardWord, { size: 20 }));
|
|
73
|
+
const sender = opts.sender ?? (await client.readContract({ address: safe, abi: safeAbi, functionName: "getOwners" }))[0];
|
|
74
|
+
const zero = "0x0000000000000000000000000000000000000000";
|
|
75
|
+
try {
|
|
76
|
+
await client.simulateContract({
|
|
77
|
+
account: safe,
|
|
78
|
+
address: guard,
|
|
79
|
+
abi: guardAbi,
|
|
80
|
+
functionName: "checkTransaction",
|
|
81
|
+
args: [tx.to, tx.value ?? 0n, tx.data ?? "0x", tx.operation ?? 0, 0n, 0n, 0n, zero, zero, "0x", sender],
|
|
82
|
+
});
|
|
83
|
+
return { allowed: true, reason: null, guard };
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
const data = revertData(e);
|
|
87
|
+
if (!data)
|
|
88
|
+
return { allowed: false, reason: "OTHER", guard, detail: e.message.split("\n")[0] };
|
|
89
|
+
let d;
|
|
90
|
+
try {
|
|
91
|
+
d = decodeErrorResult({ abi: errors, data });
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return { allowed: false, reason: "OTHER", guard, detail: data };
|
|
95
|
+
}
|
|
96
|
+
const detail = `${d.errorName}(${(d.args ?? []).map(String).join(", ")})`;
|
|
97
|
+
const capIfMaxBuy = async (r) => {
|
|
98
|
+
const cfg = (await client.readContract({ address: guard, abi: guardAbi, functionName: "configOf", args: [safe] }).catch(() => null));
|
|
99
|
+
if (cfg && String(cfg[1]).toLowerCase() === MAX_BUY_PIN)
|
|
100
|
+
return { ...r, reason: "MAX_PER_BUY", limit: await maxPerBuy(client, guard, safe) };
|
|
101
|
+
return r;
|
|
102
|
+
};
|
|
103
|
+
switch (d.errorName) {
|
|
104
|
+
case "FengceRefused": {
|
|
105
|
+
const code = Number(d.args[0]);
|
|
106
|
+
const r = { allowed: false, reason: V3_REASONS[code] ?? "OTHER", code, guard, refusedTo: d.args[2], detail };
|
|
107
|
+
return code === 1 ? capIfMaxBuy(r) : r;
|
|
108
|
+
}
|
|
109
|
+
case "FengceDenied":
|
|
110
|
+
return capIfMaxBuy({ allowed: false, reason: "CIRCUIT", guard, refusedTo: d.args[1], detail });
|
|
111
|
+
case "TickDenied":
|
|
112
|
+
return { allowed: false, reason: "TRADES_PER_HOUR", guard, detail };
|
|
113
|
+
case "FengceNotConfigured":
|
|
114
|
+
return { allowed: false, reason: "NOT_CONFIGURED", guard, detail };
|
|
115
|
+
case "FengceDelegateCallDenied":
|
|
116
|
+
return { allowed: false, reason: "DELEGATECALL", guard, detail };
|
|
117
|
+
default:
|
|
118
|
+
return { allowed: false, reason: "ADMIN", guard, detail };
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
@@ -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
|
+
}>;
|
package/dist/evaluate.js
ADDED
|
@@ -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
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { check, V3_REASONS, MAX_BUY_PIN, type CheckResult, type CheckTx, type ReasonCode } from "./check.js";
|
|
2
|
+
export { quote, refClosure, circuitTree, certificateHash, canonicalJson, type Certificate, type TreeNode, type QuoteEnv, type QuoteOptions } from "./quote.js";
|
|
3
|
+
export { parseRefs, type Ref } from "./netlist.js";
|
|
4
|
+
export { TIERS, tierFor, type Tier } from "./tiers.js";
|
|
5
|
+
export { parseSchema, toLayout, schemaHash, encodeInputs, lenientFieldValue, SchemaError, BINDING_SOURCES, type SchemaFile, type SchemaField, type SchemaBinding, type BindingSource, type FieldKind, type Layout, } from "./schema.js";
|
|
6
|
+
export { buildInstall, configInput, enabledModules, toMultiSend, domainSeparatorOf, InstallError, MIN_DELAYS, MULTI_SEND_CALL_ONLY, EXTENSIBLE_FALLBACK_HANDLER, PERMIT2, type InstallOptions, type SafeCall, } from "./install.js";
|
|
7
|
+
export { PinRegistryArtifact, FengceGuardArtifact, FengceSignatureVerifierArtifact, FengceStrictHandlerArtifact, CatalogArtifact, PolicySimulatorArtifact, TickArtifact, } from "./artifacts.js";
|
|
8
|
+
export { readCatalog, catalogEntry, CATALOG_TIERS, type CatalogEntry, type CatalogTier, type CatalogManifest, type CatalogVector } from "./catalog.js";
|
|
9
|
+
export { XLAYER, processorAbi } from "./abi.js";
|
|
10
|
+
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,10 @@
|
|
|
1
|
+
export { check, V3_REASONS, MAX_BUY_PIN } from "./check.js";
|
|
2
|
+
export { quote, refClosure, circuitTree, certificateHash, canonicalJson } from "./quote.js";
|
|
3
|
+
export { parseRefs } from "./netlist.js";
|
|
4
|
+
export { TIERS, tierFor } from "./tiers.js";
|
|
5
|
+
export { parseSchema, toLayout, schemaHash, encodeInputs, lenientFieldValue, SchemaError, BINDING_SOURCES, } from "./schema.js";
|
|
6
|
+
export { buildInstall, configInput, enabledModules, toMultiSend, domainSeparatorOf, InstallError, MIN_DELAYS, MULTI_SEND_CALL_ONLY, EXTENSIBLE_FALLBACK_HANDLER, PERMIT2, } from "./install.js";
|
|
7
|
+
export { PinRegistryArtifact, FengceGuardArtifact, FengceSignatureVerifierArtifact, FengceStrictHandlerArtifact, CatalogArtifact, PolicySimulatorArtifact, TickArtifact, } from "./artifacts.js";
|
|
8
|
+
export { readCatalog, catalogEntry, CATALOG_TIERS } from "./catalog.js";
|
|
9
|
+
export { XLAYER, processorAbi } from "./abi.js";
|
|
10
|
+
export { parseNetlist, loadCircuit, evaluateLocally, evaluateTrace, preSign, localFacts, } from "./evaluate.js";
|