@fangorn-network/sdk 0.1.0 → 0.1.2

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 (72) hide show
  1. package/README.md +1 -1
  2. package/lib/cli/cli.js +126 -325
  3. package/lib/cli/index.d.ts +2 -3
  4. package/lib/cli/index.js +10 -15
  5. package/lib/cli/sell.d.ts +28 -0
  6. package/lib/cli/sell.js +95 -0
  7. package/lib/cli/stage.d.ts +19 -0
  8. package/lib/cli/stage.js +94 -0
  9. package/lib/config.d.ts +71 -81
  10. package/lib/config.js +22 -38
  11. package/lib/contracts/data-registry/abi.d.ts +195 -19
  12. package/lib/contracts/data-registry/abi.js +409 -206
  13. package/lib/contracts/data-registry/index.d.ts +126 -2
  14. package/lib/contracts/data-registry/index.js +174 -1
  15. package/lib/contracts/index.d.ts +4 -7
  16. package/lib/contracts/index.js +4 -7
  17. package/lib/contracts/logs.d.ts +1 -1
  18. package/lib/contracts/logs.js +1 -1
  19. package/lib/contracts/{membership-registry → settlement-registry}/abi.d.ts +301 -636
  20. package/lib/contracts/settlement-registry/abi.js +962 -0
  21. package/lib/contracts/settlement-registry/index.d.ts +143 -0
  22. package/lib/contracts/settlement-registry/index.js +213 -0
  23. package/lib/crypto/aes.d.ts +2 -2
  24. package/lib/crypto/aes.js +4 -4
  25. package/lib/crypto/encryption.d.ts +8 -109
  26. package/lib/crypto/encryption.js +16 -114
  27. package/lib/crypto/paid.d.ts +104 -0
  28. package/lib/crypto/paid.js +147 -0
  29. package/lib/engine/car.d.ts +5 -1
  30. package/lib/engine/car.js +2 -2
  31. package/lib/engine/index.d.ts +33 -14
  32. package/lib/engine/index.js +98 -41
  33. package/lib/engine/records.d.ts +19 -8
  34. package/lib/engine/records.js +81 -7
  35. package/lib/engine/test-helpers.d.ts +2 -3
  36. package/lib/engine/test-helpers.js +7 -5
  37. package/lib/erc8004.js +6 -6
  38. package/lib/fangorn.d.ts +65 -86
  39. package/lib/fangorn.js +115 -153
  40. package/lib/feed.d.ts +7 -8
  41. package/lib/feed.js +7 -8
  42. package/lib/index.d.ts +10 -13
  43. package/lib/index.js +10 -13
  44. package/lib/providers/storage/signed-url.d.ts +2 -10
  45. package/lib/providers/storage/signed-url.js +5 -15
  46. package/lib/providers/storage/types.d.ts +1 -1
  47. package/lib/providers/storage/utils.js +5 -3
  48. package/lib/test/key-server.d.ts +12 -0
  49. package/lib/test/key-server.js +30 -0
  50. package/lib/test/mem-registry.d.ts +14 -19
  51. package/lib/test/mem-registry.js +44 -37
  52. package/lib/test/sdk-suite.d.ts +1 -4
  53. package/lib/test/sdk-suite.js +16 -87
  54. package/lib/test/testbed.d.ts +12 -22
  55. package/lib/test/testbed.js +29 -56
  56. package/lib/types/index.d.ts +6 -11
  57. package/package.json +1 -1
  58. package/lib/contracts/app-registry/abi.d.ts +0 -1265
  59. package/lib/contracts/app-registry/abi.js +0 -1454
  60. package/lib/contracts/app-registry/index.d.ts +0 -161
  61. package/lib/contracts/app-registry/index.js +0 -274
  62. package/lib/contracts/membership-registry/abi.js +0 -1333
  63. package/lib/contracts/membership-registry/index.d.ts +0 -79
  64. package/lib/contracts/membership-registry/index.js +0 -104
  65. package/lib/contracts/types.d.ts +0 -10
  66. package/lib/contracts/types.js +0 -12
  67. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +0 -1
  68. package/lib/harness/examples/hackmd/build-markdown-graph.js +0 -17
  69. package/lib/harness/index.d.ts +0 -58
  70. package/lib/harness/index.js +0 -73
  71. package/lib/registry.d.ts +0 -118
  72. package/lib/registry.js +0 -184
package/README.md CHANGED
@@ -62,7 +62,7 @@ The [Guide](docs/GUIDE.md) covers the full flow: commit vs push, epochs, history
62
62
 
