@fangorn-network/sdk 2026.10.28 → 2026.11.3-dev

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.
Files changed (65) hide show
  1. package/README.md +36 -658
  2. package/lib/cli/cli.js +30 -356
  3. package/lib/cli/index.d.ts +1 -4
  4. package/lib/cli/index.js +2 -20
  5. package/lib/config.d.ts +163 -226
  6. package/lib/config.js +8 -35
  7. package/lib/contracts/data-registry/abi.d.ts +206 -6
  8. package/lib/contracts/data-registry/abi.js +236 -7
  9. package/lib/contracts/data-registry/index.d.ts +126 -2
  10. package/lib/contracts/data-registry/index.js +174 -1
  11. package/lib/contracts/index.d.ts +5 -8
  12. package/lib/contracts/index.js +4 -7
  13. package/lib/contracts/logs.d.ts +1 -1
  14. package/lib/contracts/logs.js +1 -1
  15. package/lib/contracts/{membership-registry → settlement-registry}/abi.d.ts +288 -637
  16. package/lib/contracts/{membership-registry → settlement-registry}/abi.js +326 -712
  17. package/lib/contracts/settlement-registry/index.d.ts +141 -0
  18. package/lib/contracts/settlement-registry/index.js +209 -0
  19. package/lib/crypto/aes.d.ts +2 -2
  20. package/lib/crypto/aes.js +4 -4
  21. package/lib/crypto/encryption.d.ts +8 -109
  22. package/lib/crypto/encryption.js +16 -114
  23. package/lib/crypto/paid.d.ts +104 -0
  24. package/lib/crypto/paid.js +147 -0
  25. package/lib/engine/index.d.ts +23 -12
  26. package/lib/engine/index.js +68 -29
  27. package/lib/engine/records.d.ts +4 -7
  28. package/lib/engine/records.js +6 -6
  29. package/lib/engine/test-helpers.d.ts +2 -3
  30. package/lib/engine/test-helpers.js +7 -5
  31. package/lib/erc8004.js +1 -4
  32. package/lib/fangorn.d.ts +64 -95
  33. package/lib/fangorn.js +106 -164
  34. package/lib/feed.d.ts +7 -8
  35. package/lib/feed.js +7 -8
  36. package/lib/index.d.ts +10 -14
  37. package/lib/index.js +9 -13
  38. package/lib/providers/storage/signed-url.d.ts +2 -10
  39. package/lib/providers/storage/signed-url.js +4 -14
  40. package/lib/providers/storage/types.d.ts +1 -1
  41. package/lib/providers/storage/utils.js +5 -3
  42. package/lib/test/key-server.d.ts +12 -0
  43. package/lib/test/key-server.js +30 -0
  44. package/lib/test/mem-registry.d.ts +14 -19
  45. package/lib/test/mem-registry.js +44 -37
  46. package/lib/test/sdk-suite.d.ts +1 -4
  47. package/lib/test/sdk-suite.js +16 -87
  48. package/lib/test/testbed.d.ts +5204 -5214
  49. package/lib/test/testbed.js +29 -56
  50. package/lib/types/index.d.ts +6 -11
  51. package/package.json +1 -4
  52. package/lib/contracts/app-registry/abi.d.ts +0 -1306
  53. package/lib/contracts/app-registry/abi.js +0 -1493
  54. package/lib/contracts/app-registry/index.d.ts +0 -200
  55. package/lib/contracts/app-registry/index.js +0 -325
  56. package/lib/contracts/membership-registry/index.d.ts +0 -79
  57. package/lib/contracts/membership-registry/index.js +0 -104
  58. package/lib/contracts/types.d.ts +0 -8
  59. package/lib/contracts/types.js +0 -10
  60. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +0 -1
  61. package/lib/harness/examples/hackmd/build-markdown-graph.js +0 -17
  62. package/lib/harness/index.d.ts +0 -58
  63. package/lib/harness/index.js +0 -73
  64. package/lib/registry.d.ts +0 -118
  65. package/lib/registry.js +0 -184
package/lib/cli/cli.js CHANGED
@@ -1,16 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import getNetwork, { nonBlank, toAppId } from "../config.js";
2
+ import getNetwork, { nonBlank } from "../config.js";
3
3
  import { agentCardUrl, parseAgentId } from "../erc8004.js";
4
- import { PublisherStatus } from "../contracts/types.js";
5
- import "../contracts/index.js";
6
4
  import { Fangorn } from "../fangorn.js";
7
- import { handleCancel, selectChain } from "./index.js";
8
- import { createPublicClient, formatEther, formatUnits, http, isAddress } from "viem";
5
+ import { handleCancel } from "./index.js";
6
+ import { createPublicClient, formatEther, http, isAddress } from "viem";
9
7
  import { privateKeyToAccount } from "viem/accounts";
10
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
11
- import { dirname, join } from "path";
12
8
  import { Command } from "commander";
13
9
  import { confirm, intro, outro, spinner, text } from "@clack/prompts";
