@fangorn-network/sdk 0.1.0 → 0.1.1

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 (71) hide show
  1. package/lib/cli/cli.js +128 -328
  2. package/lib/cli/index.d.ts +1 -4
  3. package/lib/cli/index.js +2 -20
  4. package/lib/cli/sell.d.ts +28 -0
  5. package/lib/cli/sell.js +95 -0
  6. package/lib/cli/stage.d.ts +19 -0
  7. package/lib/cli/stage.js +94 -0
  8. package/lib/config.d.ts +16 -79
  9. package/lib/config.js +11 -39
  10. package/lib/contracts/data-registry/abi.d.ts +195 -19
  11. package/lib/contracts/data-registry/abi.js +409 -206
  12. package/lib/contracts/data-registry/index.d.ts +126 -2
  13. package/lib/contracts/data-registry/index.js +174 -1
  14. package/lib/contracts/index.d.ts +4 -7
  15. package/lib/contracts/index.js +4 -7
  16. package/lib/contracts/logs.d.ts +1 -1
  17. package/lib/contracts/logs.js +1 -1
  18. package/lib/contracts/{membership-registry → settlement-registry}/abi.d.ts +301 -636
  19. package/lib/contracts/settlement-registry/abi.js +962 -0
  20. package/lib/contracts/settlement-registry/index.d.ts +143 -0
  21. package/lib/contracts/settlement-registry/index.js +213 -0
  22. package/lib/crypto/aes.d.ts +2 -2
  23. package/lib/crypto/aes.js +4 -4
  24. package/lib/crypto/encryption.d.ts +8 -109
  25. package/lib/crypto/encryption.js +16 -114
  26. package/lib/crypto/paid.d.ts +104 -0
  27. package/lib/crypto/paid.js +147 -0
  28. package/lib/engine/car.d.ts +5 -1
  29. package/lib/engine/car.js +2 -2
  30. package/lib/engine/index.d.ts +33 -14
  31. package/lib/engine/index.js +98 -41
  32. package/lib/engine/records.d.ts +19 -8
  33. package/lib/engine/records.js +81 -7
  34. package/lib/engine/test-helpers.d.ts +2 -3
  35. package/lib/engine/test-helpers.js +7 -5
  36. package/lib/erc8004.js +7 -10
  37. package/lib/fangorn.d.ts +65 -86
  38. package/lib/fangorn.js +115 -153
  39. package/lib/feed.d.ts +7 -8
  40. package/lib/feed.js +7 -8
  41. package/lib/index.d.ts +10 -13
  42. package/lib/index.js +10 -13
  43. package/lib/providers/storage/signed-url.d.ts +2 -10
  44. package/lib/providers/storage/signed-url.js +5 -15
  45. package/lib/providers/storage/types.d.ts +1 -1
  46. package/lib/providers/storage/utils.js +5 -3
  47. package/lib/test/key-server.d.ts +12 -0
  48. package/lib/test/key-server.js +30 -0
  49. package/lib/test/mem-registry.d.ts +14 -19
  50. package/lib/test/mem-registry.js +44 -37
  51. package/lib/test/sdk-suite.d.ts +1 -4
  52. package/lib/test/sdk-suite.js +16 -87
  53. package/lib/test/testbed.d.ts +5130 -5140
  54. package/lib/test/testbed.js +29 -56
  55. package/lib/types/index.d.ts +6 -11
  56. package/package.json +1 -1
  57. package/lib/contracts/app-registry/abi.d.ts +0 -1265
  58. package/lib/contracts/app-registry/abi.js +0 -1454
  59. package/lib/contracts/app-registry/index.d.ts +0 -161
  60. package/lib/contracts/app-registry/index.js +0 -274
  61. package/lib/contracts/membership-registry/abi.js +0 -1333
  62. package/lib/contracts/membership-registry/index.d.ts +0 -79
  63. package/lib/contracts/membership-registry/index.js +0 -104
  64. package/lib/contracts/types.d.ts +0 -10
  65. package/lib/contracts/types.js +0 -12
  66. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +0 -1
  67. package/lib/harness/examples/hackmd/build-markdown-graph.js +0 -17
  68. package/lib/harness/index.d.ts +0 -58
  69. package/lib/harness/index.js +0 -73
  70. package/lib/registry.d.ts +0 -118
  71. package/lib/registry.js +0 -184
package/lib/cli/cli.js CHANGED
@@ -1,16 +1,16 @@
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 } from "viem";
5
+ import { sealRecords } from "./sell.js";
6
+ import { fileToRecords, walk } from "./stage.js";
7
+ import { handleCancel } from "./index.js";
8
+ import { createPublicClient, formatEther, http, isAddress, parseUnits } from "viem";
9
9
  import { privateKeyToAccount } from "viem/accounts";
10
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
11
- import { dirname, join } from "path";
12
10
  import { Command } from "commander";
