@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
@@ -1,79 +0,0 @@
1
- import { Address, Hash, Hex, PublicClient, WalletClient } from "viem";
2
-
3
- //#region src/contracts/membership-registry/index.d.ts
4
- /** A signed ERC-3009 `receiveWithAuthorization` paying the registry, as `join` takes it. */
5
- interface MembershipPayment {
6
- from: Address;
7
- value: bigint;
8
- validAfter: bigint;
9
- validBefore: bigint;
10
- nonce: Hex;
11
- v: number;
12
- r: Hex;
13
- s: Hex;
14
- }
15
- /** What `join` needs besides the payment: the app, the commitment, the salt in the nonce. */
16
- interface JoinArgs {
17
- appId: Hex;
18
- commitment: bigint;
19
- salt: Hex;
20
- payment: MembershipPayment;
21
- }
22
- /** What `claim` needs: a Semaphore proof over the (app, epoch) group, message = holder. */
23
- interface ClaimArgs {
24
- appId: Hex;
25
- epoch: bigint;
26
- holder: Address;
27
- merkleTreeDepth: bigint;
28
- merkleTreeRoot: bigint;
29
- nullifier: bigint;
30
- points: readonly [bigint, bigint, bigint, bigint, bigint, bigint, bigint, bigint];
31
- }
32
- /** The nonce a payer signs for `join`, the same derivation as the contract's `joinNonce`. */
33
- declare const joinNonce: (appId: Hex, epoch: bigint, commitment: bigint, salt: Hex) => Hex;
34
- /** The Semaphore scope of (app, epoch), as the contract fixes it in `claim`. */
35
- declare const membershipScope: (appId: Hex, epoch: bigint) => bigint;
36
- /** A holder's membership token id in an app. */
37
- declare const membershipTokenId: (appId: Hex, holder: Address) => bigint;
38
- /**
39
- * Client for the MembershipRegistry.
40
- *
41
- * The app owner's half is here (`setPlan`), with the reads every gate needs
42
- * (`canRead`, `planOf`, `currentEpoch`) and the two relayed writes (`join`, `claim`),
43
- * which take what a buyer signed and proved, so anyone may submit them.
44
- *
45
- * The buyer's half (Semaphore identity, stealth holder, the payment signature, the
46
- * group from `Joined` logs, the proof) lives in `@fangorn-network/fetch`: this SDK
47
- * carries no Semaphore proving dependency.
48
- */
49
- declare class MembershipRegistryClient {
50
- private contractAddress;
51
- private publicClient;
52
- private walletClient?;
53
- constructor(contractAddress: Address, publicClient: PublicClient, walletClient?: WalletClient | undefined);
54
- getAddress(): Address;
55
- private write;
56
- private read;
57
- /** Price (USDC base units) and period (seconds) of a membership in `appId`. App owner only. */
58
- setPlan(appId: Hex, price: bigint, period: bigint): Promise<Hash>;
59
- join({
60
- appId,
61
- commitment,
62
- salt,
63
- payment
64
- }: JoinArgs): Promise<Hash>;
65
- claim(a: ClaimArgs): Promise<Hash>;
66
- planOf(appId: Hex): Promise<{
67
- price: bigint;
68
- period: bigint;
69
- }>;
70
- currentEpoch(appId: Hex): Promise<bigint>;
71
- /** What `who` may read with `tokenId`: the app, and until when (seconds; 0 = nothing). */
72
- canRead(tokenId: bigint, who: Address): Promise<{
73
- appId: Hex;
74
- until: bigint;
75
- }>;
76
- expiresAt(tokenId: bigint): Promise<bigint>;
77
- }
78
- //#endregion
79
- export { ClaimArgs, JoinArgs, MembershipPayment, MembershipRegistryClient, joinNonce, membershipScope, membershipTokenId };
@@ -1,104 +0,0 @@
1
- import { requireWallet, sendWrite } from "../write.js";
2
- import { MEMBERSHIP_REGISTRY_ABI } from "./abi.js";
3
- import { encodeAbiParameters, keccak256 } from "viem";
4
-
5
- //#region src/contracts/membership-registry/index.ts
6
- /** The nonce a payer signs for `join`, the same derivation as the contract's `joinNonce`. */
7
- const joinNonce = (appId, epoch, commitment, salt) => keccak256(encodeAbiParameters([
8
- { type: "bytes32" },
9
- { type: "uint256" },
10
- { type: "uint256" },
11
- { type: "bytes32" }
12
- ], [
13
- appId,
14
- epoch,
15
- commitment,
16
- salt
17
- ]));
18
- /** The Semaphore scope of (app, epoch), as the contract fixes it in `claim`. */
19
- const membershipScope = (appId, epoch) => BigInt(keccak256(encodeAbiParameters([{ type: "bytes32" }, { type: "uint256" }], [appId, epoch])));
20
- /** A holder's membership token id in an app. */
21
- const membershipTokenId = (appId, holder) => BigInt(keccak256(encodeAbiParameters([{ type: "bytes32" }, { type: "address" }], [appId, holder])));
22
- /**
23
- * Client for the MembershipRegistry.
24
- *
25
- * The app owner's half is here (`setPlan`), with the reads every gate needs
26
- * (`canRead`, `planOf`, `currentEpoch`) and the two relayed writes (`join`, `claim`),
27
- * which take what a buyer signed and proved, so anyone may submit them.
28
- *
29
- * The buyer's half (Semaphore identity, stealth holder, the payment signature, the
30
- * group from `Joined` logs, the proof) lives in `@fangorn-network/fetch`: this SDK
31
- * carries no Semaphore proving dependency.
32
- */
33
- var MembershipRegistryClient = class {
34
- constructor(contractAddress, publicClient, walletClient) {
35
- this.contractAddress = contractAddress;
36
- this.publicClient = publicClient;
37
- this.walletClient = walletClient;
38
- }
39
- getAddress() {
40
- return this.contractAddress;
41
- }
42
- write(functionName, args) {
43
- return sendWrite(this.publicClient, requireWallet(this.walletClient, functionName), this.contractAddress, MEMBERSHIP_REGISTRY_ABI, functionName, args);
44
- }
45
- read(functionName, args = []) {
46
- return this.publicClient.readContract({
47
- address: this.contractAddress,
48
- abi: MEMBERSHIP_REGISTRY_ABI,
49
- functionName,
50
- args
51
- });
52
- }
53
- /** Price (USDC base units) and period (seconds) of a membership in `appId`. App owner only. */
54
- setPlan(appId, price, period) {
55
- return this.write("setPlan", [
56
- appId,
57
- price,
58
- period
59
- ]);
60
- }
61
- join({ appId, commitment, salt, payment }) {
62
- return this.write("join", [
63
- appId,
64
- commitment,
65
- salt,
66
- payment
67
- ]);
68
- }
69
- claim(a) {
70
- return this.write("claim", [
71
- a.appId,
72
- a.epoch,
73
- a.holder,
74
- a.merkleTreeDepth,
75
- a.merkleTreeRoot,
76
- a.nullifier,
77
- a.points
78
- ]);
79
- }
80
- async planOf(appId) {
81
- const [price, period] = await this.read("planOf", [appId]);
82
- return {
83
- price,
84
- period
85
- };
86
- }
87
- currentEpoch(appId) {
88
- return this.read("currentEpoch", [appId]);
89
- }
90
- /** What `who` may read with `tokenId`: the app, and until when (seconds; 0 = nothing). */
91
- async canRead(tokenId, who) {
92
- const [appId, until] = await this.read("canRead", [tokenId, who]);
93
- return {
94
- appId,
95
- until
96
- };
97
- }
98
- expiresAt(tokenId) {
99
- return this.read("expiresAt", [tokenId]);
100
- }
101
- };
102
-
103
- //#endregion
104
- export { MembershipRegistryClient, joinNonce, membershipScope, membershipTokenId };
@@ -1,10 +0,0 @@
1
- //#region src/contracts/types.d.ts
2
- declare enum PublisherStatus {
3
- NONE = 0,
4
- ACTIVE = 1,
5
- SUSPENDED = 2,
6
- /** Retired: invited under the old join flow and never joined. Not a member. */
7
- INVITED = 3,
8
- }
9
- //#endregion
10
- export { PublisherStatus };
@@ -1,12 +0,0 @@
1
- //#region src/contracts/types.ts
2
- let PublisherStatus = /* @__PURE__ */ function(PublisherStatus$1) {
3
- PublisherStatus$1[PublisherStatus$1["NONE"] = 0] = "NONE";
4
- PublisherStatus$1[PublisherStatus$1["ACTIVE"] = 1] = "ACTIVE";
5
- PublisherStatus$1[PublisherStatus$1["SUSPENDED"] = 2] = "SUSPENDED";
6
- /** Retired: invited under the old join flow and never joined. Not a member. */
7
- PublisherStatus$1[PublisherStatus$1["INVITED"] = 3] = "INVITED";
8
- return PublisherStatus$1;
9
- }({});
10
-
11
- //#endregion
12
- export { PublisherStatus };
@@ -1 +0,0 @@
1
- export { };
@@ -1,17 +0,0 @@
1
- import { buildAssetGraph, extractMarkdownLinks } from "../../index.js";
2
-
3
- //#region src/harness/examples/hackmd/build-markdown-graph.ts
4
- const buildMarkdownGraph = (dir) => {
5
- return buildAssetGraph(dir, { processors: { ".md": (file) => ({
6
- tag: "doc",
7
- payload: { content: file.readText() },
8
- links: extractMarkdownLinks(file.readText())
9
- }) } });
10
- };
11
- if (import.meta.url === `file://${process.argv[1]}`) {
12
- const dir = process.argv[2] ?? ".";
13
- process.stdout.write(JSON.stringify(buildMarkdownGraph(dir), null, 2) + "\n");
14
- }
15
-
16
- //#endregion
17
- export { };
@@ -1,58 +0,0 @@
1
- import { Stats } from "fs";
2
-
3
- //#region src/harness/index.d.ts
4
- interface FileFacade {
5
- /** The full filename including extension (e.g., "notes.md") */
6
- name: string;
7
- /** The filename without extension, used as the default ID (e.g., "notes") */
8
- nameNoExt: string;
9
- /** The file extension in lowercase, including the dot (e.g., ".md") */
10
- ext: string;
11
- /** The absolute or relative path to the file */
12
- path: string;
13
- /** Reads the file and returns its content as a UTF-8 string */
14
- readText: () => string;
15
- /** Reads the file and returns its raw Buffer data */
16
- readBuffer: () => Buffer;
17
- /** Retrieves file system metadata stats for the file */
18
- stat: () => Stats;
19
- }
20
- interface ProcessorResult {
21
- /** The entity type/tag for the graph vertex (defaults to "asset") */
22
- tag?: string;
23
- /** Custom metadata object attached to the vertex */
24
- payload?: Record<string, unknown>;
25
- /** An array of target vertex IDs that this file links to */
26
- links?: string[];
27
- }
28
- type AssetProcessor = (file: FileFacade) => ProcessorResult;
29
- interface BuildAssetGraphOptions {
30
- /** A dictionary mapping lowercase file extensions (e.g., ".md") to processor functions */
31
- processors?: Record<string, AssetProcessor>;
32
- }
33
- interface Vertex {
34
- id: string;
35
- tag: string;
36
- payload: Record<string, unknown>;
37
- }
38
- interface Edge {
39
- rel: string;
40
- from: string;
41
- to: string;
42
- }
43
- interface CommitFileGraph {
44
- vertices: Vertex[];
45
- edges: Edge[];
46
- }
47
- /**
48
- * Traverses a directory, parses files based on their extensions,
49
- * and generates a strictly validated Fangorn-compliant commit graph.
50
- */
51
- declare function buildAssetGraph(dir: string, options?: BuildAssetGraphOptions): CommitFileGraph;
52
- /**
53
- * Utility helper to scan markdown strings for standard markdown links or wikilinks.
54
- */
55
- declare function extractMarkdownLinks(content: string): string[];
56
- declare const buildMarkdownGraph: (dir: string) => CommitFileGraph;
57
- //#endregion
58
- export { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks };
@@ -1,73 +0,0 @@
1
- import { readFileSync, readdirSync, statSync } from "fs";
2
- import { basename, extname, join } from "path";
3
-
4
- //#region src/harness/index.ts
5
- /**
6
- * Traverses a directory, parses files based on their extensions,
7
- * and generates a strictly validated Fangorn-compliant commit graph.
8
- */
9
- function buildAssetGraph(dir, options = {}) {
10
- const { processors = {} } = options;
11
- const rawFiles = readdirSync(dir);
12
- const getId = (f) => basename(f, extname(f));
13
- const validIds = new Set(rawFiles.map(getId));
14
- const vertices = [];
15
- const edges = /* @__PURE__ */ new Set();
16
- for (const f of rawFiles) {
17
- const ext = extname(f).toLowerCase();
18
- const processor = processors[ext];
19
- const fromId = getId(f);
20
- const fullPath = join(dir, f);
21
- const fileFacade = {
22
- name: f,
23
- nameNoExt: fromId,
24
- ext,
25
- path: fullPath,
26
- readText: () => readFileSync(fullPath, "utf-8"),
27
- readBuffer: () => readFileSync(fullPath),
28
- stat: () => statSync(fullPath)
29
- };
30
- try {
31
- const { tag = "asset", payload = {}, links = [] } = processor(fileFacade);
32
- vertices.push({
33
- id: fromId,
34
- tag,
35
- payload
36
- });
37
- for (const toId of links) if (toId && fromId !== toId && validIds.has(toId)) edges.add(JSON.stringify({
38
- rel: "links",
39
- from: fromId,
40
- to: toId
41
- }));
42
- } catch (err) {
43
- console.error(`Fangorn Error processing file ${f}:`, err);
44
- }
45
- }
46
- return {
47
- vertices,
48
- edges: Array.from(edges).map((e) => JSON.parse(e))
49
- };
50
- }
51
- /**
52
- * Utility helper to scan markdown strings for standard markdown links or wikilinks.
53
- */
54
- function extractMarkdownLinks(content) {
55
- const LINK_REGEX = /\]\(([^)\s]+?\.md)(?:#[^)]*)?\)|\[\[([^\]|#]+?)(?:[|#][^\]]*)?\]\]/g;
56
- const links = [];
57
- const convertToId = (str) => basename(str, extname(str));
58
- for (const match of content.matchAll(LINK_REGEX)) {
59
- const rawTarget = match[1];
60
- if (rawTarget) links.push(convertToId(rawTarget));
61
- }
62
- return links;
63
- }
64
- const buildMarkdownGraph = (dir) => {
65
- return buildAssetGraph(dir, { processors: { ".md": (file) => ({
66
- tag: "doc",
67
- payload: { content: file.readText() },
68
- links: extractMarkdownLinks(file.readText())
69
- }) } });
70
- };
71
-
72
- //#endregion
73
- export { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks };
package/lib/registry.d.ts DELETED
@@ -1,118 +0,0 @@
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 };
package/lib/registry.js DELETED
@@ -1,184 +0,0 @@
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 };