@fangorn-network/sdk 0.1.0-dev → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/lib/cli/cli.js +328 -128
  2. package/lib/cli/index.d.ts +4 -1
  3. package/lib/cli/index.js +20 -2
  4. package/lib/config.d.ts +111 -48
  5. package/lib/config.js +39 -11
  6. package/lib/contracts/app-registry/abi.d.ts +1265 -0
  7. package/lib/contracts/app-registry/abi.js +1454 -0
  8. package/lib/contracts/app-registry/index.d.ts +161 -0
  9. package/lib/contracts/app-registry/index.js +274 -0
  10. package/lib/contracts/data-registry/abi.d.ts +19 -195
  11. package/lib/contracts/data-registry/abi.js +206 -409
  12. package/lib/contracts/data-registry/index.d.ts +2 -126
  13. package/lib/contracts/data-registry/index.js +1 -174
  14. package/lib/contracts/index.d.ts +7 -4
  15. package/lib/contracts/index.js +7 -4
  16. package/lib/contracts/logs.d.ts +1 -1
  17. package/lib/contracts/logs.js +1 -1
  18. package/lib/contracts/{settlement-registry → membership-registry}/abi.d.ts +636 -301
  19. package/lib/contracts/membership-registry/abi.js +1333 -0
  20. package/lib/contracts/membership-registry/index.d.ts +79 -0
  21. package/lib/contracts/membership-registry/index.js +104 -0
  22. package/lib/contracts/types.d.ts +10 -0
  23. package/lib/contracts/types.js +12 -0
  24. package/lib/crypto/aes.d.ts +2 -2
  25. package/lib/crypto/aes.js +4 -4
  26. package/lib/crypto/encryption.d.ts +109 -8
  27. package/lib/crypto/encryption.js +114 -16
  28. package/lib/engine/car.d.ts +1 -5
  29. package/lib/engine/car.js +2 -2
  30. package/lib/engine/index.d.ts +14 -33
  31. package/lib/engine/index.js +41 -98
  32. package/lib/engine/records.d.ts +8 -19
  33. package/lib/engine/records.js +7 -81
  34. package/lib/engine/test-helpers.d.ts +3 -2
  35. package/lib/engine/test-helpers.js +5 -7
  36. package/lib/erc8004.js +10 -7
  37. package/lib/fangorn.d.ts +86 -65
  38. package/lib/fangorn.js +153 -115
  39. package/lib/feed.d.ts +8 -7
  40. package/lib/feed.js +8 -7
  41. package/lib/harness/examples/hackmd/build-markdown-graph.d.ts +1 -0
  42. package/lib/harness/examples/hackmd/build-markdown-graph.js +17 -0
  43. package/lib/harness/index.d.ts +58 -0
  44. package/lib/harness/index.js +73 -0
  45. package/lib/index.d.ts +13 -10
  46. package/lib/index.js +13 -10
  47. package/lib/node_modules/{@jridgewell → .pnpm/@jridgewell_sourcemap-codec@1.5.5/node_modules/@jridgewell}/sourcemap-codec/dist/sourcemap-codec.js +1 -1
  48. package/lib/node_modules/{@vitest → .pnpm/@vitest_expect@4.0.18/node_modules/@vitest}/expect/dist/index.js +8 -8
  49. package/lib/node_modules/{@vitest → .pnpm/@vitest_pretty-format@4.0.18/node_modules/@vitest}/pretty-format/dist/index.js +2 -2
  50. package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/chunk-tasks.js +2 -2
  51. package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/index.js +4 -4
  52. package/lib/node_modules/{@vitest → .pnpm/@vitest_snapshot@4.0.18/node_modules/@vitest}/snapshot/dist/index.js +4 -4
  53. package/lib/node_modules/{@vitest → .pnpm/@vitest_spy@4.0.18/node_modules/@vitest}/spy/dist/index.js +1 -1
  54. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/chunk-_commonjsHelpers.js +1 -1
  55. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/chunk-pathe.M-eThtNZ.js +1 -1
  56. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/diff.js +3 -3
  57. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/display.js +2 -2
  58. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/error.js +2 -2
  59. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/helpers.js +1 -1
  60. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/serialize.js +1 -1
  61. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/source-map.js +1 -1
  62. package/lib/node_modules/{@vitest → .pnpm/@vitest_utils@4.0.18/node_modules/@vitest}/utils/dist/timers.js +1 -1
  63. package/lib/node_modules/{chai → .pnpm/chai@6.2.2/node_modules/chai}/index.js +1 -1
  64. package/lib/node_modules/{magic-string → .pnpm/magic-string@0.30.21/node_modules/magic-string}/dist/magic-string.es.js +2 -2
  65. package/lib/node_modules/{pathe → .pnpm/pathe@2.0.3/node_modules/pathe}/dist/shared/pathe.M-eThtNZ.js +1 -1
  66. package/lib/node_modules/{tinyrainbow → .pnpm/tinyrainbow@3.0.3/node_modules/tinyrainbow}/dist/index.js +1 -1
  67. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/_commonjsHelpers.D26ty3Ew.js +1 -1
  68. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/date.Bq6ZW5rf.js +1 -1
  69. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/utils.DvEY5TfP.js +2 -2
  70. package/lib/node_modules/{vitest → .pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest}/dist/chunks/vi.2VT5v0um.js +11 -11
  71. package/lib/providers/storage/signed-url.d.ts +10 -2
  72. package/lib/providers/storage/signed-url.js +15 -5
  73. package/lib/providers/storage/types.d.ts +1 -1
  74. package/lib/providers/storage/utils.js +3 -5
  75. package/lib/registry.d.ts +118 -0
  76. package/lib/registry.js +184 -0
  77. package/lib/test/mem-registry.d.ts +19 -14
  78. package/lib/test/mem-registry.js +37 -44
  79. package/lib/test/sdk-suite.d.ts +4 -1
  80. package/lib/test/sdk-suite.js +89 -18
  81. package/lib/test/testbed.d.ts +5227 -5218
  82. package/lib/test/testbed.js +56 -29
  83. package/lib/types/index.d.ts +11 -6
  84. package/package.json +1 -1
  85. package/lib/cli/sell.d.ts +0 -28
  86. package/lib/cli/sell.js +0 -95
  87. package/lib/cli/stage.d.ts +0 -19
  88. package/lib/cli/stage.js +0 -94
  89. package/lib/contracts/settlement-registry/abi.js +0 -962
  90. package/lib/contracts/settlement-registry/index.d.ts +0 -143
  91. package/lib/contracts/settlement-registry/index.js +0 -213
  92. package/lib/crypto/paid.d.ts +0 -104
  93. package/lib/crypto/paid.js +0 -147
  94. package/lib/test/key-server.d.ts +0 -12
  95. package/lib/test/key-server.js +0 -30
  96. /package/lib/node_modules/{@vitest → .pnpm/@vitest_runner@4.0.18/node_modules/@vitest}/runner/dist/utils.js +0 -0