63
63
  ## Network
64
64
 
65
- Fangorn runs on **Base Sepolia**. The DataRegistry, SettlementRegistry, and hosted upload worker are all deployed there. Addresses are in [`src/config.ts`](src/config.ts) (`BaseSepoliaConfig`). To use a local anvil or a private deployment, pass your own `NetworkConfig` to `Fangorn.create`, or set the `FANGORN_*` overrides for the CLI (see the [Guide](docs/GUIDE.md#configure)). Contract sources are in [fangorn-network/contracts](https://github.com/fangorn-network/contracts).
65
+ Fangorn runs on **Base Sepolia** (the default) and **Arbitrum Sepolia**. Each has its own DataRegistry and SettlementRegistry; only Base Sepolia has a hosted upload worker. Addresses are in [`src/config.ts`](src/config.ts) (`BaseSepoliaConfig`, `ArbitrumSepoliaConfig`). The CLI asks for the network in `fangorn init`, and `CHAIN_NAME=arbitrumSepolia` overrides it. To use a local anvil or a private deployment, pass your own `NetworkConfig` to `Fangorn.create`, or set the `FANGORN_*` overrides for the CLI (see the [Guide](docs/GUIDE.md#configure)). Contract sources are in [fangorn-network/contracts](https://github.com/fangorn-network/contracts).
66
66
 
67
67
  ## Development
68
68
 
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";
5
+ import { sealRecords } from "./sell.js";
6
+ import { fileToRecords, walk } from "./stage.js";
7
7
  import { handleCancel, selectChain } from "./index.js";
8
- import { createPublicClient, formatEther, formatUnits, http } from "viem";
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,13 @@ 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
40
  const storedChain = stored.chainName === "Arbitrum Sepolia" ? "arbitrumSepolia" : stored.chainName;
42
41
  _config = {
43
42
  privateKey: stored.privateKey,
44
- cfg: getNetwork(envChain ?? storedChain),
45
- appId: envAppId ?? nonBlank(stored.appId),
43
+ cfg: network(envChain ?? storedChain),
46
44
  pinataJwt: stored.pinataJwt,
47
45
  pinataGateway: stored.pinataGateway,
48
46
  signedUrlWorkerUrl: stored.signedUrlWorkerUrl ?? ""
@@ -53,8 +51,7 @@ function loadConfig() {
53
51
  if (!privateKey) throw new Error("Incomplete environment configuration. Missing: ETH_PRIVATE_KEY\nSet it or run `fangorn init` to use a config file.");
54
52
  _config = {
55
53
  privateKey,
56
- cfg: getNetwork(envChain ?? "baseSepolia"),
57
- appId: envAppId,
54
+ cfg: network(envChain ?? "baseSepolia"),
58
55
  pinataJwt: pinataJwt ?? "",
59
56
  pinataGateway: pinataGateway ?? "",
60
57
  signedUrlWorkerUrl: signedUrlWorkerUrl ?? ""
@@ -63,6 +60,25 @@ function loadConfig() {
63
60
  }
64
61
  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
62
  }
63
+ /**
64
+ * The named network, with its RPC and contracts overridable from the environment:
65
+ * FANGORN_RPC_URL, FANGORN_DATA_REGISTRY and FANGORN_SETTLEMENT_REGISTRY, for a local
66
+ * chain (an anvil with the contracts deployed) or a private RPC. Blank counts as unset.
67
+ */
68
+ function network(name) {
69
+ const cfg = getNetwork(name);
70
+ const address = (variable) => {
71
+ const value = nonBlank(process.env[variable]);
72
+ if (value !== void 0 && !isAddress(value)) throw new Error(`${variable} is not an address: "${value}"`);
73
+ return value;
74
+ };
75
+ return {
76
+ ...cfg,
77
+ rpcUrl: nonBlank(process.env.FANGORN_RPC_URL) ?? cfg.rpcUrl,
78
+ dataRegistryContractAddress: address("FANGORN_DATA_REGISTRY") ?? cfg.dataRegistryContractAddress,
79
+ settlementRegistryContractAddress: address("FANGORN_SETTLEMENT_REGISTRY") ?? cfg.settlementRegistryContractAddress
80
+ };
81
+ }
66
82
  function getAccount() {
67
83
  if (_account) return _account;
68
84
  _account = privateKeyToAccount(loadConfig().privateKey);
@@ -81,27 +97,10 @@ function getFangorn() {
81
97
  _fangorn = Fangorn.create({
82
98
  privateKey: cfg.privateKey,
83
99
  storage,
84
- config: cfg.cfg,
85
- appId: appFlag() ?? cfg.appId
100
+ config: cfg.cfg
86
101
  });
87
102
  return _fangorn;
88
103
  }
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
104
  var LocalRepo = class LocalRepo {
106
105
  constructor(dir, state) {
107
106
  this.dir = dir;
@@ -146,11 +145,23 @@ var LocalRepo = class LocalRepo {
146
145
  this.state.head = cid;
147
146
  this.save();
148
147
  }
148
+ root() {
149
+ return this.dir;
150
+ }
151
+ /** The staging area: what the next `fangorn commit` (no file) will commit. */
152
+ staged() {
153
+ const p = join(this.dir, ".fangorn", "index.json");
154
+ return existsSync(p) ? JSON.parse(readFileSync(p, "utf-8")) : {
155
+ records: [],
156
+ deletes: []
157
+ };
158
+ }
159
+ setStaged(s) {
160
+ writeFileSync(join(this.dir, ".fangorn", "index.json"), JSON.stringify(s, null, 2), "utf-8");
161
+ }
149
162
  };
150
163
  const program = new Command();
151
- const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
152
164
  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
165
  program.command("init").description("Configure your Fangorn credentials").action(async () => {
155
166
  intro("Fangorn Setup");
156
167
  const chainName = await selectChain();
@@ -166,7 +177,7 @@ program.command("init").description("Configure your Fangorn credentials").action
166
177
  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
178
  handleCancel(pinataJwt);
168
179
  const pinataGateway = await text({
169
- message: "Pinata Gateway URL (optional; blank uses a public IPFS gateway):",
180
+ message: "Pinata Gateway URL (optional; blank uses the network's gateway):",
170
181
  placeholder: "https://your-gateway.mypinata.cloud"
171
182
  });
172
183
  handleCancel(pinataGateway);
@@ -180,124 +191,25 @@ program.command("init").description("Configure your Fangorn credentials").action
180
191
  chainName,
181
192
  pinataJwt,
182
193
  pinataGateway,
183
- signedUrlWorkerUrl,
184
- appId: existsSync(CONFIG_PATH) ? readStoredConfig().appId : void 0
194
+ signedUrlWorkerUrl
185
195
  });
186
196
  outro(`Config saved to ${CONFIG_PATH}`);
187
197
  });
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) => {
198
+ 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
199
  try {
292
200
  const cfg = loadConfig();
293
201
  const url = agentCardUrl(cardUrl, opts.accessWorker);
202
+ const local = opts.repo ? void 0 : LocalRepo.open();
203
+ const repo = opts.repo ?? local?.namespace() ?? "";
294
204
  const s = spinner();
295
205
  const chainId = cfg.cfg.caip2;
296
206
  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");
207
+ 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");
208
+ const fangorn = getFangorn();
298
209
  let result;
299
210
  try {
300
- result = await getFangorn().registerAgent(url, {
211
+ result = await fangorn.registerAgent(url, {
212
+ repo,
301
213
  mcp: opts.mcp,
302
214
  update,
303
215
  skipRegister: opts.skipRegister
@@ -305,180 +217,15 @@ appCmd.command("agent").description("Register this app's gateway as an ERC-8004
305
217
  } catch (e) {
306
218
  s.stop();
307
219
  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;
220
+ 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
221
  }
310
222
  s.stop();
223
+ if (local && result.txHash) local.setHead(await fangorn.onChainTip(fangorn.getAddress(), repo));
311
224
  const agentId = result.agentId !== void 0 ? `${String(chainId)}:${String(result.agentId)}` : void 0;
312
- const txHash = result.txHash ?? "(already bound)";
313
225
  if (agentId) console.log(`Agent ID: ${agentId}`);
226
+ console.log(`Repo: ${repo}`);
314
227
  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"}`);
228
+ console.log(`Tx: ${result.txHash ?? "(already bound)"}`);
482
229
  process.exit(0);
483
230
  } catch (err) {
484
231
  console.error("Failed:", err.message);
@@ -497,7 +244,6 @@ program.command("wallet").description("Show the wallet this CLI signs with").arg
497
244
  console.log(`Public key: ${account.publicKey}`);
498
245
  console.log(`Balance: ${formatEther(balance)} ETH`);
499
246
  console.log(`Network: ${cfg.cfg.chain.name} (${cfg.cfg.caip2.toString()})`);
500
- console.log(`App: ${currentAppName()}`);
501
247
  console.log(`Config: ${existsSync(CONFIG_PATH) ? CONFIG_PATH : "(from environment)"}`);
502
248
  if (opts.reveal) {
503
249
  console.log(`\nPrivate key: ${cfg.privateKey}`);
@@ -536,16 +282,69 @@ program.command("repo").description("Repository operations").command("init").des
536
282
  process.exit(1);
537
283
  }
538
284
  });
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) => {
285
+ 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) => {
286
+ try {
287
+ const repo = LocalRepo.open();
288
+ const staged = repo.staged();
289
+ let n = 0;
290
+ for (const p of paths) for (const rel of walk(repo.root(), join(process.cwd(), p))) {
291
+ const got = fileToRecords(repo.root(), rel, options);
292
+ if (!got) {
293
+ console.warn(`skipped (binary): ${rel}`);
294
+ continue;
295
+ }
296
+ const ids = new Set(got.records.map((r) => r.id));
297
+ staged.records = staged.records.filter((r) => !r.id || !ids.has(r.id)).concat(got.records);
298
+ staged.deletes = staged.deletes.filter((d) => !ids.has(d)).concat(got.deletes);
299
+ n += got.records.length + got.deletes.length;
300
+ console.log(`added ${rel} (${got.records.length.toString()} record(s))`);
301
+ }
302
+ repo.setStaged(staged);
303
+ console.log(`${n.toString()} change(s) staged. Run \`fangorn commit\`.`);
304
+ process.exit(0);
305
+ } catch (err) {
306
+ console.error("Failed:", err.message);
307
+ process.exit(1);
308
+ }
309
+ });
310
+ program.command("rm").description("Stage record deletes (and drop them from the staging area)").argument("<ids...>", "Record ids").action((ids) => {
311
+ try {
312
+ const repo = LocalRepo.open();
313
+ const staged = repo.staged();
314
+ staged.records = staged.records.filter((r) => !r.id || !ids.includes(r.id));
315
+ staged.deletes = [...new Set([...staged.deletes, ...ids])];
316
+ repo.setStaged(staged);
317
+ console.log(`${ids.length.toString()} delete(s) staged.`);
318
+ process.exit(0);
319
+ } catch (err) {
320
+ console.error("Failed:", err.message);
321
+ process.exit(1);
322
+ }
323
+ });
324
+ 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
325
  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
326
  const repo = LocalRepo.open();
327
+ if (file && !existsSync(file)) throw new Error(`file not found: ${file}`);
328
+ const data = file ? JSON.parse(readFileSync(file, "utf-8")) : repo.staged();
329
+ let records = data.records ?? [];
330
+ const deletes = data.deletes ?? [];
331
+ 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
332
  const fangorn = getFangorn();
548
333
  const parent = repo.head() ?? void 0;
334
+ if (options.paid) {
335
+ if (!options.price) throw new Error("--paid needs --price");
336
+ if (parent && parent !== await fangorn.onChainTip(fangorn.getAddress(), repo.namespace())) throw new Error("push your local commits before committing paid records");
337
+ const shareBps = Math.round(Number(options.share) * 100);
338
+ const days = Number(options.deadlineDays);
339
+ if (!Number.isFinite(days) || days <= 0) throw new Error(`--deadline-days must be a positive number, got ${options.deadlineDays}`);
340
+ records = await sealRecords(fangorn, repo.namespace(), records, {
341
+ fields: options.paid.split(",").map((f) => f.trim()).filter(Boolean),
342
+ price: parseUnits(options.price, 6),
343
+ shareBps,
344
+ deadline: BigInt(Math.floor(Date.now() / 1e3 + days * 86400)),
345
+ keyServer: options.keyServer
346
+ });
347
+ }
549
348
  const s = spinner();
550
349
  s.start(parent ? "Committing (building on local HEAD)..." : "Committing (initial)...");
551
350
  const result = await fangorn.commit({
@@ -553,16 +352,18 @@ program.command("commit").description("Put/delete a namespace's records in a new
553
352
  records,
554
353
  deletes,
555
354
  parent,
556
- message: options.message,
557
355
  replace: options.replace
558
356
  });
559
357
  s.stop();
560
358
  repo.setHead(result.commitCid);
359
+ if (!file) repo.setStaged({
360
+ records: [],
361
+ deletes: []
362
+ });
561
363
  console.log(`Commit: ${result.commitCid}`);
562
364
  console.log(`Parent: ${result.parent ?? "(root)"}`);
563
365
  console.log(`Tree: ${result.root}`);
564
366
  console.log(`Staged: ${records.length.toString()} put(s) / ${deletes.length.toString()} delete(s)`);
565
- console.log(`Message: ${options.message}`);
566
367
  console.log(`\nCommitted locally. Run \`fangorn push\` to settle it on-chain.`);
567
368
  process.exit(0);
568
369
  } catch (err) {
@@ -600,6 +401,8 @@ program.command("status").description("Compare the local tip with the on-chain t
600
401
  console.log(`Local HEAD: ${localHead ?? "(none)"}`);
601
402
  console.log(`On-chain tip: ${onChainTip ?? "(none)"}`);
602
403
  console.log(`Status: ${state}`);
404
+ const staged = repo.staged();
405
+ console.log(`Staged: ${staged.records.length.toString()} put(s) / ${staged.deletes.length.toString()} delete(s)`);
603
406
  process.exit(0);
604
407
  } catch (err) {
605
408
  console.error("Failed:", err.message);
@@ -617,8 +420,7 @@ program.command("log").description("Walk commit history from the local tip").opt
617
420
  for await (const c of fangorn.log(head, options.max)) {
618
421
  console.log(`commit ${c.cid}`);
619
422
  console.log(`Epoch: ${c.epoch.toString()}`);
620
- console.log(`Tree: ${c.root}`);
621
- console.log(`\n ${c.message}\n`);
423
+ console.log(`Tree: ${c.root}\n`);
622
424
  }
623
425
  process.exit(0);
624
426
  } catch (err) {
@@ -635,8 +437,7 @@ program.command("show").description("Show a commit and what it changed vs. its p
635
437
  console.log(`commit ${target}`);
636
438
  console.log(`Epoch: ${diff.epoch.toString()}`);
637
439
  console.log(`Parent: ${diff.parent ?? "(root)"}`);
638
- console.log(`Tree: ${diff.root}`);
639
- console.log(`\n ${diff.message}\n`);
440
+ console.log(`Tree: ${diff.root}\n`);
640
441
  console.log(`Changes vs. parent: +${diff.added.length.toString()} / -${diff.removed.length.toString()} key(s)`);
641
442
  for (const k of diff.added) console.log(` + ${k}`);
642
443
  for (const k of diff.removed) console.log(` - ${k}`);
@@ -667,7 +468,7 @@ program.command("clone").description("Track an existing on-chain namespace by re
667
468
  process.exit(1);
668
469
  }
669
470
  });
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) => {
471
+ 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
472
  try {
672
473
  const fangorn = getFangorn();
673
474
  let namespace = namespaceArg;
@@ -682,7 +483,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
682
483
  owner = owner ?? fangorn.getAddress();
683
484
  }
684
485
  const repoDir = join(process.cwd(), ".fangorn");
685
- const cursorPath = join(repoDir, `subscribe-${owner ?? "app"}-${namespace ?? "all"}.json`);
486
+ const cursorPath = join(repoDir, `subscribe-${owner ?? "all"}-${namespace ?? "all"}.json`);
686
487
  const readCursor = () => {
687
488
  if (options.fromStart) return 0n;
688
489
  if (options.fromBlock !== void 0) return options.fromBlock;
@@ -701,7 +502,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
701
502
  };
702
503
  const bigintReplacer = (_k, v) => typeof v === "bigint" ? v.toString() : v;
703
504
  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.`);
505
+ console.error(`Subscribing to "${namespace ?? "*"}" @ ${owner ?? "*"} ` + (fromBlock !== void 0 ? `from block ${fromBlock.toString()}` : "(live from current tip)") + ` — Ctrl-C to stop.`);
705
506
  const controller = new AbortController();
706
507
  process.on("SIGINT", () => {
707
508
  controller.abort();
@@ -709,7 +510,7 @@ program.command("subscribe").description("Watch on-chain pushes to a namespace a
709
510
  process.on("SIGTERM", () => {
710
511
  controller.abort();
711
512
  });
712
- const stream = options.all ? fangorn.subscribeApp({
513
+ const stream = options.all ? fangorn.subscribeAll({
713
514
  repo: namespace,
714
515
  owner,
715
516
  fromBlock,
@@ -1,13 +1,12 @@
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;
5
+ /** Asks which supported network to use, and returns its name ("baseSepolia", ...). */
7
6
  declare const selectChain: () => Promise<string>;
8
7
  declare function parseGadgetArg(raw: string): {
9
8
  type: string;
10
9
  args: string[];
11
10
  };
12
11
  //#endregion
13
- export { getChain, handleCancel, parseGadgetArg, selectChain };
12
+ export { handleCancel, parseGadgetArg, selectChain };