13
11
  import { confirm, intro, outro, spinner, text } from "@clack/prompts";
12
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
13
+ import { dirname, join } from "path";
14
14
  import { homedir } from "os";
15
15
  import "dotenv/config";
16
16
 
@@ -34,15 +34,12 @@ function loadConfig() {
34
34
  const pinataJwt = process.env.PINATA_JWT;
35
35
  const pinataGateway = process.env.PINATA_GATEWAY;
36
36
  const signedUrlWorkerUrl = process.env.SIGNED_URL_WORKER_URL;
37
- const envAppId = nonBlank(process.env.FANGORN_APP_ID);
38
37
  const envChain = nonBlank(process.env.CHAIN_NAME);
39
38
  if (existsSync(CONFIG_PATH)) {
40
39
  const stored = readStoredConfig();
41
- const storedChain = stored.chainName === "Arbitrum Sepolia" ? "arbitrumSepolia" : stored.chainName;
42
40
  _config = {
43
41
  privateKey: stored.privateKey,
44
- cfg: getNetwork(envChain ?? storedChain),
45
- appId: envAppId ?? nonBlank(stored.appId),
42
+ cfg: network(envChain ?? stored.chainName),
46
43
  pinataJwt: stored.pinataJwt,
47
44
  pinataGateway: stored.pinataGateway,
48
45
  signedUrlWorkerUrl: stored.signedUrlWorkerUrl ?? ""
@@ -53,8 +50,7 @@ function loadConfig() {
53
50
  if (!privateKey) throw new Error("Incomplete environment configuration. Missing: ETH_PRIVATE_KEY\nSet it or run `fangorn init` to use a config file.");
54
51
  _config = {
55
52
  privateKey,
56
- cfg: getNetwork(envChain ?? "baseSepolia"),
57
- appId: envAppId,
53
+ cfg: network(envChain ?? "baseSepolia"),
58
54
  pinataJwt: pinataJwt ?? "",
59
55
  pinataGateway: pinataGateway ?? "",
60
56
  signedUrlWorkerUrl: signedUrlWorkerUrl ?? ""
@@ -63,6 +59,25 @@ function loadConfig() {
63
59
  }
64
60
  throw new Error("No configuration found. Run `fangorn init` or set ETH_PRIVATE_KEY\n(with no config, uploads go to Fangorn's shared Pinata account; files may be unpinned without notice. Set PINATA_JWT + PINATA_GATEWAY to use your own storage).");
65
61
  }
62
+ /**
63
+ * The named network, with its RPC and contracts overridable from the environment:
64
+ * FANGORN_RPC_URL, FANGORN_DATA_REGISTRY and FANGORN_SETTLEMENT_REGISTRY, for a local
65
+ * chain (an anvil with the contracts deployed) or a private RPC. Blank counts as unset.
66
+ */
67
+ function network(name) {
68
+ const cfg = getNetwork(name);
69
+ const address = (variable) => {
70
+ const value = nonBlank(process.env[variable]);
71
+ if (value !== void 0 && !isAddress(value)) throw new Error(`${variable} is not an address: "${value}"`);
72
+ return value;
73
+ };
74
+ return {
75
+ ...cfg,
76
+ rpcUrl: nonBlank(process.env.FANGORN_RPC_URL) ?? cfg.rpcUrl,
77
+ dataRegistryContractAddress: address("FANGORN_DATA_REGISTRY") ?? cfg.dataRegistryContractAddress,
78
+ settlementRegistryContractAddress: address("FANGORN_SETTLEMENT_REGISTRY") ?? cfg.settlementRegistryContractAddress
79
+ };
80
+ }
66
81
  function getAccount() {
67
82
  if (_account) return _account;
68
83
  _account = privateKeyToAccount(loadConfig().privateKey);
@@ -81,27 +96,10 @@ function getFangorn() {
81
96
  _fangorn = Fangorn.create({
82
97
  privateKey: cfg.privateKey,
83
98
  storage,
84
- config: cfg.cfg,
85
- appId: appFlag() ?? cfg.appId
99
+ config: cfg.cfg
86
100
  });
87
101
  return _fangorn;
88
102
  }
89
- /** The `--app` override for this invocation; blank counts as unset. */
90
- function appFlag() {
91
- return nonBlank(program.opts().app);
92
- }
93
- /**
94
- * The currently configured app name. App commands need one: there is no default
95
- * app, since publishing and reading need none.
96
- */
97
- function currentAppName() {
98
- const name = appFlag() ?? loadConfig().appId;
99
- if (!name) throw new Error("no app chosen: run `fangorn set-app <name>` or pass --app");
100
- return name;
101
- }
102
- function currentAppId() {
103
- return toAppId(currentAppName());
104
- }
105
103
  var LocalRepo = class LocalRepo {
106
104
  constructor(dir, state) {
107
105
  this.dir = dir;
@@ -146,14 +144,26 @@ var LocalRepo = class LocalRepo {
146
144
  this.state.head = cid;
147
145
  this.save();
148
146
  }
147
+ root() {
148
+ return this.dir;
149
+ }
150
+ /** The staging area: what the next `fangorn commit` (no file) will commit. */
151
+ staged() {
152
+ const p = join(this.dir, ".fangorn", "index.json");
153
+ return existsSync(p) ? JSON.parse(readFileSync(p, "utf-8")) : {
154
+ records: [],
155
+ deletes: []
156
+ };
157
+ }
158
+ setStaged(s) {
159
+ writeFileSync(join(this.dir, ".fangorn", "index.json"), JSON.stringify(s, null, 2), "utf-8");
160
+ }
149
161
  };
150
162
  const program = new Command();
151
- const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
152
163
  program.name("fangorn").description("Fangorn Network CLI").version("0.4.0");
153
- program.option("--app <name-or-id>", "App (global namespace) for this command — overrides the stored app (see `set-app`)");
154
164
  program.command("init").description("Configure your Fangorn credentials").action(async () => {
155
165
  intro("Fangorn Setup");
156
- const chainName = await selectChain();
166
+ const chainName = "baseSepolia";
157
167
  const privateKey = await text({
158
168
  message: "Wallet private key (stored locally, never transmitted):",
159
169
  placeholder: "0x...",
@@ -166,7 +176,7 @@ program.command("init").description("Configure your Fangorn credentials").action
166
176
  const pinataJwt = await text({ message: "Pinata JWT — leave blank to use Fangorn's shared Pinata account (testnet convenience; files may be unpinned without notice):" });
167
177
  handleCancel(pinataJwt);
168
178
  const pinataGateway = await text({
169
- message: "Pinata Gateway URL (optional; blank uses a public IPFS gateway):",
179
+ message: "Pinata Gateway URL (optional; blank uses the network's gateway):",
170
180
  placeholder: "https://your-gateway.mypinata.cloud"
171
181
  });
172
182
  handleCancel(pinataGateway);
@@ -180,124 +190,25 @@ program.command("init").description("Configure your Fangorn credentials").action
180
190
  chainName,
181
191
  pinataJwt,
182
192
  pinataGateway,
183
- signedUrlWorkerUrl,
184
- appId: existsSync(CONFIG_PATH) ? readStoredConfig().appId : void 0
193
+ signedUrlWorkerUrl
185
194
  });
186
195
  outro(`Config saved to ${CONFIG_PATH}`);
187
196
  });
188
- 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) => {
189
- try {
190
- if (!app) {
191
- const current = currentAppName();
192
- console.log(`App: ${current}`);
193
- console.log(`App id: ${toAppId(current)}`);
194
- process.exit(0);
195
- }
196
- 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.`);
197
- writeStoredConfig({
198
- ...readStoredConfig(),
199
- appId: app
200
- });
201
- console.log(`App: ${app}`);
202
- console.log(`App id: ${toAppId(app)}`);
203
- if (process.env.FANGORN_APP_ID) console.log(`\nNote: FANGORN_APP_ID=${process.env.FANGORN_APP_ID} is set and overrides this.`);
204
- console.log(`\nSaved to ${CONFIG_PATH}. Run \`fangorn app info\` to see whether it is claimed and whether it has accepted you.`);
205
- process.exit(0);
206
- } catch (err) {
207
- console.error("Failed:", err.message);
208
- process.exit(1);
209
- }
210
- });
211
- /** Fees are USDC, which has 6 decimals; the contracts count in its base units. */
212
- const USDC_DECIMALS = 6;
213
- function formatUsdc(amount) {
214
- return `${formatUnits(amount, USDC_DECIMALS)} USDC`;
215
- }
216
- /** The status word for a publisher in one app, and whether they can publish. */
217
- function membershipLine(status, canPublish, appSuspended, expired) {
218
- if (appSuspended) return "the whole app is suspended by the protocol admin — nobody can publish under it";
219
- if (expired) return "the app's subscription has expired — nobody can publish until its owner runs `fangorn app renew`";
220
- if (canPublish) return "accepted";
221
- if (status === PublisherStatus.SUSPENDED) return "suspended from this app by its owner";
222
- if (status === PublisherStatus.ACTIVE) return "accepted, but suspended network-wide by the protocol admin";
223
- return "not accepted here — ask the app's owner to run `fangorn app accept <your address>`";
224
- }
225
- const appCmd = program.command("app").description("Claim and manage apps, and the publishers they accept");
226
- appCmd.command("info").description("Show this app's owner, subscription, and where you stand in it").action(async () => {
227
- try {
228
- const self = getAccount().address;
229
- const apps = getFangorn().getAppRegistry();
230
- const s = spinner();
231
- s.start("Reading registry...");
232
- const [{ canPublish, owner, expiresAt }, status, appSuspended, suspendedGlobally] = await Promise.all([
233
- apps.access(self),
234
- apps.status(self),
235
- apps.isAppSuspended(),
236
- apps.isGloballySuspended(self)
237
- ]);
238
- s.stop();
239
- const expired = expiresAt <= BigInt(Math.floor(Date.now() / 1e3));
240
- console.log(`App: ${currentAppName()}`);
241
- console.log(`App id: ${apps.getAppId() ?? ""}`);
242
- if (owner === ZERO_ADDRESS) console.log(`Owner: (unclaimed — \`fangorn app claim\` takes it)`);
243
- else {
244
- console.log(`Owner: ${owner}${owner.toLowerCase() === self.toLowerCase() ? " (you)" : ""}`);
245
- console.log(expiresAt === 0n ? `Expires: cancelled — \`fangorn app renew\` starts a new period` : `Expires: ${(/* @__PURE__ */ new Date(Number(expiresAt) * 1e3)).toISOString()}${expired ? " (EXPIRED)" : ""}`);
246
- }
247
- if (appSuspended) console.log(`Status: SUSPENDED by the protocol admin`);
248
- console.log(`\nWallet: ${self}`);
249
- if (suspendedGlobally) console.log(`Network: SUSPENDED by the protocol admin — cannot claim, be accepted or publish`);
250
- console.log(`This app: ${owner === ZERO_ADDRESS ? "n/a (unclaimed)" : membershipLine(status, canPublish, appSuspended, expired)}`);
251
- process.exit(0);
252
- } catch (err) {
253
- console.error("Failed:", err.message);
254
- process.exit(1);
255
- }
256
- });
257
- appCmd.command("claim").description("Claim the configured app on-chain (first come, first served)").action(async () => {
258
- try {
259
- const self = getAccount().address;
260
- const registry = getFangorn().getAppRegistry();
261
- const s = spinner();
262
- s.start("Checking app ownership...");
263
- const [owner, suspendedGlobally] = await Promise.all([registry.getAppOwner(), registry.isGloballySuspended(self)]);
264
- s.stop();
265
- if (owner !== ZERO_ADDRESS) {
266
- const mine = owner.toLowerCase() === self.toLowerCase();
267
- 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.`);
268
- process.exit(mine ? 0 : 1);
269
- }
270
- if (suspendedGlobally) {
271
- console.error(`${self} is suspended by the protocol admin — claiming will revert.`);
272
- process.exit(1);
273
- }
274
- const subscriptionFee = await registry.subscriptionFee();
275
- console.log(`Subscription fee: ${formatUsdc(subscriptionFee)}`);
276
- s.start("Claiming app...");
277
- const txHash = await registry.registerApp();
278
- s.stop();
279
- console.log(`App: ${currentAppName()}`);
280
- console.log(`App id: ${currentAppId()}`);
281
- console.log(`Owner: ${self}`);
282
- console.log(`Tx: ${txHash}`);
283
- console.log(`\nClaiming makes you your own first publisher. Accept others with \`fangorn app accept <address>\`.`);
284
- process.exit(0);
285
- } catch (err) {
286
- console.error("Failed:", err.message);
287
- process.exit(1);
288
- }
289
- });
290
- 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) => {
197
+ 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) => {
291
198
  try {
292
199
  const cfg = loadConfig();
293
200
  const url = agentCardUrl(cardUrl, opts.accessWorker);
201
+ const local = opts.repo ? void 0 : LocalRepo.open();
202
+ const repo = opts.repo ?? local?.namespace() ?? "";
294
203
  const s = spinner();
295
204
  const chainId = cfg.cfg.caip2;
296
205
  const update = opts.update ? parseAgentId(opts.update, chainId) : void 0;
297
- 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");
206
+ 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");
207
+ const fangorn = getFangorn();
298
208
  let result;
299
209
  try {
300
- result = await getFangorn().registerAgent(url, {
210
+ result = await fangorn.registerAgent(url, {
211
+ repo,
301
212
  mcp: opts.mcp,
302
213
  update,
303
214
  skipRegister: opts.skipRegister
@@ -305,180 +216,15 @@ appCmd.command("agent").description("Register this app's gateway as an ERC-8004
305
216
  } catch (e) {
306
217
  s.stop();
307
218
  const minted = e.agentId;
308
- 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;
219
+ 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;
309
220
  }
310
221
  s.stop();
222
+ if (local && result.txHash) local.setHead(await fangorn.onChainTip(fangorn.getAddress(), repo));
311
223
  const agentId = result.agentId !== void 0 ? `${String(chainId)}:${String(result.agentId)}` : void 0;
312
- const txHash = result.txHash ?? "(already bound)";
313
224
  if (agentId) console.log(`Agent ID: ${agentId}`);
225
+ console.log(`Repo: ${repo}`);
314
226
  console.log(`Card: ${url}`);
315
- console.log(`Tx: ${txHash}`);
316
- process.exit(0);
317
- } catch (err) {
318
- console.error("Failed:", err.message);
319
- process.exit(1);
320
- }
321
- });
322
- 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) => {
323
- try {
324
- const registry = getFangorn().getAppRegistry();
325
- const s = spinner();
326
- s.start("Checking publisher standing...");
327
- const suspended = await registry.isGloballySuspended(publisher);
328
- s.stop();
329
- if (suspended) {
330
- console.error(`${publisher} is suspended by the protocol admin — accepting them will revert.`);
331
- process.exit(1);
332
- }
333
- s.start("Accepting publisher...");
334
- const txHash = await registry.acceptPublisher(publisher);
335
- s.stop();
336
- console.log(`Accepted: ${publisher}`);
337
- console.log(`Tx: ${txHash}`);
338
- console.log(`\nThey can now upload with this app's storage, and the app includes their data.`);
339
- process.exit(0);
340
- } catch (err) {
341
- console.error("Failed:", err.message);
342
- process.exit(1);
343
- }
344
- });
345
- appCmd.command("renew").description("Pay for one more period of your app's subscription (owner only)").action(async () => {
346
- try {
347
- const registry = getFangorn().getAppRegistry();
348
- const s = spinner();
349
- s.start("Renewing subscription...");
350
- const txHash = await registry.renewSubscription();
351
- const expiresAt = await registry.expiresAt();
352
- s.stop();
353
- console.log(`Renewed: ${registry.getAppId() ?? ""}`);
354
- console.log(`Expires: ${(/* @__PURE__ */ new Date(Number(expiresAt) * 1e3)).toISOString()}`);
355
- console.log(`Tx: ${txHash}`);
356
- process.exit(0);
357
- } catch (err) {
358
- console.error("Failed:", err.message);
359
- process.exit(1);
360
- }
361
- });
362
- appCmd.command("cancel").description("End your app's subscription now, without refund (owner only)").action(async () => {
363
- try {
364
- const registry = getFangorn().getAppRegistry();
365
- const ok = await confirm({ message: `Cancel ${registry.getAppId() ?? ""}'s subscription? Nothing is refunded, and the app takes no commits or joins until renewed.` });
366
- handleCancel(ok);
367
- if (!ok) process.exit(0);
368
- const s = spinner();
369
- s.start("Cancelling subscription...");
370
- const txHash = await registry.cancelSubscription();
371
- s.stop();
372
- console.log(`Cancelled: ${registry.getAppId() ?? ""}`);
373
- console.log(`Tx: ${txHash}`);
374
- process.exit(0);
375
- } catch (err) {
376
- console.error("Failed:", err.message);
377
- process.exit(1);
378
- }
379
- });
380
- appCmd.command("withdraw-fees").description("Withdraw the join fees your apps collected before joining was removed (owner only)").argument("[to]", "Where to send them; defaults to this wallet").action(async (to) => {
381
- try {
382
- const registry = getFangorn().getAppRegistry();
383
- const owed = await registry.joinFeesOwed();
384
- if (owed === 0n) {
385
- console.log("No join fees to withdraw.");
386
- process.exit(0);
387
- }
388
- const s = spinner();
389
- s.start(`Withdrawing ${formatUsdc(owed)}...`);
390
- const txHash = await registry.withdrawJoinFees(to);
391
- s.stop();
392
- console.log(`Withdrawn: ${formatUsdc(owed)}`);
393
- console.log(`Tx: ${txHash}`);
394
- process.exit(0);
395
- } catch (err) {
396
- console.error("Failed:", err.message);
397
- process.exit(1);
398
- }
399
- });
400
- appCmd.command("suspend").description("Suspend a member from your app (owner only)").argument("<publisher>", "Publisher address").action(async (publisher) => {
401
- try {
402
- const s = spinner();
403
- s.start("Suspending publisher...");
404
- const txHash = await getFangorn().getAppRegistry().setPublisherSuspended(publisher, true);
405
- s.stop();
406
- console.log(`Suspended: ${publisher}`);
407
- console.log(`Tx: ${txHash}`);
408
- process.exit(0);
409
- } catch (err) {
410
- console.error("Failed:", err.message);
411
- process.exit(1);
412
- }
413
- });
414
- appCmd.command("reinstate").description("Reinstate a suspended publisher in your app (owner only)").argument("<publisher>", "Publisher address").action(async (publisher) => {
415
- try {
416
- const s = spinner();
417
- s.start("Reinstating publisher...");
418
- const txHash = await getFangorn().getAppRegistry().setPublisherSuspended(publisher, false);
419
- s.stop();
420
- console.log(`Reinstated: ${publisher}`);
421
- console.log(`Tx: ${txHash}`);
422
- process.exit(0);
423
- } catch (err) {
424
- console.error("Failed:", err.message);
425
- process.exit(1);
426
- }
427
- });
428
- const appAdminCmd = appCmd.command("admin").description("Protocol-admin takedowns for the whole app (admin only)");
429
- /** The AppRegistry client, refusing early if this wallet is not the protocol admin. */
430
- async function requireAdmin() {
431
- const registry = getFangorn().getAppRegistry();
432
- const self = getAccount().address;
433
- const admin = await registry.admin();
434
- if (admin.toLowerCase() !== self.toLowerCase()) throw new Error(`Not the protocol admin: this registry's admin is ${admin}, you are ${self}.`);
435
- return registry;
436
- }
437
- appAdminCmd.command("suspend").description("Suspend this entire app — nobody can publish under it (admin only)").action(async () => {
438
- try {
439
- const registry = await requireAdmin();
440
- const ok = await confirm({ message: `Suspend the whole app ${registry.getAppId() ?? ""}? Every publisher, including its owner, stops being able to publish.` });
441
- handleCancel(ok);
442
- if (!ok) process.exit(0);
443
- const s = spinner();
444
- s.start("Suspending app...");
445
- const txHash = await registry.setAppSuspended(true);
446
- s.stop();
447
- console.log(`Suspended: ${currentAppId()}`);
448
- console.log(`Tx: ${txHash}`);
449
- console.log(`\nMemberships are kept — \`fangorn app admin reinstate\` restores them as they were.`);
450
- process.exit(0);
451
- } catch (err) {
452
- console.error("Failed:", err.message);
453
- process.exit(1);
454
- }
455
- });
456
- appAdminCmd.command("reinstate").description("Lift the suspension on this entire app (admin only)").action(async () => {
457
- try {
458
- const registry = await requireAdmin();
459
- const s = spinner();
460
- s.start("Reinstating app...");
461
- const txHash = await registry.setAppSuspended(false);
462
- s.stop();
463
- console.log(`Reinstated: ${currentAppId()}`);
464
- console.log(`Tx: ${txHash}`);
465
- process.exit(0);
466
- } catch (err) {
467
- console.error("Failed:", err.message);
468
- process.exit(1);
469
- }
470
- });
471
- appAdminCmd.command("status").description("Who the protocol admin is, and whether this app is suspended").action(async () => {
472
- try {
473
- const registry = getFangorn().getAppRegistry();
474
- const self = getAccount().address;
475
- const s = spinner();
476
- s.start("Reading registry...");
477
- const [admin, suspended] = await Promise.all([registry.admin(), registry.isAppSuspended()]);
478
- s.stop();
479
- console.log(`App id: ${currentAppId()}`);
480
- console.log(`Admin: ${admin}${admin.toLowerCase() === self.toLowerCase() ? " (you)" : ""}`);
481
- console.log(`Suspended: ${suspended ? "yes — nobody can publish under this app" : "no"}`);
227
+ console.log(`Tx: ${result.txHash ?? "(already bound)"}`);
482
228
  process.exit(0);
483
229
  } catch (err) {
484
230
  console.error("Failed:", err.message);
@@ -497,7 +243,6 @@ program.command("wallet").description("Show the wallet this CLI signs with").arg
497
243
  console.log(`Public key: ${account.publicKey}`);
498
244
  console.log(`Balance: ${formatEther(balance)} ETH`);
499
245
  console.log(`Network: ${cfg.cfg.chain.name} (${cfg.cfg.caip2.toString()})`);
500
- console.log(`App: ${currentAppName()}`);
501
246
  console.log(`Config: ${existsSync(CONFIG_PATH) ? CONFIG_PATH : "(from environment)"}`);
502
247
  if (opts.reveal) {
503
248
  console.log(`\nPrivate key: ${cfg.privateKey}`);
@@ -536,16 +281,69 @@ program.command("repo").description("Repository operations").command("init").des
536
281
  process.exit(1);
537
282
  }
538
283
  });
539
- 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) => {
284
+ program.command("add").description("Stage files as records: csv/jsonl/json arrays → a record per row, other text → one record per file").argument("<paths...>", "Files or directories (dot entries skipped)").option("--type <type>", "Record type (default: file name, or \"file\" for text)").option("--id-column <col>", "Column/field holding the record id", "id").action((paths, options) => {
285
+ try {
286
+ const repo = LocalRepo.open();
287
+ const staged = repo.staged();
288
+ let n = 0;
289
+ for (const p of paths) for (const rel of walk(repo.root(), join(process.cwd(), p))) {
290
+ const got = fileToRecords(repo.root(), rel, options);
291
+ if (!got) {
292
+ console.warn(`skipped (binary): ${rel}`);
293
+ continue;
294
+ }
295
+ const ids = new Set(got.records.map((r) => r.id));
296
+ staged.records = staged.records.filter((r) => !r.id || !ids.has(r.id)).concat(got.records);
297
+ staged.deletes = staged.deletes.filter((d) => !ids.has(d)).concat(got.deletes);
298
+ n += got.records.length + got.deletes.length;
299
+ console.log(`added ${rel} (${got.records.length.toString()} record(s))`);
300
+ }
301
+ repo.setStaged(staged);
302
+ console.log(`${n.toString()} change(s) staged. Run \`fangorn commit\`.`);
303
+ process.exit(0);
304
+ } catch (err) {
305
+ console.error("Failed:", err.message);
306
+ process.exit(1);
307
+ }
308
+ });
309
+ program.command("rm").description("Stage record deletes (and drop them from the staging area)").argument("<ids...>", "Record ids").action((ids) => {
310
+ try {
311
+ const repo = LocalRepo.open();
312
+ const staged = repo.staged();
313
+ staged.records = staged.records.filter((r) => !r.id || !ids.includes(r.id));
314
+ staged.deletes = [...new Set([...staged.deletes, ...ids])];
315
+ repo.setStaged(staged);
316
+ console.log(`${ids.length.toString()} delete(s) staged.`);
317
+ process.exit(0);
318
+ } catch (err) {
319
+ console.error("Failed:", err.message);
320
+ process.exit(1);
321
+ }
322
+ });
323
+ 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\"]} (default: the staging area, see `fangorn add`)").option("--replace", "Snapshot semantics: the file replaces the namespace's previous contents (omitted entries are removed)").option("--paid <fields>", "Comma-separated payload fields to sell: sealed (field-v1) and priced with signed terms").option("--price <usdc>", "Price of each paid record, in USDC (e.g. 0.01)").option("--share <percent>", "Share of each sale paid to the referrer (Fangorn takes none by default)", "0").option("--deadline-days <days>", "Days the signed terms stay buyable", "365").option("--key-server <url>", "Key server a new deposit is sealed to (an existing deposit keeps its own)", "https://keys-test.fangorn.network").action(async (file, options) => {
540
324
  try {
541
- if (!existsSync(file)) throw new Error(`file not found: ${file}`);
542
- const data = JSON.parse(readFileSync(file, "utf-8"));
543
- const records = data.records ?? [];
544
- const deletes = data.deletes ?? [];
545
- if (!Array.isArray(records) || !Array.isArray(deletes) || records.length + deletes.length === 0) throw new Error(`${file} must contain a non-empty "records" or "deletes" array`);
546
325
  const repo = LocalRepo.open();
326
+ if (file && !existsSync(file)) throw new Error(`file not found: ${file}`);
327
+ const data = file ? JSON.parse(readFileSync(file, "utf-8")) : repo.staged();
328
+ let records = data.records ?? [];
329
+ const deletes = data.deletes ?? [];
330
+ if (!Array.isArray(records) || !Array.isArray(deletes) || records.length + deletes.length === 0) throw new Error(file ? `${file} must contain a non-empty "records" or "deletes" array` : "nothing staged — run `fangorn add <paths>` first");
547
331
  const fangorn = getFangorn();
548
332
  const parent = repo.head() ?? void 0;
333
+ if (options.paid) {
334
+ if (!options.price) throw new Error("--paid needs --price");
335
+ if (parent && parent !== await fangorn.onChainTip(fangorn.getAddress(), repo.namespace())) throw new Error("push your local commits before committing paid records");
336
+ const shareBps = Math.round(Number(options.share) * 100);
337
+ const days = Number(options.deadlineDays);
338
+ if (!Number.isFinite(days) || days <= 0) throw new Error(`--deadline-days must be a positive number, got ${options.deadlineDays}`);
339
+ records = await sealRecords(fangorn, repo.namespace(), records, {
340
+ fields: options.paid.split(",").map((f) => f.trim()).filter(Boolean),
341
+ price: parseUnits(options.price, 6),
342
+ shareBps,
343
+ deadline: BigInt(Math.floor(Date.now() / 1e3 + days * 86400)),
344
+ keyServer: options.keyServer
345
+ });
346
+ }
549
347
  const s = spinner();
550
348
  s.start(parent ? "Committing (building on local HEAD)..." : "Committing (initial)...");
551
349
  const result = await fangorn.commit({
@@ -553,16 +351,18 @@ program.command("commit").description("Put/delete a namespace's records in a new
553
351
  records,
554
352
  deletes,
555
353
  parent,
556
- message: options.message,
557
354
  replace: options.replace
558
355
  });
559
356
  s.stop();
560
357
  repo.setHead(result.commitCid);
358
+ if (!file) repo.setStaged({
359
+ records: [],
360
+ deletes: []
361
+ });
561
362
  console.log(`Commit: ${result.commitCid}`);
562
363
  console.log(`Parent: ${result.parent ?? "(root)"}`);
563
364
  console.log(`Tree: ${result.root}`);
564
365
  console.log(`Staged: ${records.length.toString()} put(s) / ${deletes.length.toString()} delete(s)`);
565
- console.log(`Message: ${options.message}`);
566
366
  console.log(`\nCommitted locally. Run \`fangorn push\` to settle it on-chain.`);
567
367
  process.exit(0);
568
368
  } catch (err) {
@@ -600,6 +400,8 @@ program.command("status").description("Compare the local tip with the on-chain t
600
400
  console.log(`Local HEAD: ${localHead ?? "(none)"}`);
601
401
  console.log(`On-chain tip: ${onChainTip ?? "(none)"}`);
602
402
  console.log(`Status: ${state}`);
403
+ const staged = repo.staged();
404
+ console.log(`Staged: ${staged.records.length.toString()} put(s) / ${staged.deletes.length.toString()} delete(s)`);
603
405
  process.exit(0);
604
406
  } catch (err) {
605
407
  console.error("Failed:", err.message);
@@ -617,8 +419,7 @@ program.command("log").description("Walk commit history from the local tip").opt
617
419
  for await (const c of fangorn.log(head, options.max)) {
618
420
  console.log(`commit ${c.cid}`);
619
421
  console.log(`Epoch: ${c.epoch.toString()}`);
620
- console.log(`Tree: ${c.root}`);
621
- console.log(`\n ${c.message}\n`);
422
+ console.log(`Tree: ${c.root}\n`);
622
423
  }
623
424
  process.exit(0);
624
425
  } catch (err) {
@@ -635,8 +436,7 @@ program.command("show").description("Show a commit and what it changed vs. its p
635
436
  console.log(`commit ${target}`);
636
437
  console.log(`Epoch: ${diff.epoch.toString()}`);
637
438
  console.log(`Parent: ${diff.parent ?? "(root)"}`);
638
- console.log(`Tree: ${diff.root}`);
639
- console.log(`\n ${diff.message}\n`);
439
+ console.log(`Tree: ${diff.root}\n`);
640
440
  console.log(`Changes vs. parent: +${diff.added.length.toString()} / -${diff.removed.length.toString()} key(s)`);
641
441
  for (const k of diff.added) console.log(` + ${k}`);
642
442
  for (const k of diff.removed) console.log(` - ${k}`);
@@ -667,7 +467,7 @@ program.command("clone").description("Track an existing on-chain namespace by re
667
467
  process.exit(1);
668
468
  }
669
469
  });
670
- 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) => {
470
+ 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) => {
671
471
  try {
672
472
  const fangorn = getFangorn();
673
473
  let namespace = namespaceArg;
@@ -682,7 +482,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
682
482
  owner = owner ?? fangorn.getAddress();
683
483
  }
684
484
  const repoDir = join(process.cwd(), ".fangorn");
685
- const cursorPath = join(repoDir, `subscribe-${owner ?? "app"}-${namespace ?? "all"}.json`);
485
+ const cursorPath = join(repoDir, `subscribe-${owner ?? "all"}-${namespace ?? "all"}.json`);
686
486
  const readCursor = () => {
687
487
  if (options.fromStart) return 0n;
688
488
  if (options.fromBlock !== void 0) return options.fromBlock;
@@ -701,7 +501,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
701
501
  };
702
502
  const bigintReplacer = (_k, v) => typeof v === "bigint" ? v.toString() : v;
703
503
  const fromBlock = readCursor();
704
- console.error(`Subscribing to "${namespace ?? "*"}" @ ${owner ?? "* (whole app)"} ` + (fromBlock !== void 0 ? `from block ${fromBlock.toString()}` : "(live from current tip)") + ` — Ctrl-C to stop.`);
504
+ console.error(`Subscribing to "${namespace ?? "*"}" @ ${owner ?? "*"} ` + (fromBlock !== void 0 ? `from block ${fromBlock.toString()}` : "(live from current tip)") + ` — Ctrl-C to stop.`);
705
505
  const controller = new AbortController();
706
506
  process.on("SIGINT", () => {
707
507
  controller.abort();
@@ -709,7 +509,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
709
509
  process.on("SIGTERM", () => {
710
510
  controller.abort();
711
511
  });
712
- const stream = options.all ? fangorn.subscribeApp({
512
+ const stream = options.all ? fangorn.subscribeAll({
713
513
  repo: namespace,
714
514
  owner,
715
515
  fromBlock,
@@ -1,13 +1,10 @@
1
1
  import "./cli.js";
2
- import * as viem161 from "viem";
3
2
 
4
3
  //#region src/cli/index.d.ts
5
- declare const getChain: (chainStr: string) => viem161.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 };