@fengce/sdk 0.1.0 → 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 ADDED
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0
4
+
5
+ - `check(client, safe, tx)`: runs the Safe's guard on a transaction (one `eth_call`, nothing sent) and returns
6
+ `{ allowed, reason, code?, limit?, guard, refusedTo?, detail? }`. Reason codes for FengceGuard v2 and FengceGuardV3:
7
+ `MAX_PER_BUY`, `CIRCUIT`, `TRADES_PER_HOUR`, `QUIET_HOURS`, `HOLD_LOCK`, `TILT_SHIELD`, `AGENT_CAP`,
8
+ `NOT_CONFIGURED`, `DELEGATECALL`, `ADMIN`, `OTHER`. Exports `V3_REASONS` and `MAX_BUY_PIN`.
9
+ - README: the app is getfengce.vercel.app.
10
+
11
+ ## 0.1.1
12
+
13
+ - `readCatalog` reads every Catalog entry in parallel (one round of calls; a batching transport sends them together)
14
+ instead of one call after another. Same result, in listing order.
15
+ - README: links to the app (Okun, getokun.vercel.app) and its engine page, and to this changelog.
16
+
17
+ ## 0.1.0
18
+
19
+ - First release: schemas and schema hashes, Quote certificates, Safe guard install calldata, local evaluation and
20
+ `evaluateTrace`, the `fengce-quote` CLI.
package/README.md CHANGED
@@ -1,7 +1,10 @@
1
1
  # @fengce/sdk
2
2
 