10
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
11
+ import { dirname, join } from "path";
14
12
  import { homedir } from "os";
15
13
  import "dotenv/config";
16
14
 
@@ -34,15 +32,12 @@ function loadConfig() {
34
32
  const pinataJwt = process.env.PINATA_JWT;
35
33
  const pinataGateway = process.env.PINATA_GATEWAY;
36
34
  const signedUrlWorkerUrl = process.env.SIGNED_URL_WORKER_URL;
37
- const envAppId = nonBlank(process.env.FANGORN_APP_ID);
38
35
  const envChain = nonBlank(process.env.CHAIN_NAME);
39
36
  if (existsSync(CONFIG_PATH)) {
40
37
  const stored = readStoredConfig();
41
- const storedChain = stored.chainName === "Arbitrum Sepolia" ? "arbitrumSepolia" : stored.chainName;
42
38
  _config = {
43
39
  privateKey: stored.privateKey,
44
- cfg: network(envChain ?? storedChain),
45
- appId: envAppId ?? nonBlank(stored.appId),
40
+ cfg: network(envChain ?? stored.chainName),
46
41
  pinataJwt: stored.pinataJwt,
47
42
  pinataGateway: stored.pinataGateway,
48
43
  signedUrlWorkerUrl: stored.signedUrlWorkerUrl ?? ""
@@ -54,7 +49,6 @@ function loadConfig() {
54
49
  _config = {
55
50
  privateKey,
56
51
  cfg: network(envChain ?? "baseSepolia"),
57
- appId: envAppId,
58
52
  pinataJwt: pinataJwt ?? "",
59
53
  pinataGateway: pinataGateway ?? "",
60
54
  signedUrlWorkerUrl: signedUrlWorkerUrl ?? ""
@@ -65,7 +59,7 @@ function loadConfig() {
65
59
  }
66
60
  /**
67
61
  * The named network, with its RPC and contracts overridable from the environment:
68
- * FANGORN_RPC_URL, FANGORN_APP_REGISTRY and FANGORN_DATA_REGISTRY, for a local
62
+ * FANGORN_RPC_URL, FANGORN_DATA_REGISTRY and FANGORN_SETTLEMENT_REGISTRY, for a local
69
63
  * chain (an anvil with the contracts deployed) or a private RPC. Blank counts as unset.
70
64
  */
71
65
  function network(name) {
@@ -78,8 +72,8 @@ function network(name) {
78
72
  return {
79
73
  ...cfg,
80
74
  rpcUrl: nonBlank(process.env.FANGORN_RPC_URL) ?? cfg.rpcUrl,
81
- appRegistryContractAddress: address("FANGORN_APP_REGISTRY") ?? cfg.appRegistryContractAddress,
82
- dataRegistryContractAddress: address("FANGORN_DATA_REGISTRY") ?? cfg.dataRegistryContractAddress
75
+ dataRegistryContractAddress: address("FANGORN_DATA_REGISTRY") ?? cfg.dataRegistryContractAddress,
76
+ settlementRegistryContractAddress: address("FANGORN_SETTLEMENT_REGISTRY") ?? cfg.settlementRegistryContractAddress
83
77
  };
84
78
  }
85
79
  function getAccount() {
@@ -100,27 +94,10 @@ function getFangorn() {
100
94
  _fangorn = Fangorn.create({
101
95
  privateKey: cfg.privateKey,
102
96
  storage,
103
- config: cfg.cfg,
104
- appId: appFlag() ?? cfg.appId
97
+ config: cfg.cfg
105
98
  });
106
99
  return _fangorn;
107
100
  }
108
- /** The `--app` override for this invocation; blank counts as unset. */
109
- function appFlag() {
110
- return nonBlank(program.opts().app);
111
- }
112
- /**
113
- * The currently configured app name. App commands need one: there is no default
114
- * app, since publishing and reading need none.
115
- */
116
- function currentAppName() {
117
- const name = appFlag() ?? loadConfig().appId;
118
- if (!name) throw new Error("no app chosen: run `fangorn set-app <name>` or pass --app");
119
- return name;
120
- }
121
- function currentAppId() {
122
- return toAppId(currentAppName());
123
- }
124
101
  var LocalRepo = class LocalRepo {
125
102
  constructor(dir, state) {
126
103
  this.dir = dir;
@@ -167,12 +144,10 @@ var LocalRepo = class LocalRepo {
167
144
  }
168
145
  };
169
146
  const program = new Command();
170
- const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
171
147
  program.name("fangorn").description("Fangorn Network CLI").version("0.4.0");
172
- program.option("--app <name-or-id>", "App (global namespace) for this command — overrides the stored app (see `set-app`)");
173
148
  program.command("init").description("Configure your Fangorn credentials").action(async () => {
174
149
  intro("Fangorn Setup");
175
- const chainName = await selectChain();
150
+ const chainName = "baseSepolia";
176
151
  const privateKey = await text({
177
152
  message: "Wallet private key (stored locally, never transmitted):",
178
153
  placeholder: "0x...",
@@ -199,176 +174,25 @@ program.command("init").description("Configure your Fangorn credentials").action
199
174
  chainName,
200
175
  pinataJwt,
201
176
  pinataGateway,
202
- signedUrlWorkerUrl,
203
- appId: existsSync(CONFIG_PATH) ? readStoredConfig().appId : void 0
177
+ signedUrlWorkerUrl
204
178
  });
205
179
  outro(`Config saved to ${CONFIG_PATH}`);
206
180
  });
207
- program.command("set-app").description("Set the app (global namespace) this CLI publishes and reads under").argument("[app]", "App name or 32-byte app id (omit to show the current one)").action((app) => {
208
- try {
209
- if (!app) {
210
- const current = currentAppName();
211
- console.log(`App: ${current}`);
212
- console.log(`App id: ${toAppId(current)}`);
213
- process.exit(0);
214
- }
215
- if (!existsSync(CONFIG_PATH)) throw new Error(`no config file at ${CONFIG_PATH} — run \`fangorn init\` first, or set FANGORN_APP_ID in the environment.`);
216
- writeStoredConfig({
217
- ...readStoredConfig(),
218
- appId: app
219
- });
220
- console.log(`App: ${app}`);
221
- console.log(`App id: ${toAppId(app)}`);
222
- if (process.env.FANGORN_APP_ID) console.log(`\nNote: FANGORN_APP_ID=${process.env.FANGORN_APP_ID} is set and overrides this.`);
223
- console.log(`\nSaved to ${CONFIG_PATH}. Run \`fangorn app info\` to see whether it is claimed and whether it has accepted you.`);
224
- process.exit(0);
225
- } catch (err) {
226
- console.error("Failed:", err.message);
227
- process.exit(1);
228
- }
229
- });
230
- /** Fees are USDC, which has 6 decimals; the contracts count in its base units. */
231
- const USDC_DECIMALS = 6;
232
- function formatUsdc(amount) {
233
- return `${formatUnits(amount, USDC_DECIMALS)} USDC`;
234
- }
235
- /** The status word for a publisher in one app, and whether they can publish. */
236
- function membershipLine(status, canPublish, appSuspended, expired) {
237
- if (appSuspended) return "the whole app is suspended by the protocol admin — nobody can publish under it";
238
- if (expired) return "the app's subscription has expired — nobody can publish until its owner runs `fangorn app renew`";
239
- if (canPublish) return "accepted";
240
- if (status === PublisherStatus.SUSPENDED) return "suspended from this app by its owner";
241
- if (status === PublisherStatus.ACTIVE) return "accepted, but suspended network-wide by the protocol admin";
242
- return "not accepted here — ask the app's owner to run `fangorn app accept <your address>`";
243
- }
244
- const appCmd = program.command("app").description("Claim and manage apps, and the publishers they accept");
245
- appCmd.command("info").description("Show this app's owner, subscription, and where you stand in it").action(async () => {
246
- try {
247
- const self = getAccount().address;
248
- const apps = getFangorn().getAppRegistry();
249
- const s = spinner();
250
- s.start("Reading registry...");
251
- const [{ canPublish, owner, expiresAt }, status, appSuspended, suspendedGlobally, canonical, current] = await Promise.all([
252
- apps.access(self),
253
- apps.status(self),
254
- apps.isAppSuspended(),
255
- apps.isGloballySuspended(self),
256
- apps.canonicalAppId(),
257
- apps.currentAppId()
258
- ]);
259
- s.stop();
260
- const expired = expiresAt <= BigInt(Math.floor(Date.now() / 1e3));
261
- console.log(`App: ${currentAppName()}`);
262
- console.log(`App id: ${apps.getAppId() ?? ""}`);
263
- const id = apps.getAppId()?.toLowerCase();
264
- if (canonical.toLowerCase() !== id) console.log(`Claimed as: ${canonical}`);
265
- if (current.toLowerCase() !== id) console.log(`Renamed to: ${current} (this name still works; \`fangorn set-app <new name>\` follows it)`);
266
- if (owner === ZERO_ADDRESS) console.log(`Owner: (unclaimed — \`fangorn app claim\` takes it)`);
267
- else {
268
- console.log(`Owner: ${owner}${owner.toLowerCase() === self.toLowerCase() ? " (you)" : ""}`);
269
- console.log(expiresAt === 0n ? `Expires: cancelled — \`fangorn app renew\` starts a new period` : `Expires: ${(/* @__PURE__ */ new Date(Number(expiresAt) * 1e3)).toISOString()}${expired ? " (EXPIRED)" : ""}`);
270
- }
271
- if (appSuspended) console.log(`Status: SUSPENDED by the protocol admin`);
272
- console.log(`\nWallet: ${self}`);
273
- if (suspendedGlobally) console.log(`Network: SUSPENDED by the protocol admin — cannot claim, be accepted or publish`);
274
- console.log(`This app: ${owner === ZERO_ADDRESS ? "n/a (unclaimed)" : membershipLine(status, canPublish, appSuspended, expired)}`);
275
- process.exit(0);
276
- } catch (err) {
277
- console.error("Failed:", err.message);
278
- process.exit(1);
279
- }
280
- });
281
- appCmd.command("claim").description("Claim the configured app on-chain (first come, first served)").action(async () => {
282
- try {
283
- const self = getAccount().address;
284
- const registry = getFangorn().getAppRegistry();
285
- const s = spinner();
286
- s.start("Checking app ownership...");
287
- const [owner, suspendedGlobally] = await Promise.all([registry.getAppOwner(), registry.isGloballySuspended(self)]);
288
- s.stop();
289
- if (owner !== ZERO_ADDRESS) {
290
- const mine = owner.toLowerCase() === self.toLowerCase();
291
- console.log(mine ? `Already claimed by you: ${registry.getAppId() ?? ""}` : `App ${registry.getAppId() ?? ""} is already owned by ${owner}. Pick another name with \`fangorn set-app\`, or ask its owner to accept you.`);
292
- process.exit(mine ? 0 : 1);
293
- }
294
- if (suspendedGlobally) {
295
- console.error(`${self} is suspended by the protocol admin — claiming will revert.`);
296
- process.exit(1);
297
- }
298
- const subscriptionFee = await registry.subscriptionFee();
299
- console.log(`Subscription fee: ${formatUsdc(subscriptionFee)}`);
300
- s.start("Claiming app...");
301
- const txHash = await registry.registerApp();
302
- s.stop();
303
- console.log(`App: ${currentAppName()}`);
304
- console.log(`App id: ${currentAppId()}`);
305
- console.log(`Owner: ${self}`);
306
- console.log(`Tx: ${txHash}`);
307
- console.log(`\nClaiming makes you your own first publisher. Accept others with \`fangorn app accept <address>\`.`);
308
- process.exit(0);
309
- } catch (err) {
310
- console.error("Failed:", err.message);
311
- process.exit(1);
312
- }
313
- });
314
- appCmd.command("rename").description("Give your app a new name (owner only); its old names keep working").argument("<name>", "The new app name, or a 32-byte app id").action(async (name) => {
315
- try {
316
- const self = getAccount().address;
317
- const fangorn = getFangorn();
318
- const registry = fangorn.getAppRegistry();
319
- const newId = toAppId(name);
320
- const s = spinner();
321
- s.start("Checking app ownership...");
322
- const [owner, canonical, holder, holderOwner] = await Promise.all([
323
- registry.getAppOwner(),
324
- registry.canonicalAppId(),
325
- registry.canonicalAppId(newId),
326
- registry.getAppOwner(newId)
327
- ]);
328
- s.stop();
329
- if (owner === ZERO_ADDRESS) {
330
- console.error(`App ${registry.getAppId() ?? ""} is unclaimed — \`fangorn app claim\` takes it.`);
331
- process.exit(1);
332
- }
333
- if (owner.toLowerCase() !== self.toLowerCase()) {
334
- console.error(`App ${registry.getAppId() ?? ""} is owned by ${owner}; only its owner can rename it.`);
335
- process.exit(1);
336
- }
337
- if (holderOwner !== ZERO_ADDRESS && holder !== canonical) {
338
- console.error(`"${name}" (${newId}) is already another app's, owned by ${holderOwner}. Pick another name.`);
339
- process.exit(1);
340
- }
341
- s.start("Renaming app...");
342
- const txHash = await fangorn.renameApp(name);
343
- s.stop();
344
- const source = appFlag() ? "--app" : nonBlank(process.env.FANGORN_APP_ID) ? "FANGORN_APP_ID" : void 0;
345
- if (!source) writeStoredConfig({
346
- ...readStoredConfig(),
347
- appId: name
348
- });
349
- console.log(`App: ${name}`);
350
- console.log(`App id: ${newId}`);
351
- console.log(`Claimed as: ${canonical}`);
352
- console.log(`Tx: ${txHash}`);
353
- console.log(source ? `\nThe app came from ${source}: update it to "${name}". The old name keeps working meanwhile.` : `\nSaved to ${CONFIG_PATH}.`);
354
- console.log(`Every name the app went by still resolves to it, and stays yours: nobody else can claim one.`);
355
- process.exit(0);
356
- } catch (err) {
357
- console.error("Failed:", err.message);
358
- process.exit(1);
359
- }
360
- });
361
- appCmd.command("agent").description("Register this app's gateway as an ERC-8004 agent and point the app at its card (owner only)").argument("[cardUrl]", "The agent card URL; or pass --access-worker to use its /.well-known/agent-card.json").option("--access-worker <url>", "The access worker serving the agent card").option("--mcp <url>", "An MCP endpoint to index alongside the card").option("--skip-register", "Only set agent_uri on-chain — for a gateway already registered with ERC-8004").option("--update <agentId>", "Update an agent already registered (e.g. 84532:10323) from the card as it is now: a new registration file, pointed to by setAgentURI; mints nothing").action(async (cardUrl, opts) => {
181
+ program.command("card").description("Point a repo at its agent card, and register the card as an ERC-8004 agent").argument("[cardUrl]", "The agent card URL; or pass --access-worker to use its /.well-known/agent-card.json").option("--repo <name>", "The repo the card speaks for (default: the repo tracked here)").option("--access-worker <url>", "The access worker serving the agent card").option("--mcp <url>", "An MCP endpoint to index alongside the card").option("--skip-register", "Only commit the @card record, for a card already registered with ERC-8004").option("--update <agentId>", "Update an agent already registered (e.g. 84532:10323) from the card as it is now: a new registration file, pointed to by setAgentURI; mints nothing").action(async (cardUrl, opts) => {
362
182
  try {
363
183
  const cfg = loadConfig();
364
184
  const url = agentCardUrl(cardUrl, opts.accessWorker);
185
+ const local = opts.repo ? void 0 : LocalRepo.open();
186
+ const repo = opts.repo ?? local?.namespace() ?? "";
365
187
  const s = spinner();
366
188
  const chainId = cfg.cfg.caip2;
367
189
  const update = opts.update ? parseAgentId(opts.update, chainId) : void 0;
368
- s.start(opts.skipRegister ? "Pointing the app at its card" : update !== void 0 ? `Updating ERC-8004 agent ${opts.update ?? ""}` : "Registering with the ERC-8004 identity registry");
190
+ s.start(opts.skipRegister ? `Pointing ${repo} at its card` : update !== void 0 ? `Updating ERC-8004 agent ${opts.update ?? ""}` : "Registering with the ERC-8004 identity registry");
191
+ const fangorn = getFangorn();
369
192
  let result;
370
193
  try {
371
- result = await getFangorn().registerAgent(url, {
194
+ result = await fangorn.registerAgent(url, {
195
+ repo,
372
196
  mcp: opts.mcp,
373
197
  update,
374
198
  skipRegister: opts.skipRegister
@@ -376,160 +200,15 @@ appCmd.command("agent").description("Register this app's gateway as an ERC-8004
376
200
  } catch (e) {
377
201
  s.stop();
378
202
  const minted = e.agentId;
379
- throw minted !== void 0 ? /* @__PURE__ */ new Error(`${e.message.replace(/; finish it with .*/, "")}. Finish it with: fangorn app agent ${url} --update ${String(chainId)}:${String(minted)}`) : e;
203
+ throw minted !== void 0 ? /* @__PURE__ */ new Error(`${e.message.replace(/; finish it with .*/, "")}. Finish it with: fangorn card ${url} --repo ${repo} --update ${String(chainId)}:${String(minted)}`) : e;
380
204
  }
381
205
  s.stop();
206
+ if (local && result.txHash) local.setHead(await fangorn.onChainTip(fangorn.getAddress(), repo));
382
207
  const agentId = result.agentId !== void 0 ? `${String(chainId)}:${String(result.agentId)}` : void 0;
383
- const txHash = result.txHash ?? "(already bound)";
384
208
  if (agentId) console.log(`Agent ID: ${agentId}`);
209
+ console.log(`Repo: ${repo}`);
385
210
  console.log(`Card: ${url}`);
386
- console.log(`Tx: ${txHash}`);
387
- process.exit(0);
388
- } catch (err) {
389
- console.error("Failed:", err.message);
390
- process.exit(1);
391
- }
392
- });
393
- appCmd.command("accept").description("Accept a publisher into your app (owner only): the app stores and includes its data").argument("<publisher>", "Publisher address").action(async (publisher) => {
394
- try {
395
- const registry = getFangorn().getAppRegistry();
396
- const s = spinner();
397
- s.start("Checking publisher standing...");
398
- const suspended = await registry.isGloballySuspended(publisher);
399
- s.stop();
400
- if (suspended) {
401
- console.error(`${publisher} is suspended by the protocol admin — accepting them will revert.`);
402
- process.exit(1);
403
- }
404
- s.start("Accepting publisher...");
405
- const txHash = await registry.acceptPublisher(publisher);
406
- s.stop();
407
- console.log(`Accepted: ${publisher}`);
408
- console.log(`Tx: ${txHash}`);
409
- console.log(`\nThey can now upload with this app's storage, and the app includes their data.`);
410
- process.exit(0);
411
- } catch (err) {
412
- console.error("Failed:", err.message);
413
- process.exit(1);
414
- }
415
- });
416
- appCmd.command("renew").description("Pay for one more period of your app's subscription (owner only)").action(async () => {
417
- try {
418
- const registry = getFangorn().getAppRegistry();
419
- const s = spinner();
420
- s.start("Renewing subscription...");
421
- const txHash = await registry.renewSubscription();
422
- const expiresAt = await registry.expiresAt();
423
- s.stop();
424
- console.log(`Renewed: ${registry.getAppId() ?? ""}`);
425
- console.log(`Expires: ${(/* @__PURE__ */ new Date(Number(expiresAt) * 1e3)).toISOString()}`);
426
- console.log(`Tx: ${txHash}`);
427
- process.exit(0);
428
- } catch (err) {
429
- console.error("Failed:", err.message);
430
- process.exit(1);
431
- }
432
- });
433
- appCmd.command("cancel").description("End your app's subscription now, without refund (owner only)").action(async () => {
434
- try {
435
- const registry = getFangorn().getAppRegistry();
436
- const ok = await confirm({ message: `Cancel ${registry.getAppId() ?? ""}'s subscription? Nothing is refunded, and the app takes no commits or joins until renewed.` });
437
- handleCancel(ok);
438
- if (!ok) process.exit(0);
439
- const s = spinner();
440
- s.start("Cancelling subscription...");
441
- const txHash = await registry.cancelSubscription();
442
- s.stop();
443
- console.log(`Cancelled: ${registry.getAppId() ?? ""}`);
444
- console.log(`Tx: ${txHash}`);
445
- process.exit(0);
446
- } catch (err) {
447
- console.error("Failed:", err.message);
448
- process.exit(1);
449
- }
450
- });
451
- appCmd.command("suspend").description("Suspend a member from your app (owner only)").argument("<publisher>", "Publisher address").action(async (publisher) => {
452
- try {
453
- const s = spinner();
454
- s.start("Suspending publisher...");
455
- const txHash = await getFangorn().getAppRegistry().setPublisherSuspended(publisher, true);
456
- s.stop();
457
- console.log(`Suspended: ${publisher}`);
458
- console.log(`Tx: ${txHash}`);
459
- process.exit(0);
460
- } catch (err) {
461
- console.error("Failed:", err.message);
462
- process.exit(1);
463
- }
464
- });
465
- appCmd.command("reinstate").description("Reinstate a suspended publisher in your app (owner only)").argument("<publisher>", "Publisher address").action(async (publisher) => {
466
- try {
467
- const s = spinner();
468
- s.start("Reinstating publisher...");
469
- const txHash = await getFangorn().getAppRegistry().setPublisherSuspended(publisher, false);
470
- s.stop();
471
- console.log(`Reinstated: ${publisher}`);
472
- console.log(`Tx: ${txHash}`);
473
- process.exit(0);
474
- } catch (err) {
475
- console.error("Failed:", err.message);
476
- process.exit(1);
477
- }
478
- });
479
- const appAdminCmd = appCmd.command("admin").description("Protocol-admin takedowns for the whole app (admin only)");
480
- /** The AppRegistry client, refusing early if this wallet is not the protocol admin. */
481
- async function requireAdmin() {
482
- const registry = getFangorn().getAppRegistry();
483
- const self = getAccount().address;
484
- const admin = await registry.admin();
485
- if (admin.toLowerCase() !== self.toLowerCase()) throw new Error(`Not the protocol admin: this registry's admin is ${admin}, you are ${self}.`);
486
- return registry;
487
- }
488
- appAdminCmd.command("suspend").description("Suspend this entire app — nobody can publish under it (admin only)").action(async () => {
489
- try {
490
- const registry = await requireAdmin();
491
- const ok = await confirm({ message: `Suspend the whole app ${registry.getAppId() ?? ""}? Every publisher, including its owner, stops being able to publish.` });
492
- handleCancel(ok);
493
- if (!ok) process.exit(0);
494
- const s = spinner();
495
- s.start("Suspending app...");
496
- const txHash = await registry.setAppSuspended(true);
497
- s.stop();
498
- console.log(`Suspended: ${currentAppId()}`);
499
- console.log(`Tx: ${txHash}`);
500
- console.log(`\nMemberships are kept — \`fangorn app admin reinstate\` restores them as they were.`);
501
- process.exit(0);
502
- } catch (err) {
503
- console.error("Failed:", err.message);
504
- process.exit(1);
505
- }
506
- });
507
- appAdminCmd.command("reinstate").description("Lift the suspension on this entire app (admin only)").action(async () => {
508
- try {
509
- const registry = await requireAdmin();
510
- const s = spinner();
511
- s.start("Reinstating app...");
512
- const txHash = await registry.setAppSuspended(false);
513
- s.stop();
514
- console.log(`Reinstated: ${currentAppId()}`);
515
- console.log(`Tx: ${txHash}`);
516
- process.exit(0);
517
- } catch (err) {
518
- console.error("Failed:", err.message);
519
- process.exit(1);
520
- }
521
- });
522
- appAdminCmd.command("status").description("Who the protocol admin is, and whether this app is suspended").action(async () => {
523
- try {
524
- const registry = getFangorn().getAppRegistry();
525
- const self = getAccount().address;
526
- const s = spinner();
527
- s.start("Reading registry...");
528
- const [admin, suspended] = await Promise.all([registry.admin(), registry.isAppSuspended()]);
529
- s.stop();
530
- console.log(`App id: ${currentAppId()}`);
531
- console.log(`Admin: ${admin}${admin.toLowerCase() === self.toLowerCase() ? " (you)" : ""}`);
532
- console.log(`Suspended: ${suspended ? "yes — nobody can publish under this app" : "no"}`);
211
+ console.log(`Tx: ${result.txHash ?? "(already bound)"}`);
533
212
  process.exit(0);
534
213
  } catch (err) {
535
214
  console.error("Failed:", err.message);
@@ -548,7 +227,6 @@ program.command("wallet").description("Show the wallet this CLI signs with").arg
548
227
  console.log(`Public key: ${account.publicKey}`);
549
228
  console.log(`Balance: ${formatEther(balance)} ETH`);
550
229
  console.log(`Network: ${cfg.cfg.chain.name} (${cfg.cfg.caip2.toString()})`);
551
- console.log(`App: ${currentAppName()}`);
552
230
  console.log(`Config: ${existsSync(CONFIG_PATH) ? CONFIG_PATH : "(from environment)"}`);
553
231
  if (opts.reveal) {
554
232
  console.log(`\nPrivate key: ${cfg.privateKey}`);
@@ -587,7 +265,7 @@ program.command("repo").description("Repository operations").command("init").des
587
265
  process.exit(1);
588
266
  }
589
267
  });
590
- program.command("commit").description("Put/delete a namespace's records in a new local commit (does not push)").argument("<file>", "JSON file: {\"records\":[{\"id\",\"type\",\"payload\"}],\"deletes\":[\"id\"]}").requiredOption("-m, --message <msg>", "Commit message").option("--replace", "Snapshot semantics: the file replaces the namespace's previous contents (omitted entries are removed)").action(async (file, options) => {
268
+ program.command("commit").description("Put/delete a namespace's records in a new local commit (does not push)").argument("<file>", "JSON file: {\"records\":[{\"id\",\"type\",\"payload\"}],\"deletes\":[\"id\"]}").option("--replace", "Snapshot semantics: the file replaces the namespace's previous contents (omitted entries are removed)").action(async (file, options) => {
591
269
  try {
592
270
  if (!existsSync(file)) throw new Error(`file not found: ${file}`);
593
271
  const data = JSON.parse(readFileSync(file, "utf-8"));
@@ -604,7 +282,6 @@ program.command("commit").description("Put/delete a namespace's records in a new
604
282
  records,
605
283
  deletes,
606
284
  parent,
607
- message: options.message,
608
285
  replace: options.replace
609
286
  });
610
287
  s.stop();
@@ -613,7 +290,6 @@ program.command("commit").description("Put/delete a namespace's records in a new
613
290
  console.log(`Parent: ${result.parent ?? "(root)"}`);
614
291
  console.log(`Tree: ${result.root}`);
615
292
  console.log(`Staged: ${records.length.toString()} put(s) / ${deletes.length.toString()} delete(s)`);
616
- console.log(`Message: ${options.message}`);
617
293
  console.log(`\nCommitted locally. Run \`fangorn push\` to settle it on-chain.`);
618
294
  process.exit(0);
619
295
  } catch (err) {
@@ -668,8 +344,7 @@ program.command("log").description("Walk commit history from the local tip").opt
668
344
  for await (const c of fangorn.log(head, options.max)) {
669
345
  console.log(`commit ${c.cid}`);
670
346
  console.log(`Epoch: ${c.epoch.toString()}`);
671
- console.log(`Tree: ${c.root}`);
672
- console.log(`\n ${c.message}\n`);
347
+ console.log(`Tree: ${c.root}\n`);
673
348
  }
674
349
  process.exit(0);
675
350
  } catch (err) {
@@ -686,8 +361,7 @@ program.command("show").description("Show a commit and what it changed vs. its p
686
361
  console.log(`commit ${target}`);
687
362
  console.log(`Epoch: ${diff.epoch.toString()}`);
688
363
  console.log(`Parent: ${diff.parent ?? "(root)"}`);
689
- console.log(`Tree: ${diff.root}`);
690
- console.log(`\n ${diff.message}\n`);
364
+ console.log(`Tree: ${diff.root}\n`);
691
365
  console.log(`Changes vs. parent: +${diff.added.length.toString()} / -${diff.removed.length.toString()} key(s)`);
692
366
  for (const k of diff.added) console.log(` + ${k}`);
693
367
  for (const k of diff.removed) console.log(` - ${k}`);
@@ -718,7 +392,7 @@ program.command("clone").description("Track an existing on-chain namespace by re
718
392
  process.exit(1);
719
393
  }
720
394
  });
721
- program.command("subscribe").description("Watch on-chain pushes to a namespace and stream JSON diffs (light client — no indexer)").argument("[namespace]", "Namespace name (default: current repo)").option("--owner <address>", "Owner (publisher) address (default: current repo owner, else self)").option("--from-block <n>", "Replay from this block (overrides the saved cursor)", (v) => BigInt(v)).option("--from-start", "Replay this namespace's full history (ignore the saved cursor)").option("--pretty", "Pretty-print each change").option("--all", "Watch the whole app (every publisher, every namespace); --owner/namespace narrow it").action(async (namespaceArg, options) => {
395
+ program.command("subscribe").description("Watch on-chain pushes to a namespace and stream JSON diffs (light client — no indexer)").argument("[namespace]", "Namespace name (default: current repo)").option("--owner <address>", "Owner (publisher) address (default: current repo owner, else self)").option("--from-block <n>", "Replay from this block (overrides the saved cursor)", (v) => BigInt(v)).option("--from-start", "Replay this namespace's full history (ignore the saved cursor)").option("--pretty", "Pretty-print each change").option("--all", "Watch every publisher and namespace; --owner/namespace narrow it").action(async (namespaceArg, options) => {
722
396
  try {
723
397
  const fangorn = getFangorn();
724
398
  let namespace = namespaceArg;
@@ -733,7 +407,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
733
407
  owner = owner ?? fangorn.getAddress();
734
408
  }
735
409
  const repoDir = join(process.cwd(), ".fangorn");
736
- const cursorPath = join(repoDir, `subscribe-${owner ?? "app"}-${namespace ?? "all"}.json`);
410
+ const cursorPath = join(repoDir, `subscribe-${owner ?? "all"}-${namespace ?? "all"}.json`);
737
411
  const readCursor = () => {
738
412
  if (options.fromStart) return 0n;
739
413
  if (options.fromBlock !== void 0) return options.fromBlock;
@@ -752,7 +426,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
752
426
  };
753
427
  const bigintReplacer = (_k, v) => typeof v === "bigint" ? v.toString() : v;
754
428
  const fromBlock = readCursor();
755
- console.error(`Subscribing to "${namespace ?? "*"}" @ ${owner ?? "* (whole app)"} ` + (fromBlock !== void 0 ? `from block ${fromBlock.toString()}` : "(live from current tip)") + ` — Ctrl-C to stop.`);
429
+ console.error(`Subscribing to "${namespace ?? "*"}" @ ${owner ?? "*"} ` + (fromBlock !== void 0 ? `from block ${fromBlock.toString()}` : "(live from current tip)") + ` — Ctrl-C to stop.`);
756
430
  const controller = new AbortController();
757
431
  process.on("SIGINT", () => {
758
432
  controller.abort();
@@ -760,7 +434,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
760
434
  process.on("SIGTERM", () => {
761
435
  controller.abort();
762
436
  });
763
- const stream = options.all ? fangorn.subscribeApp({
437
+ const stream = options.all ? fangorn.subscribeAll({
764
438
  repo: namespace,
765
439
  owner,
766
440
  fromBlock,
@@ -1,13 +1,10 @@
1
1
  import "./cli.js";
2
- import * as viem0 from "viem";
3
2
 
4
3
  //#region src/cli/index.d.ts
5
- declare const getChain: (chainStr: string) => viem0.Chain;
6
4
  declare const handleCancel: (value: unknown) => void;
7
- declare const selectChain: () => Promise<string>;
8
5
  declare function parseGadgetArg(raw: string): {
9
6
  type: string;
10
7
  args: string[];
11
8
  };
12
9
  //#endregion
13
- export { getChain, handleCancel, parseGadgetArg, selectChain };
10
+ export { handleCancel, parseGadgetArg };
package/lib/cli/index.js CHANGED
@@ -1,28 +1,10 @@
1
- import getNetwork from "../config.js";
2
1
  import "./cli.js";
3
- import { isCancel, select } from "@clack/prompts";
2
+ import { isCancel } from "@clack/prompts";
4
3
 
5
4
  //#region src/cli/index.ts
6
- const getChain = (chainStr) => {
7
- return getNetwork(chainStr).chain;
8
- };
9
5
  const handleCancel = (value) => {
10
6
  if (isCancel(value)) process.exit(0);
11
7
  };
12
- const selectChain = async () => {
13
- const chainChoice = await select({
14
- message: "Pick your chain.",
15
- options: [{
16
- value: "baseSepolia",
17
- label: "Base Sepolia"
18
- }, {
19
- value: "arbitrumSepolia",
20
- label: "Arbitrum Sepolia"
21
- }]
22
- });
23
- handleCancel(chainChoice);
24
- return chainChoice.toString();
25
- };
26
8
  function parseGadgetArg(raw) {
27
9
  const match = /^(\w+)\(([^)]*)\)$/.exec(raw);
28
10
  if (!match) throw new Error(`Invalid gadget format: "${raw}". Expected e.g. Payment(0.00001)`);
@@ -33,4 +15,4 @@ function parseGadgetArg(raw) {
33
15
  }
34
16
 
35
17
  //#endregion
36
- export { getChain, handleCancel, parseGadgetArg, selectChain };
18
+ export { handleCancel, parseGadgetArg };