@@ -0,0 +1,118 @@
1
+ import { PreparedTx } from "./contracts/write.js";
2
+ import "./contracts/index.js";
3
+ import { Address, Hash, Hex, PublicClient, WalletClient } from "viem";
4
+
5
+ //#region src/registry.d.ts
6
+ declare const ZERO_HEAD: Hex;
7
+ /** η: epoch length in seconds. e(t) = ⌊t / η⌋. */
8
+ declare const EPOCH_SECONDS = 3600;
9
+ declare function epochOf(unixSeconds: number | bigint): number;
10
+ /** ρ = (P, s): one publisher's repo. */
11
+ interface RepoRef {
12
+ publisher: Address;
13
+ repo: string;
14
+ }
15
+ /** What an exclusion names in an app: a whole publisher, one of its repos, or one record key in a repo. */
16
+ interface Exclusion {
17
+ publisher: Address;
18
+ repo?: string;
19
+ key?: string;
20
+ }
21
+ /** One entry of the update log U, (P, s, i, h, t): a repo's head moved from `parent` to `head`. */
22
+ interface UpdateEntry {
23
+ publisher: Address;
24
+ repo: string;
25
+ /** The head's position in the repo's history, from 1. */
26
+ pos: number;
27
+ parent: Hex;
28
+ head: Hex;
29
+ /** The ordering's clock at the entry (a block number). */
30
+ t: bigint;
31
+ /** Unique per entry, for de-duplication across catch-up and live. */
32
+ id: string;
33
+ }
34
+ /** A slice of the update log: every repo, one publisher's, one repo name across publishers, or one repo. */
35
+ interface LogFilter {
36
+ publisher?: Address;
37
+ repo?: string;
38
+ }
39
+ interface Registry {
40
+ /** e(t) at the ordering's current clock. A commit's epoch must be within W of it. */
41
+ epoch(): Promise<number>;
42
+ /** H(ρ): the committed head, or ZERO_HEAD for a repo never written. */
43
+ head(ref: RepoRef): Promise<Hex>;
44
+ /**
45
+ * Does app A present `publisher`? Exactly while it provides the publisher's
46
+ * storage (`canPublish`): an app presents its publishers' latest heads, less
47
+ * its exclusions. ponytail: the paper's per-head acceptance (α_A), once apps
48
+ * validate what they present.
49
+ */
50
+ presents(app: Hex, publisher: Address): Promise<boolean>;
51
+ /** C(A, X). Odd means X is in force (Proposition 3.2). */
52
+ exclusionCount(app: Hex, x: Exclusion): Promise<number>;
53
+ /** update(s, parent → head), as the signer. Valid only while `parent` is the head (Theorem 3). It names no app. */
54
+ update(repo: string, parent: Hex, head: Hex): Promise<Hash>;
55
+ /** `update` as an unsigned transaction for `publisher` to sign. */
56
+ prepareUpdate(publisher: Address, repo: string, parent: Hex, head: Hex): Promise<PreparedTx>;
57
+ exclude(app: Hex, x: Exclusion): Promise<Hash>;
58
+ restore(app: Hex, x: Exclusion): Promise<Hash>;
59
+ /** The entries of a log between two clock values, oldest first. */
60
+ log(filter: LogFilter, from: bigint, to?: bigint): Promise<UpdateEntry[]>;
61
+ /** Follow the log live. Returns an unsubscribe function. */
62
+ watch(filter: LogFilter, onEntry: (entry: UpdateEntry) => void, onError?: (err: Error) => void, pollingInterval?: number): () => void;
63
+ /** The ordering's current clock value (a block number). */
64
+ clock(): Promise<bigint>;
65
+ }
66
+ /** True if exclusion `x` covers record `key` of repo `ref`. */
67
+ declare function covers(x: Exclusion, ref: RepoRef, key?: string): boolean;
68
+ /**
69
+ * Is anything of `ref` hidden in app `app`? Checks the publisher and the repo
70
+ * exclusions, the two that can hide a whole repo (ReadSlice line 3).
71
+ */
72
+ declare function repoExcluded(registry: Registry, app: Hex, ref: RepoRef): Promise<boolean>;
73
+ /** The slot an exclusion is counted in: keccak256(abi.encode(P, N(s), N(k))), zeros for levels it doesn't name. */
74
+ declare function exclusionId(x: Exclusion): Hex;
75
+ interface ChainRegistryConfig {
76
+ dataRegistryContractAddress: Address;
77
+ appRegistryContractAddress: Address;
78
+ logWindow?: bigint;
79
+ }
80
+ /**
81
+ * The registry on the contracts: H and U in the DataRegistry; membership, X and C
82
+ * in the AppRegistry.
83
+ *
84
+ * Gaps against Definition 3.1, each closed by the contract spec
85
+ * (docs/REGISTRY_SPEC.md):
86
+ * • the contract doesn't check the commit's epoch, nor compute the head from
87
+ * (e, parent, root). The client checks the parent before it sends an update;
88
+ * • no per-head acceptance: an app presents the latest heads of the publishers
89
+ * whose storage it provides (`canPublish`). χ_A is the owner's say. No rule
90
+ * contracts, no witnesses;
91
+ * • the protocol admin's network-wide ban, which the paper doesn't have, reads
92
+ * as a publisher exclusion in every app;
93
+ * • the logs are events read through a trusted RPC: no MMR, no proofs.
94
+ */
95
+ declare class ChainRegistry implements Registry {
96
+ private publicClient;
97
+ private walletClient?;
98
+ private readonly data;
99
+ private readonly apps;
100
+ private readonly logWindow?;
101
+ constructor(config: ChainRegistryConfig, publicClient: PublicClient, walletClient?: WalletClient | undefined);
102
+ epoch(): Promise<number>;
103
+ head(ref: RepoRef): Promise<Hex>;
104
+ presents(app: Hex, publisher: Address): Promise<boolean>;
105
+ exclusionCount(app: Hex, x: Exclusion): Promise<number>;
106
+ update(repo: string, parent: Hex, head: Hex): Promise<Hash>;
107
+ prepareUpdate(publisher: Address, repo: string, parent: Hex, head: Hex): Promise<PreparedTx>;
108
+ exclude(app: Hex, x: Exclusion): Promise<Hash>;
109
+ restore(app: Hex, x: Exclusion): Promise<Hash>;
110
+ private write;
111
+ /** U's `Updated` events, narrowed on-chain by publisher and repo. */
112
+ private source;
113
+ log(filter: LogFilter, from: bigint, to?: bigint): Promise<UpdateEntry[]>;
114
+ watch(filter: LogFilter, onEntry: (entry: UpdateEntry) => void, onError?: (err: Error) => void, pollingInterval?: number): () => void;
115
+ clock(): Promise<bigint>;
116
+ }
117
+ //#endregion
118
+ export { ChainRegistry, ChainRegistryConfig, EPOCH_SECONDS, Exclusion, LogFilter, Registry, RepoRef, UpdateEntry, ZERO_HEAD, covers, epochOf, exclusionId, repoExcluded };
@@ -0,0 +1,184 @@
1
+ import { APP_REGISTRY_ABI } from "./contracts/app-registry/abi.js";
2
+ import { prepareWrite, requireWallet, sendWrite } from "./contracts/write.js";
3
+ import { getLogsInWindows } from "./contracts/logs.js";
4
+ import { repoId } from "./contracts/data-registry/index.js";
5
+ import { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
6
+ import "./contracts/index.js";
7
+ import { encodeAbiParameters, keccak256 } from "viem";
8
+
9
+ //#region src/registry.ts
10
+ const ZERO_HEAD = "0x0000000000000000000000000000000000000000000000000000000000000000";
11
+ /** η: epoch length in seconds. e(t) = ⌊t / η⌋. */
12
+ const EPOCH_SECONDS = 3600;
13
+ function epochOf(unixSeconds) {
14
+ return Math.floor(Number(unixSeconds) / EPOCH_SECONDS);
15
+ }
16
+ /** True if exclusion `x` covers record `key` of repo `ref`. */
17
+ function covers(x, ref, key) {
18
+ if (x.publisher.toLowerCase() !== ref.publisher.toLowerCase()) return false;
19
+ if (x.repo === void 0) return true;
20
+ if (x.repo !== ref.repo) return false;
21
+ return x.key === void 0 || x.key === key;
22
+ }
23
+ /**
24
+ * Is anything of `ref` hidden in app `app`? Checks the publisher and the repo
25
+ * exclusions, the two that can hide a whole repo (ReadSlice line 3).
26
+ */
27
+ async function repoExcluded(registry, app, ref) {
28
+ return (await Promise.all([registry.exclusionCount(app, { publisher: ref.publisher }), registry.exclusionCount(app, ref)])).some((c) => c % 2 === 1);
29
+ }
30
+ const ZERO = ZERO_HEAD;
31
+ /** The slot an exclusion is counted in: keccak256(abi.encode(P, N(s), N(k))), zeros for levels it doesn't name. */
32
+ function exclusionId(x) {
33
+ return keccak256(encodeAbiParameters([
34
+ { type: "address" },
35
+ { type: "bytes32" },
36
+ { type: "bytes32" }
37
+ ], [
38
+ x.publisher,
39
+ x.repo === void 0 ? ZERO : repoId(x.repo),
40
+ x.key === void 0 ? ZERO : repoId(x.key)
41
+ ]));
42
+ }
43
+ /**
44
+ * The registry on the contracts: H and U in the DataRegistry; membership, X and C
45
+ * in the AppRegistry.
46
+ *
47
+ * Gaps against Definition 3.1, each closed by the contract spec
48
+ * (docs/REGISTRY_SPEC.md):
49
+ * • the contract doesn't check the commit's epoch, nor compute the head from
50
+ * (e, parent, root). The client checks the parent before it sends an update;
51
+ * • no per-head acceptance: an app presents the latest heads of the publishers
52
+ * whose storage it provides (`canPublish`). χ_A is the owner's say. No rule
53
+ * contracts, no witnesses;
54
+ * • the protocol admin's network-wide ban, which the paper doesn't have, reads
55
+ * as a publisher exclusion in every app;
56
+ * • the logs are events read through a trusted RPC: no MMR, no proofs.
57
+ */
58
+ var ChainRegistry = class {
59
+ data;
60
+ apps;
61
+ logWindow;
62
+ constructor(config, publicClient, walletClient) {
63
+ this.publicClient = publicClient;
64
+ this.walletClient = walletClient;
65
+ this.data = config.dataRegistryContractAddress;
66
+ this.apps = config.appRegistryContractAddress;
67
+ this.logWindow = config.logWindow;
68
+ }
69
+ async epoch() {
70
+ return epochOf((await this.publicClient.getBlock()).timestamp);
71
+ }
72
+ async head(ref) {
73
+ const [, head] = await this.publicClient.readContract({
74
+ address: this.data,
75
+ abi: DATA_REGISTRY_ABI,
76
+ functionName: "getHead",
77
+ args: [ref.publisher, repoId(ref.repo)]
78
+ });
79
+ return head;
80
+ }
81
+ presents(app, publisher) {
82
+ return this.publicClient.readContract({
83
+ address: this.apps,
84
+ abi: APP_REGISTRY_ABI,
85
+ functionName: "canPublish",
86
+ args: [app, publisher]
87
+ });
88
+ }
89
+ async exclusionCount(app, x) {
90
+ const [count, banned] = await Promise.all([this.publicClient.readContract({
91
+ address: this.apps,
92
+ abi: APP_REGISTRY_ABI,
93
+ functionName: "exclusionCount",
94
+ args: [app, exclusionId(x)]
95
+ }), x.repo === void 0 ? this.publicClient.readContract({
96
+ address: this.apps,
97
+ abi: APP_REGISTRY_ABI,
98
+ functionName: "globalSuspensions",
99
+ args: [x.publisher]
100
+ }) : false]);
101
+ return banned ? Number(count) | 1 : Number(count);
102
+ }
103
+ update(repo, parent, head) {
104
+ return this.write(this.data, DATA_REGISTRY_ABI, "update", [
105
+ repo,
106
+ parent,
107
+ head
108
+ ]);
109
+ }
110
+ prepareUpdate(publisher, repo, parent, head) {
111
+ return prepareWrite(this.publicClient, publisher, this.data, DATA_REGISTRY_ABI, "update", [
112
+ repo,
113
+ parent,
114
+ head
115
+ ], { fallbackGas: 200000n });
116
+ }
117
+ exclude(app, x) {
118
+ return this.write(this.apps, APP_REGISTRY_ABI, "exclude", exclusionArgs(app, x));
119
+ }
120
+ restore(app, x) {
121
+ return this.write(this.apps, APP_REGISTRY_ABI, "restore", exclusionArgs(app, x));
122
+ }
123
+ write(address, abi, fn, args) {
124
+ return sendWrite(this.publicClient, requireWallet(this.walletClient, fn), address, abi, fn, args);
125
+ }
126
+ /** U's `Updated` events, narrowed on-chain by publisher and repo. */
127
+ source(filter) {
128
+ const ids = filter.repo === void 0 ? {} : { repo_id: repoId(filter.repo) };
129
+ const who = filter.publisher === void 0 ? {} : { publisher: filter.publisher };
130
+ return {
131
+ address: this.data,
132
+ abi: DATA_REGISTRY_ABI,
133
+ eventName: "Updated",
134
+ args: {
135
+ ...who,
136
+ ...ids
137
+ }
138
+ };
139
+ }
140
+ async log(filter, from, to) {
141
+ return (await getLogsInWindows(this.publicClient, from, to, (fromBlock, toBlock) => this.publicClient.getContractEvents({
142
+ ...this.source(filter),
143
+ fromBlock,
144
+ toBlock,
145
+ strict: true
146
+ }), this.logWindow)).sort((a, b) => a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1).map(toEntry);
147
+ }
148
+ watch(filter, onEntry, onError, pollingInterval) {
149
+ return this.publicClient.watchContractEvent({
150
+ ...this.source(filter),
151
+ strict: true,
152
+ pollingInterval,
153
+ onLogs: (logs) => {
154
+ for (const log of logs) onEntry(toEntry(log));
155
+ },
156
+ onError
157
+ });
158
+ }
159
+ clock() {
160
+ return this.publicClient.getBlockNumber({ cacheTime: 0 });
161
+ }
162
+ };
163
+ function exclusionArgs(app, x) {
164
+ return [
165
+ app,
166
+ x.publisher,
167
+ x.repo === void 0 ? ZERO : repoId(x.repo),
168
+ x.key === void 0 ? ZERO : repoId(x.key)
169
+ ];
170
+ }
171
+ function toEntry(log) {
172
+ return {
173
+ publisher: log.args.publisher,
174
+ repo: log.args.repo,
175
+ pos: Number(log.args.pos),
176
+ parent: log.args.parent,
177
+ head: log.args.head,
178
+ t: log.blockNumber,
179
+ id: `${log.transactionHash}:${log.logIndex.toString()}`
180
+ };
181
+ }
182
+
183
+ //#endregion
184
+ export { ChainRegistry, EPOCH_SECONDS, ZERO_HEAD, covers, epochOf, exclusionId, repoExcluded };
@@ -1,12 +1,9 @@
1
1
  import { PreparedTx } from "../contracts/write.js";
2
- import { CommitUpdate, LogFilter, Registry, RepoRef, UpdateEntry } from "../contracts/data-registry/index.js";
3
2
  import "../contracts/index.js";
4
- import { Address, Hash, Hex, LocalAccount } from "viem";
5
- import * as abitype31 from "abitype";
3
+ import { Exclusion, LogFilter, Registry, RepoRef, UpdateEntry } from "../registry.js";
4
+ import { Address, Hash, Hex } from "viem";
6
5
 
7
6
  //#region src/test/mem-registry.d.ts
8
- /** The EIP-712 domain a MemRegistry signs under. */
9
- declare const MEM_DOMAIN: abitype31.TypedDataDomain;
10
7
  /** One ordering and the registry state over it, shared by every signer of a MemRegistry. */
11
8
  declare class MemLedger {
12
9
  /** H: position and head */
@@ -14,6 +11,10 @@ declare class MemLedger {
14
11
  pos: number;
15
12
  head: Hex;
16
13
  }>;
14
+ /** `app/publisher` for each publisher an app presents (provides storage to) */
15
+ members: Set<string>;
16
+ /** C, per app */
17
+ counts: Map<string, number>;
17
18
  /** U */
18
19
  entries: UpdateEntry[];
19
20
  /** The clock: one tick per entry of the ordering. */
@@ -22,25 +23,29 @@ declare class MemLedger {
22
23
  append(entry: Omit<UpdateEntry, "t" | "id">): void;
23
24
  }
24
25
  /**
25
- * The paper's Apply, signing as `signer`. Signers that share a ledger see each
26
- * other's writes, like wallets on one chain.
26
+ * The paper's Apply, signing as `signer`. Membership is whatever the ledger is
27
+ * told (`members`): its rules (invites, terms, suspensions) are the contracts'
28
+ * business. Signers that share a ledger see each other's writes, like wallets on
29
+ * one chain.
27
30
  */
28
31
  declare class MemRegistry implements Registry {
29
32
  signer: Address;
30
33
  ledger: MemLedger;
31
34
  now: () => number;
32
- account?: LocalAccount | undefined;
33
- constructor(signer: Address, ledger?: MemLedger, now?: () => number, account?: LocalAccount | undefined);
35
+ constructor(signer: Address, ledger?: MemLedger, now?: () => number);
34
36
  epoch(): Promise<number>;
35
37
  head(ref: RepoRef): Promise<Hex>;
36
- update(u: CommitUpdate): Promise<Hash>;
37
- signUpdate(u: CommitUpdate): Promise<Hex>;
38
- updateBySig(publisher: Address, u: CommitUpdate, signature: Hex): Promise<Hash>;
39
- private apply;
38
+ presents(app: Hex, publisher: Address): Promise<boolean>;
39
+ exclusionCount(app: Hex, x: Exclusion): Promise<number>;
40
+ update(repo: string, parent: Hex, head: Hex): Promise<Hash>;
40
41
  prepareUpdate(): Promise<PreparedTx>;
42
+ exclude(app: Hex, x: Exclusion): Promise<Hash>;
43
+ restore(app: Hex, x: Exclusion): Promise<Hash>;
44
+ /** exclude needs an even count, restore an odd one; both add one. */
45
+ private flip;
41
46
  log(filter: LogFilter, from: bigint, to?: bigint): Promise<UpdateEntry[]>;
42
47
  watch(filter: LogFilter, onEntry: (entry: UpdateEntry) => void): () => void;
43
48
  clock(): Promise<bigint>;
44
49
  }
45
50
  //#endregion
46
- export { MEM_DOMAIN, MemLedger, MemRegistry };
51
+ export { MemLedger, MemRegistry };
@@ -1,16 +1,16 @@
1
- import { UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, updateMessage } from "../contracts/data-registry/index.js";
2
- import "../contracts/index.js";
3
- import { commitHead } from "../engine/index.js";
4
- import { verifyTypedData } from "viem";
1
+ import { ZERO_HEAD, epochOf } from "../registry.js";
5
2
 
6
3
  //#region src/test/mem-registry.ts
7
- /** The EIP-712 domain a MemRegistry signs under. */
8
- const MEM_DOMAIN = dataDomain(31337, "0x000000000000000000000000000000000000da7a");
9
4
  const refKey = (r) => `${r.publisher.toLowerCase()}/${r.repo}`;
5
+ const exclKey = (x) => `${x.publisher.toLowerCase()}/${x.repo ?? ""}/${x.key ?? ""}`;
10
6
  /** One ordering and the registry state over it, shared by every signer of a MemRegistry. */
11
7
  var MemLedger = class {
12
8
  /** H: position and head */
13
9
  heads = /* @__PURE__ */ new Map();
10
+ /** `app/publisher` for each publisher an app presents (provides storage to) */
11
+ members = /* @__PURE__ */ new Set();
12
+ /** C, per app */
13
+ counts = /* @__PURE__ */ new Map();
14
14
  /** U */
15
15
  entries = [];
16
16
  /** The clock: one tick per entry of the ordering. */
@@ -29,15 +29,16 @@ var MemLedger = class {
29
29
  };
30
30
  const matches = (filter, e) => (!filter.publisher || e.publisher.toLowerCase() === filter.publisher.toLowerCase()) && (!filter.repo || e.repo === filter.repo);
31
31
  /**
32
- * The paper's Apply, signing as `signer`. Signers that share a ledger see each
33
- * other's writes, like wallets on one chain.
32
+ * The paper's Apply, signing as `signer`. Membership is whatever the ledger is
33
+ * told (`members`): its rules (invites, terms, suspensions) are the contracts'
34
+ * business. Signers that share a ledger see each other's writes, like wallets on
35
+ * one chain.
34
36
  */
35
37
  var MemRegistry = class {
36
- constructor(signer, ledger = new MemLedger(), now = () => Math.floor(Date.now() / 1e3), account) {
38
+ constructor(signer, ledger = new MemLedger(), now = () => Math.floor(Date.now() / 1e3)) {
37
39
  this.signer = signer;
38
40
  this.ledger = ledger;
39
41
  this.now = now;
40
- this.account = account;
41
42
  }
42
43
  epoch() {
43
44
  return Promise.resolve(epochOf(this.now()));
@@ -45,56 +46,48 @@ var MemRegistry = class {
45
46
  head(ref) {
46
47
  return Promise.resolve(this.ledger.heads.get(refKey(ref))?.head ?? ZERO_HEAD);
47
48
  }
48
- update(u) {
49
- return this.apply(this.signer, u);
49
+ presents(app, publisher) {
50
+ return Promise.resolve(this.ledger.members.has(`${app}/${publisher.toLowerCase()}`));
50
51
  }
51
- signUpdate(u) {
52
- if (!this.account) return Promise.reject(/* @__PURE__ */ new Error("MemRegistry has no account to sign with"));
53
- return this.account.signTypedData({
54
- domain: MEM_DOMAIN,
55
- types: UPDATE_TYPES,
56
- primaryType: "Update",
57
- message: updateMessage(this.account.address, u)
58
- });
59
- }
60
- async updateBySig(publisher, u, signature) {
61
- if (!await verifyTypedData({
62
- address: publisher,
63
- domain: MEM_DOMAIN,
64
- types: UPDATE_TYPES,
65
- primaryType: "Update",
66
- message: updateMessage(publisher, u),
67
- signature
68
- })) throw new Error("BadSignature");
69
- return this.apply(publisher, u);
52
+ exclusionCount(app, x) {
53
+ return Promise.resolve(this.ledger.counts.get(`${app}/${exclKey(x)}`) ?? 0);
70
54
  }
71
- async apply(publisher, u) {
72
- const now = epochOf(this.now());
73
- if (u.epoch > now || u.epoch + WINDOW < now) throw new Error("EpochOutOfWindow");
55
+ async update(repo, parent, head) {
74
56
  const ref = {
75
- publisher,
76
- repo: u.repo
57
+ publisher: this.signer,
58
+ repo
77
59
  };
78
- if (await this.head(ref) !== u.parent) throw new Error("StaleStateRoot");
79
- const head = await commitHead(u);
60
+ if (await this.head(ref) !== parent) throw new Error("StaleStateRoot");
80
61
  const pos = (this.ledger.heads.get(refKey(ref))?.pos ?? 0) + 1;
81
62
  this.ledger.heads.set(refKey(ref), {
82
63
  pos,
83
64
  head
84
65
  });
85
66
  this.ledger.append({
86
- publisher,
87
- repo: u.repo,
67
+ publisher: this.signer,
68
+ repo,
88
69
  pos,
89
- parent: u.parent,
90
- head,
91
- timestamp: BigInt(this.now())
70
+ parent,
71
+ head
92
72
  });
93
73
  return "0x00";
94
74
  }
95
75
  prepareUpdate() {
96
76
  return Promise.reject(/* @__PURE__ */ new Error("MemRegistry has no transactions to prepare"));
97
77
  }
78
+ exclude(app, x) {
79
+ return this.flip(app, x, 0);
80
+ }
81
+ restore(app, x) {
82
+ return this.flip(app, x, 1);
83
+ }
84
+ /** exclude needs an even count, restore an odd one; both add one. */
85
+ async flip(app, x, parity) {
86
+ const n = await this.exclusionCount(app, x);
87
+ if (n % 2 !== parity) throw new Error(parity ? "NotExcluded" : "AlreadyExcluded");
88
+ this.ledger.counts.set(`${app}/${exclKey(x)}`, n + 1);
89
+ return "0x00";
90
+ }
98
91
  log(filter, from, to) {
99
92
  return Promise.resolve(this.ledger.entries.filter((e) => e.t >= from && (to === void 0 || e.t <= to) && matches(filter, e)));
100
93
  }
@@ -111,4 +104,4 @@ var MemRegistry = class {
111
104
  };
112
105
 
113
106
  //#endregion
114
- export { MEM_DOMAIN, MemLedger, MemRegistry };
107
+ export { MemLedger, MemRegistry };
@@ -1,10 +1,13 @@
1
1
  import { Fangorn, RepoChange } from "../fangorn.js";
2
2
  import { Network } from "./testbed.js";
3
+ import { Hex } from "viem";
3
4
 
4
5
  //#region src/test/sdk-suite.d.ts
6
+ /** The app a test client was made under. */
7
+ declare function appOf(f: Fangorn): Hex;
5
8
  declare const head: (f: Fangorn, repo: string) => Promise<`0x${string}`>;
6
9
  /** Take the first n entries of the stream and then stop. */
7
10
  declare function take(stream: AsyncGenerator<RepoChange>, n: number): Promise<RepoChange[]>;
8
11
  declare function sdkSuite(makeNetwork: () => Promise<Network>, timeout?: number): void;
9
12
  //#endregion
10
- export { head, sdkSuite, take };
13
+ export { appOf, head, sdkSuite, take };
@@ -1,12 +1,18 @@
1
- import { ZERO_HEAD } from "../contracts/data-registry/index.js";
2
- import "../contracts/index.js";
1
+ import { ZERO_HEAD } from "../registry.js";
3
2
  import { GADGET_SELF_HKDF_V1, sealSelf, unsealSelf } from "../crypto/encryption.js";
4
- import { afterAll, beforeAll, describe, it } from "../node_modules/@vitest/runner/dist/index.js";
5
- import { globalExpect } from "../node_modules/vitest/dist/chunks/vi.2VT5v0um.js";
3
+ import { afterAll, beforeAll, describe, it } from "../node_modules/.pnpm/@vitest_runner@4.0.18/node_modules/@vitest/runner/dist/index.js";
4
+ import { globalExpect } from "../node_modules/.pnpm/vitest@4.0.18_@types_node@24.10.1_jiti@2.6.1_terser@5.51.2_tsx@4.21.0_yaml@2.8.2/node_modules/vitest/dist/chunks/vi.2VT5v0um.js";
5
+ import { TEST_APP } from "./testbed.js";
6
6
  import { bytesToHex, hexToBytes, keccak256, stringToBytes } from "viem";
7
7
  import { generatePrivateKey } from "viem/accounts";
8
8
 
9
9
  //#region src/test/sdk-suite.ts
10
+ /** The app a test client was made under. */
11
+ function appOf(f) {
12
+ const app = f.getAppId();
13
+ if (!app) throw new Error("this client has no app");
14
+ return app;
15
+ }
10
16
  const head = (f, repo) => f.getRegistry().head({
11
17
  publisher: f.getAddress(),
12
18
  repo
@@ -20,6 +26,8 @@ async function take(stream, n) {
20
26
  }
21
27
  return out;
22
28
  }
29
+ /** A fresh app name, so a test's owner and exclusions are its own. */
30
+ const freshApp = () => `app-${Math.random().toString(36).slice(2)}`;
23
31
  function sdkSuite(makeNetwork, timeout = 5e3) {
24
32
  let net;
25
33
  beforeAll(async () => {
@@ -71,7 +79,7 @@ function sdkSuite(makeNetwork, timeout = 5e3) {
71
79
  }, timeout);
72
80
  it("stores a payload sealed to its publisher as opaque bytes", async () => {
73
81
  const sk = generatePrivateKey();
74
- const f = await net.client(sk);
82
+ const f = await net.client(TEST_APP, sk);
75
83
  await f.initRepo("private");
76
84
  const resourceId = keccak256(stringToBytes("private:secret"));
77
85
  const ciphertext = sealSelf(new TextEncoder().encode("the eagles are coming"), hexToBytes(sk), resourceId);
@@ -103,31 +111,94 @@ function sdkSuite(makeNetwork, timeout = 5e3) {
103
111
  id: "x",
104
112
  type: "t",
105
113
  payload: {}
106
- }]
114
+ }],
115
+ message: "m"
107
116
  });
108
117
  await globalExpect(f.push("r", stale.commitCid)).rejects.toThrow(/stale parent/);
109
118
  }, timeout);
110
119
  });
111
- describe("reading other publishers", () => {
112
- it("any client reads any publisher's repo, and lists every repo", async () => {
113
- const reader = await net.client();
114
- const pub = await net.client();
115
- await pub.initRepo("catalog");
116
- const { payloadCid } = await pub.upload("catalog", { title: "t" }, "entry", "g");
117
- const { contents } = await reader.readRepo(pub.getAddress(), "catalog");
120
+ describe("apps present what they accept", () => {
121
+ it("one member reads another's repo, and the app lists both", async () => {
122
+ const app = freshApp();
123
+ const owner = await net.client(app);
124
+ const guest = await net.client(app);
125
+ await owner.initRepo("catalog");
126
+ await guest.initRepo("catalog");
127
+ const { payloadCid } = await guest.upload("catalog", { title: "from the guest" }, "entry", "g");
128
+ const { contents } = await owner.readRepo(guest.getAddress(), "catalog");
118
129
  globalExpect(contents.records.map((r) => r.cid)).toEqual([payloadCid]);
119
- globalExpect((await reader.repos({ owner: pub.getAddress() })).map((d) => [d.owner, d.repo])).toEqual([[pub.getAddress(), "catalog"]]);
130
+ const listed = await owner.appRepos({ repo: "catalog" });
131
+ globalExpect(listed.map((d) => d.owner).sort()).toEqual([owner.getAddress(), guest.getAddress()].sort());
132
+ globalExpect(listed.every((d) => d.repo === "catalog")).toBe(true);
133
+ }, timeout);
134
+ it("an app presents its members' repos and nobody else's; an update names no app", async () => {
135
+ const app = freshApp();
136
+ const owner = await net.client(app);
137
+ const loner = await net.client(null);
138
+ await loner.initRepo("notes");
139
+ await loner.upload("notes", { n: 1 }, "t", "x");
140
+ globalExpect((await owner.readRepo(loner.getAddress(), "notes")).contents.records).toEqual([]);
141
+ globalExpect(await owner.appRepos()).toEqual([]);
142
+ globalExpect((await (await net.client(null)).readRepo(loner.getAddress(), "notes")).contents.records).toHaveLength(1);
143
+ }, timeout);
144
+ it("an excluded publisher disappears from the app's reads, and a restore brings it back", async () => {
145
+ const app = freshApp();
146
+ const owner = await net.client(app);
147
+ const guest = await net.client(app);
148
+ await guest.initRepo("catalog");
149
+ await guest.upload("catalog", { title: "t" }, "entry", "g");
150
+ const x = { publisher: guest.getAddress() };
151
+ const appId = appOf(owner);
152
+ await owner.getRegistry().exclude(appId, x);
153
+ globalExpect(await owner.appRepos()).toEqual([]);
154
+ globalExpect((await owner.readRepo(guest.getAddress(), "catalog")).contents.records).toEqual([]);
155
+ await owner.getRegistry().restore(appId, x);
156
+ globalExpect(await owner.appRepos()).toHaveLength(1);
157
+ globalExpect((await owner.readRepo(guest.getAddress(), "catalog")).contents.records).toHaveLength(1);
158
+ }, timeout);
159
+ it("a repo exclusion hides that repo only", async () => {
160
+ const app = freshApp();
161
+ const owner = await net.client(app);
162
+ const guest = await net.client(app);
163
+ for (const repo of ["keep", "drop"]) {
164
+ await guest.initRepo(repo);
165
+ await guest.upload(repo, { repo }, "t", "x");
166
+ }
167
+ await owner.getRegistry().exclude(appOf(owner), {
168
+ publisher: guest.getAddress(),
169
+ repo: "drop"
170
+ });
171
+ globalExpect((await owner.appRepos()).map((d) => d.repo)).toEqual(["keep"]);
172
+ globalExpect((await owner.readRepo(guest.getAddress(), "drop")).contents.records).toEqual([]);
173
+ globalExpect((await owner.readRepo(guest.getAddress(), "keep")).contents.records).toHaveLength(1);
174
+ }, timeout);
175
+ it("an exclusion in one app hides nothing in another that presents the same publisher", async () => {
176
+ const [appA, appB] = [freshApp(), freshApp()];
177
+ const ownerA = await net.client(appA);
178
+ const ownerB = await net.client(appB);
179
+ const sk = generatePrivateKey();
180
+ const guest = await net.client(appA, sk);
181
+ await net.client(appB, sk);
182
+ await guest.initRepo("catalog");
183
+ await guest.upload("catalog", { title: "t" }, "entry", "g");
184
+ const ref = {
185
+ publisher: guest.getAddress(),
186
+ repo: "catalog"
187
+ };
188
+ await ownerA.getRegistry().exclude(appOf(ownerA), { publisher: ref.publisher });
189
+ globalExpect((await ownerA.readRepo(ref.publisher, "catalog")).contents.records).toEqual([]);
190
+ globalExpect((await ownerB.readRepo(ref.publisher, "catalog")).contents.records).toHaveLength(1);
120
191
  }, timeout);
121
192
  });
122
193
  describe("subscriptions", () => {
123
194
  it("replays from a block, then follows live", async () => {
124
- const pub = await net.client();
195
+ const app = freshApp();
196
+ const pub = await net.client(app);
125
197
  const from = await net.clock();
126
198
  await pub.initRepo("feed");
127
199
  await pub.upload("feed", { n: 1 }, "t", "a");
128
200
  const ctl = new AbortController();
129
- const stream = (await net.client()).subscribeAll({
130
- owner: pub.getAddress(),
201
+ const stream = (await net.client(app)).subscribeApp({
131
202
  fromBlock: from,
132
203
  signal: ctl.signal,
133
204
  pollingInterval: 100
@@ -152,4 +223,4 @@ function sdkSuite(makeNetwork, timeout = 5e3) {
152
223
  }
153
224
 
154
225
  //#endregion
155
- export { head, sdkSuite, take };
226
+ export { appOf, head, sdkSuite, take };