3
- TypeScript tools for [Fengce](https://github.com/pgreyy/fengce): TapeOut circuit schemas, Quote certificates and
4
- Safe guard install calldata. Built on [viem](https://viem.sh). Node 20 or later.
3
+ TypeScript tools for [Fengce](https://github.com/pgreyy/fengce): check a Safe transaction against its on-chain limits
4
+ before you send it, TapeOut circuit schemas, Quote certificates and Safe guard install calldata. Built on
5
+ [viem](https://viem.sh). Node 20 or later.
6
+
7
+ App: [getfengce.vercel.app](https://getfengce.vercel.app) (limits on your Safe) and the [docs](https://getfengce.vercel.app/docs/). Changes: [CHANGELOG.md](CHANGELOG.md).
5
8
 
6
9
  ## Install
7
10
 
@@ -14,6 +17,32 @@ npx fengce-quote <processor> <circuitId> --out quote.json # the Quote CLI
14
17
 
15
18
  From the repository instead: `cd sdk && npm ci && npm run build`.
16
19
 
20
+ ## Check a transaction before you send it
21
+
22
+ ```ts
23
+ import { createPublicClient, http } from "viem";
24
+ import { check } from "@fengce/sdk";
25
+
26
+ const client = createPublicClient({ transport: http("https://rpc.xlayer.tech") });
27
+ const r = await check(client, safe, { to: USDT0, data: transferCalldata });
28
+ // { allowed: false, reason: "MAX_PER_BUY", limit: 30000000n, guard: "0x9D2A…8E6e", refusedTo: "0x779D…3736" }
29
+ ```
30
+
31
+ `check` runs the Safe's own guard on the transaction (one `eth_call` with the Safe as sender; nothing is sent and no
32
+ signature is needed), so the answer is the one the Safe would give. Batches: pass the MultiSendCallOnly call with
33
+ `operation: 1`. A Safe without a guard returns `{ allowed: true, guard: null }`.
34
+
35
+ | `reason` | Meaning |
36
+ |---|---|
37
+ | `MAX_PER_BUY` | the max-per-buy circuit (NAND #2) refused: over the cap, paying USDT0; `limit` is the cap |
38
+ | `CIRCUIT` | another pinned policy circuit refused |
39
+ | `TRADES_PER_HOUR` | counter circuit #7: too many swaps this clock hour (UTC) |
40
+ | `QUIET_HOURS`, `HOLD_LOCK`, `TILT_SHIELD`, `AGENT_CAP` | FengceGuardV3 rules (`code` 3, 4, 5, 6) |
41
+ | `NOT_CONFIGURED` | a Fengce guard is installed but has no policy for this Safe |
42
+ | `DELEGATECALL` | a delegatecall other than MultiSendCallOnly |
43
+ | `ADMIN` | a Safe admin change that must wait for the timelock or recovery |
44
+ | `OTHER` | anything else (`detail` has the decoded error) |
45
+
17
46
  ## Schemas
18
47
 
19
48
  ```ts
@@ -25,7 +54,7 @@ encodeInputs(schema, { overLimit: true }); // "0x03": strict, LSB first, never t
25
54
  toLayout(schema); // the Schema.Layout struct for contract calls
26
55
  ```
27
56
 
28
- File format and binding sources: see `src/schema.ts` and `docs/INTEGRATION.md`. Examples:
57
+ File format and binding sources: see `contracts/src/schema.ts` and `docs/INTEGRATION.md`. Examples:
29
58
  `examples/nand-limit.schema.json`, `examples/comparator16.schema.json`, `examples/encode.ts`.
30
59
 
31
60
  ## Install calldata for a Safe
@@ -51,7 +80,7 @@ fengce-quote <processor> <circuitId> [--rpc URL] [--port N] [--out FILE] [--inpu
51
80
 
52
81
  Needs `anvil` (Foundry) on PATH. Starts a local fork of X Layer, deploys PinRegistry and FengceGuard on it,
53
82
  measures gas on the full Safe path (Safe execution overhead, pre-check and outcome check, reported separately),
54
- assigns a tier from the full Safe path (`src/tiers.json`: Green up to 1M gas, Amber up to 3.5M, Red above), pins the circuit on the fork with the resulting `certificateHash` and checks what
83
+ assigns a tier from the full Safe path (`contracts/src/tiers.json`: Green up to 1M gas, Amber up to 3.5M, Red above), pins the circuit on the fork with the resulting `certificateHash` and checks what
55
84
  the registry stored. Nothing is sent to the real chain. Programmatic use: `quote(env, processor, id, options)`.
56
85
 
57
86
  The certificate hash is keccak256 of the certificate's canonical JSON (`canonicalJson`: keys sorted, no
@@ -73,7 +102,7 @@ await preSign(client, { processor, circuitId, schema }, safe, { to, value, data
73
102
  The interpreter follows TAP-02 (NAND, LATCH with state, REF sub-circuits) on the netlist bytes read from chain.
74
103
  `scripts/differential.ts` compares it with on-chain `eval` on random inputs (`npm run test:live`);
75
104
  `scripts/trace-check.ts` compares `evaluateTrace` with on-chain `eval` (`npx tsx scripts/trace-check.ts`).
76
- `preSign` covers native transfers, ERC-20 transfer and approve offline; use the app's simulator for other calls.
105
+ `preSign` covers native transfers, ERC-20 transfer and approve offline; use the app's [Try it](https://getfengce.vercel.app/try/) page for real calls through a Safe.
77
106
 
78
107
  ## Development
79
108
 
@@ -81,8 +110,8 @@ The interpreter follows TAP-02 (NAND, LATCH with state, REF sub-circuits) on the
81
110
  |---|---|
82
111
  | `npm test` | Unit tests |
83
112
  | `npm run typecheck` | Type check |
84
- | `npm run sync-artifacts` | Refresh `src/artifacts.ts` after `forge build` in the repository root |
85
- | `npx tsx scripts/gen-vectors.ts` | Refresh `test/vectors/hashes.json` (read-only RPC calls) |
113
+ | `npm run sync-artifacts` | Refresh `contracts/src/artifacts.ts` after `forge build` in the repository root |
114
+ | `npx tsx scripts/gen-vectors.ts` | Refresh `contracts/test/vectors/hashes.json` (read-only RPC calls) |
86
115
 
87
116
  ## License
88
117
 
package/dist/catalog.js CHANGED
@@ -7,11 +7,11 @@ function toEntry(e) {
7
7
  /** Reads every entry of a Catalog contract. */
8
8
  export async function readCatalog(client, catalog) {
9
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;
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
15
  }
16
16
  /** Reads one entry by pin id (lister is the zero address if it is not listed). */
17
17
  export async function catalogEntry(client, catalog, pinId) {
@@ -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
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export { check, V3_REASONS, MAX_BUY_PIN, type CheckResult, type CheckTx, type ReasonCode } from "./check.js";
1
2
  export { quote, refClosure, circuitTree, certificateHash, canonicalJson, type Certificate, type TreeNode, type QuoteEnv, type QuoteOptions } from "./quote.js";
2
3
  export { parseRefs, type Ref } from "./netlist.js";
3
4
  export { TIERS, tierFor, type Tier } from "./tiers.js";
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export { check, V3_REASONS, MAX_BUY_PIN } from "./check.js";
1
2
  export { quote, refClosure, circuitTree, certificateHash, canonicalJson } from "./quote.js";
2
3
  export { parseRefs } from "./netlist.js";
3
4
  export { TIERS, tierFor } from "./tiers.js";
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@fengce/sdk",
3
- "version": "0.1.0",
4
- "description": "TypeScript SDK for Fengce: TapeOut circuit schemas, Quote certificates and Safe guard install calldata",
3
+ "version": "0.2.0",
4
+ "description": "TypeScript SDK for Fengce: check a Safe transaction against its on-chain limits (allowed, or the reason code), TapeOut circuit schemas, Quote certificates and guard install calldata",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
7
  "main": "dist/index.js",
@@ -18,7 +18,8 @@
18
18
  "files": [
19
19
  "dist",
20
20
  "README.md",
21
- "LICENSE"
21
+ "LICENSE",
22
+ "CHANGELOG.md"
22
23
  ],
23
24
  "engines": {
24
25
  "node": ">=20"