@fangorn-network/sdk 0.1.0-dev

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/LICENSE.md +20 -0
  2. package/README.md +80 -0
  3. package/lib/cli/cli.d.ts +2 -0
  4. package/lib/cli/cli.js +571 -0
  5. package/lib/cli/index.d.ts +10 -0
  6. package/lib/cli/index.js +18 -0
  7. package/lib/cli/sell.d.ts +28 -0
  8. package/lib/cli/sell.js +95 -0
  9. package/lib/cli/stage.d.ts +19 -0
  10. package/lib/cli/stage.js +94 -0
  11. package/lib/config.d.ts +697 -0
  12. package/lib/config.js +45 -0
  13. package/lib/contracts/data-registry/abi.d.ts +442 -0
  14. package/lib/contracts/data-registry/abi.js +508 -0
  15. package/lib/contracts/data-registry/index.d.ts +131 -0
  16. package/lib/contracts/data-registry/index.js +183 -0
  17. package/lib/contracts/index.d.ts +6 -0
  18. package/lib/contracts/index.js +6 -0
  19. package/lib/contracts/logs.d.ts +17 -0
  20. package/lib/contracts/logs.js +28 -0
  21. package/lib/contracts/settlement-registry/abi.d.ts +810 -0
  22. package/lib/contracts/settlement-registry/abi.js +962 -0
  23. package/lib/contracts/settlement-registry/index.d.ts +143 -0
  24. package/lib/contracts/settlement-registry/index.js +213 -0
  25. package/lib/contracts/write.d.ts +59 -0
  26. package/lib/contracts/write.js +102 -0
  27. package/lib/crypto/aes.d.ts +19 -0
  28. package/lib/crypto/aes.js +26 -0
  29. package/lib/crypto/encryption.d.ts +38 -0
  30. package/lib/crypto/encryption.js +68 -0
  31. package/lib/crypto/paid.d.ts +104 -0
  32. package/lib/crypto/paid.js +147 -0
  33. package/lib/crypto/rand.d.ts +5 -0
  34. package/lib/crypto/rand.js +16 -0
  35. package/lib/crypto/types.d.ts +23 -0
  36. package/lib/crypto/types.js +1 -0
  37. package/lib/engine/car.d.ts +14 -0
  38. package/lib/engine/car.js +42 -0
  39. package/lib/engine/index.d.ts +206 -0
  40. package/lib/engine/index.js +377 -0
  41. package/lib/engine/records.d.ts +121 -0
  42. package/lib/engine/records.js +239 -0
  43. package/lib/engine/test-helpers.d.ts +38 -0
  44. package/lib/engine/test-helpers.js +63 -0
  45. package/lib/erc8004.d.ts +56 -0
  46. package/lib/erc8004.js +140 -0
  47. package/lib/fangorn.d.ts +342 -0
  48. package/lib/fangorn.js +642 -0
  49. package/lib/feed.d.ts +34 -0
  50. package/lib/feed.js +67 -0
  51. package/lib/index.d.ts +17 -0
  52. package/lib/index.js +16 -0
  53. package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
  54. package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
  55. package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
  56. package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
  57. package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
  58. package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
  59. package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
  60. package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
  61. package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
  62. package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
  63. package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
  64. package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
  65. package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
  66. package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
  67. package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
  68. package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
  69. package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
  70. package/lib/node_modules/chai/index.js +2874 -0
  71. package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
  72. package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
  73. package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
  74. package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
  75. package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
  76. package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
  77. package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
  78. package/lib/providers/storage/car.d.ts +36 -0
  79. package/lib/providers/storage/car.js +81 -0
  80. package/lib/providers/storage/index.d.ts +5 -0
  81. package/lib/providers/storage/index.js +5 -0
  82. package/lib/providers/storage/pinata.d.ts +53 -0
  83. package/lib/providers/storage/pinata.js +178 -0
  84. package/lib/providers/storage/signed-url.d.ts +54 -0
  85. package/lib/providers/storage/signed-url.js +122 -0
  86. package/lib/providers/storage/types.d.ts +62 -0
  87. package/lib/providers/storage/types.js +1 -0
  88. package/lib/providers/storage/utils.d.ts +30 -0
  89. package/lib/providers/storage/utils.js +107 -0
  90. package/lib/repo/index.d.ts +56 -0
  91. package/lib/repo/index.js +73 -0
  92. package/lib/test/key-server.d.ts +12 -0
  93. package/lib/test/key-server.js +30 -0
  94. package/lib/test/mem-registry.d.ts +46 -0
  95. package/lib/test/mem-registry.js +114 -0
  96. package/lib/test/sdk-suite.d.ts +10 -0
  97. package/lib/test/sdk-suite.js +155 -0
  98. package/lib/test/testbed.d.ts +16786 -0
  99. package/lib/test/testbed.js +175 -0
  100. package/lib/types/index.d.ts +37 -0
  101. package/lib/types/index.js +1 -0
  102. package/package.json +87 -0
@@ -0,0 +1,104 @@
1
+ import { MetadataStorage } from "../providers/storage/types.js";
2
+ import { AccessSigner } from "./encryption.js";
3
+ import { Address, Hex } from "viem";
4
+
5
+ //#region src/crypto/paid.d.ts
6
+ declare const GADGET_FIELD_V1 = "field-v1";
7
+ /** What a repo key is sealed under. `repo` is `repoId(name)`. */
8
+ interface PaidScope {
9
+ chainId: number;
10
+ registry: Address;
11
+ publisher: Address;
12
+ repo: Hex;
13
+ generation: bigint;
14
+ }
15
+ /** The repo key, sealed to a key server. Public: it goes in the repo as a record. */
16
+ interface Deposit {
17
+ "@type": "deposit";
18
+ gadget: typeof GADGET_FIELD_V1;
19
+ chainId: number;
20
+ registry: Address;
21
+ publisher: Address;
22
+ repo: Hex;
23
+ generation: string;
24
+ keyServer: string;
25
+ sealed: Hex;
26
+ }
27
+ /** A paid field's value in a record payload. */
28
+ interface FieldHandle {
29
+ "@type": "handle";
30
+ gadget: typeof GADGET_FIELD_V1;
31
+ generation: string;
32
+ cid: string;
33
+ }
34
+ /** What a buyer posts to a key server's `/access`. */
35
+ interface AccessRequest {
36
+ publisher: Address;
37
+ repo: Hex;
38
+ generation: string;
39
+ /** `recordKey(id)`, or `WHOLE_REPO` for the repo key */
40
+ key: Hex;
41
+ /** A throwaway X25519 public key; the reply is sealed to it. */
42
+ readerKey: Hex;
43
+ /** The deposit's `sealed`. */
44
+ sealed: Hex;
45
+ timestamp: number;
46
+ signature: Hex;
47
+ }
48
+ declare const statement: (s: PaidScope) => Hex;
49
+ /**
50
+ * A random repo key. The publisher doesn't keep it: to seal more records later,
51
+ * it asks the key server for it (`requestKey` with `WHOLE_REPO`), like a buyer
52
+ * of the whole repo.
53
+ */
54
+ declare const newRepoKey: () => Uint8Array;
55
+ declare const deriveRecordKey: (kRepo: Uint8Array, stmt: Hex, key: Hex) => Uint8Array;
56
+ /** `nonce(12) || AES-256-GCM(kRecord, plaintext, aad = stmt || key || field)` */
57
+ declare function encryptField(kRecord: Uint8Array, plaintext: Uint8Array, stmt: Hex, key: Hex, field: string): Uint8Array;
58
+ declare function decryptField(kRecord: Uint8Array, ciphertext: Uint8Array, stmt: Hex, key: Hex, field: string): Uint8Array;
59
+ declare function makeDeposit(p: {
60
+ kRepo: Uint8Array;
61
+ keyServerPubkey: Uint8Array;
62
+ keyServer: string;
63
+ scope: PaidScope;
64
+ }): Deposit;
65
+ /** Encrypt one field, upload the ciphertext, and return the handle that replaces the value. */
66
+ declare function sealField(p: {
67
+ plaintext: Uint8Array;
68
+ kRepo: Uint8Array;
69
+ scope: PaidScope;
70
+ /** `recordKey(id)` */
71
+ key: Hex;
72
+ field: string;
73
+ storage: Pick<MetadataStorage, "putFile">;
74
+ }): Promise<FieldHandle>;
75
+ /** What the reader signs (EIP-191, raw): the statement, the key asked for, the reply key and the time. */
76
+ declare const accessMessage: (stmt: Hex, key: Hex, readerKey: Hex, timestamp: number) => Hex;
77
+ declare function buildAccessRequest(p: {
78
+ signer: AccessSigner;
79
+ deposit: Deposit;
80
+ key: Hex;
81
+ readerKey: Hex;
82
+ /** unix seconds; defaults to now */
83
+ timestamp?: number;
84
+ }): Promise<AccessRequest>;
85
+ /** Ask the deposit's key server for `key`'s key: the record key, or the repo key for `WHOLE_REPO`. */
86
+ declare function requestKey(p: {
87
+ deposit: Deposit;
88
+ key: Hex;
89
+ signer: AccessSigner;
90
+ fetch?: typeof globalThis.fetch;
91
+ }): Promise<Uint8Array>;
92
+ /** Get the record's key, fetch the field's ciphertext and decrypt it. */
93
+ declare function openField(p: {
94
+ handle: FieldHandle;
95
+ deposit: Deposit;
96
+ /** `recordKey(id)` */
97
+ key: Hex;
98
+ field: string;
99
+ signer: AccessSigner;
100
+ storage: Pick<MetadataStorage, "getFile">;
101
+ fetch?: typeof globalThis.fetch;
102
+ }): Promise<Uint8Array>;
103
+ //#endregion
104
+ export { AccessRequest, Deposit, FieldHandle, GADGET_FIELD_V1, PaidScope, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement };
@@ -0,0 +1,147 @@
1
+ import { GCM_NONCE_LENGTH, aesGcmDecrypt, aesGcmEncrypt } from "./aes.js";
2
+ import { getRandomValues } from "./rand.js";
3
+ import { seal, unseal } from "./encryption.js";
4
+ import { bytesToHex, concat, encodeAbiParameters, hexToBytes, keccak256, toHex } from "viem";
5
+ import { sha256 } from "@noble/hashes/sha2.js";
6
+ import { x25519 } from "@noble/curves/ed25519";
7
+ import { hkdf } from "@noble/hashes/hkdf.js";
8
+
9
+ //#region src/crypto/paid.ts
10
+ const GADGET_FIELD_V1 = "field-v1";
11
+ const hkdf32 = (ikm, info) => hkdf(sha256, ikm, void 0, typeof info === "string" ? hexToBytes(info) : info, 32);
12
+ const statement = (s) => keccak256(encodeAbiParameters([
13
+ { type: "string" },
14
+ { type: "uint256" },
15
+ { type: "address" },
16
+ { type: "address" },
17
+ { type: "bytes32" },
18
+ { type: "uint64" }
19
+ ], [
20
+ "fangorn:pay:v1",
21
+ BigInt(s.chainId),
22
+ s.registry,
23
+ s.publisher,
24
+ s.repo,
25
+ s.generation
26
+ ]));
27
+ const scopeOf = (d) => ({
28
+ chainId: d.chainId,
29
+ registry: d.registry,
30
+ publisher: d.publisher,
31
+ repo: d.repo,
32
+ generation: BigInt(d.generation)
33
+ });
34
+ /**
35
+ * A random repo key. The publisher doesn't keep it: to seal more records later,
36
+ * it asks the key server for it (`requestKey` with `WHOLE_REPO`), like a buyer
37
+ * of the whole repo.
38
+ */
39
+ const newRepoKey = () => getRandomValues(new Uint8Array(32));
40
+ const deriveRecordKey = (kRepo, stmt, key) => hkdf32(kRepo, concat([
41
+ stmt,
42
+ key,
43
+ toHex("fangorn:record-key")
44
+ ]));
45
+ const fieldAad = (stmt, key, field) => hexToBytes(concat([
46
+ stmt,
47
+ key,
48
+ toHex(field)
49
+ ]));
50
+ /** `nonce(12) || AES-256-GCM(kRecord, plaintext, aad = stmt || key || field)` */
51
+ function encryptField(kRecord, plaintext, stmt, key, field) {
52
+ const nonce = getRandomValues(new Uint8Array(GCM_NONCE_LENGTH));
53
+ const ct = aesGcmEncrypt(kRecord, plaintext, nonce, fieldAad(stmt, key, field));
54
+ const out = new Uint8Array(nonce.length + ct.length);
55
+ out.set(nonce);
56
+ out.set(ct, nonce.length);
57
+ return out;
58
+ }
59
+ function decryptField(kRecord, ciphertext, stmt, key, field) {
60
+ return aesGcmDecrypt(kRecord, ciphertext.slice(GCM_NONCE_LENGTH), ciphertext.slice(0, GCM_NONCE_LENGTH), fieldAad(stmt, key, field));
61
+ }
62
+ function makeDeposit(p) {
63
+ const { scope } = p;
64
+ return {
65
+ "@type": "deposit",
66
+ gadget: GADGET_FIELD_V1,
67
+ chainId: scope.chainId,
68
+ registry: scope.registry,
69
+ publisher: scope.publisher,
70
+ repo: scope.repo,
71
+ generation: scope.generation.toString(),
72
+ keyServer: p.keyServer,
73
+ sealed: bytesToHex(seal(p.kRepo, p.keyServerPubkey, statement(scope)))
74
+ };
75
+ }
76
+ /** Encrypt one field, upload the ciphertext, and return the handle that replaces the value. */
77
+ async function sealField(p) {
78
+ const stmt = statement(p.scope);
79
+ const ct = encryptField(deriveRecordKey(p.kRepo, stmt, p.key), p.plaintext, stmt, p.key, p.field);
80
+ return {
81
+ "@type": "handle",
82
+ gadget: GADGET_FIELD_V1,
83
+ generation: p.scope.generation.toString(),
84
+ cid: await p.storage.putFile(ct, `${p.key}.${p.field}`)
85
+ };
86
+ }
87
+ /** What the reader signs (EIP-191, raw): the statement, the key asked for, the reply key and the time. */
88
+ const accessMessage = (stmt, key, readerKey, timestamp) => keccak256(encodeAbiParameters([
89
+ { type: "string" },
90
+ { type: "bytes32" },
91
+ { type: "bytes32" },
92
+ { type: "bytes32" },
93
+ { type: "uint64" }
94
+ ], [
95
+ "fangorn:access:v1",
96
+ stmt,
97
+ key,
98
+ readerKey,
99
+ BigInt(timestamp)
100
+ ]));
101
+ async function buildAccessRequest(p) {
102
+ const { deposit, key, readerKey } = p;
103
+ const timestamp = p.timestamp ?? Math.floor(Date.now() / 1e3);
104
+ const raw = accessMessage(statement(scopeOf(deposit)), key, readerKey, timestamp);
105
+ return {
106
+ publisher: deposit.publisher,
107
+ repo: deposit.repo,
108
+ generation: deposit.generation,
109
+ key,
110
+ readerKey,
111
+ sealed: deposit.sealed,
112
+ timestamp,
113
+ signature: await p.signer.signMessage({ message: { raw } })
114
+ };
115
+ }
116
+ /** Ask the deposit's key server for `key`'s key: the record key, or the repo key for `WHOLE_REPO`. */
117
+ async function requestKey(p) {
118
+ const secret = x25519.utils.randomSecretKey();
119
+ const req = await buildAccessRequest({
120
+ signer: p.signer,
121
+ deposit: p.deposit,
122
+ key: p.key,
123
+ readerKey: bytesToHex(x25519.getPublicKey(secret))
124
+ });
125
+ const res = await (p.fetch ?? fetch)(`${p.deposit.keyServer}/access`, {
126
+ method: "POST",
127
+ headers: { "Content-Type": "application/json" },
128
+ body: JSON.stringify(req)
129
+ });
130
+ if (!res.ok) throw new Error(`key server refused: ${res.status.toString()} ${await res.text()}`);
131
+ const { sealed } = await res.json();
132
+ return unseal(hexToBytes(sealed), secret, statement(scopeOf(p.deposit)));
133
+ }
134
+ /** Get the record's key, fetch the field's ciphertext and decrypt it. */
135
+ async function openField(p) {
136
+ if (p.handle.generation !== p.deposit.generation) throw new Error("the handle and the deposit are for different generations");
137
+ const [kRecord, ct] = await Promise.all([requestKey({
138
+ deposit: p.deposit,
139
+ key: p.key,
140
+ signer: p.signer,
141
+ fetch: p.fetch
142
+ }), p.storage.getFile(p.handle.cid)]);
143
+ return decryptField(kRecord, ct, statement(scopeOf(p.deposit)), p.key, p.field);
144
+ }
145
+
146
+ //#endregion
147
+ export { GADGET_FIELD_V1, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement };
@@ -0,0 +1,5 @@
1
+ //#region src/crypto/rand.d.ts
2
+ declare function getSubtleCrypto(): SubtleCrypto;
3
+ declare function getRandomValues(array: Uint8Array<ArrayBuffer>): Uint8Array<ArrayBuffer>;
4
+ //#endregion
5
+ export { getRandomValues, getSubtleCrypto };
@@ -0,0 +1,16 @@
1
+ //#region src/crypto/rand.ts
2
+ function getCrypto() {
3
+ if (typeof globalThis.crypto !== "undefined") return globalThis.crypto;
4
+ throw new Error("No crypto available - are you in Node < 19?");
5
+ }
6
+ function getSubtleCrypto() {
7
+ if (typeof window !== "undefined") return window.crypto.subtle;
8
+ else return getCrypto().subtle;
9
+ }
10
+ function getRandomValues(array) {
11
+ if (typeof window !== "undefined") return window.crypto.getRandomValues(array);
12
+ else return getCrypto().getRandomValues(array);
13
+ }
14
+
15
+ //#endregion
16
+ export { getRandomValues, getSubtleCrypto };
@@ -0,0 +1,23 @@
1
+ //#region src/crypto/types.d.ts
2
+ interface AesEncryptedData {
3
+ ciphertext: Uint8Array<ArrayBuffer>;
4
+ iv: Uint8Array<ArrayBuffer>;
5
+ authTag: Uint8Array<ArrayBuffer>;
6
+ salt: Uint8Array<ArrayBuffer>;
7
+ }
8
+ interface DecryptedPayload {
9
+ data: Uint8Array;
10
+ }
11
+ /**
12
+ * Result of successful decryption
13
+ */
14
+ interface DecryptedPayload {
15
+ data: Uint8Array;
16
+ metadata?: {
17
+ tag: string;
18
+ extension?: string;
19
+ fileType?: string;
20
+ };
21
+ }
22
+ //#endregion
23
+ export { AesEncryptedData, DecryptedPayload };
@@ -0,0 +1 @@
1
+ export { };
@@ -0,0 +1,14 @@
1
+ import { Block } from "./records.js";
2
+ import { CID } from "multiformats/cid";
3
+
4
+ //#region src/engine/car.d.ts
5
+ /** Serialize blocks into CAR v1 bytes under a single root. */
6
+ declare function packCar(root: CID, blocks: Iterable<Block>): Promise<Uint8Array>;
7
+ /** Decode CAR bytes back into blocks, each checked against its CID (the host is untrusted). */
8
+ declare function readCar(bytes: Uint8Array, {
9
+ verify
10
+ }?: {
11
+ verify?: boolean | undefined;
12
+ }): Promise<Block[]>;
13
+ //#endregion
14
+ export { packCar, readCar };
@@ -0,0 +1,42 @@
1
+ import { assertBlockMatches } from "./records.js";
2
+ import { CID } from "multiformats/cid";
3
+ import { CarReader, CarWriter } from "@ipld/car";
4
+
5
+ //#region src/engine/car.ts
6
+ /** Serialize blocks into CAR v1 bytes under a single root. */
7
+ async function packCar(root, blocks) {
8
+ const { writer, out } = CarWriter.create([root]);
9
+ const collected = [];
10
+ const sink = (async () => {
11
+ for await (const part of out) collected.push(part);
12
+ })();
13
+ for (const block of blocks) await writer.put(block);
14
+ await writer.close();
15
+ await sink;
16
+ let total = 0;
17
+ for (const p of collected) total += p.length;
18
+ const buf = new Uint8Array(total);
19
+ let off = 0;
20
+ for (const p of collected) {
21
+ buf.set(p, off);
22
+ off += p.length;
23
+ }
24
+ return buf;
25
+ }
26
+ /** Decode CAR bytes back into blocks, each checked against its CID (the host is untrusted). */
27
+ async function readCar(bytes, { verify = true } = {}) {
28
+ const reader = await CarReader.fromBytes(bytes);
29
+ const blocks = [];
30
+ for await (const { cid, bytes: blockBytes } of reader.blocks()) {
31
+ const ours = CID.parse(cid.toString());
32
+ if (verify) assertBlockMatches(ours, blockBytes);
33
+ blocks.push({
34
+ cid: ours,
35
+ bytes: blockBytes
36
+ });
37
+ }
38
+ return blocks;
39
+ }
40
+
41
+ //#endregion
42
+ export { packCar, readCar };
@@ -0,0 +1,206 @@
1
+ import { CommitUpdate, Registry } from "../contracts/data-registry/index.js";
2
+ import "../contracts/index.js";
3
+ import { MetadataStorage } from "../providers/storage/types.js";
4
+ import { CommitBlock, Ref } from "./records.js";
5
+ import { Address, Hash, Hex } from "viem";
6
+ import { CID } from "multiformats/cid";
7
+
8
+ //#region src/engine/index.d.ts
9
+ type RecordType = string;
10
+ type RepoName = string;
11
+ /** A staged (typed) record */
12
+ interface RecordInput {
13
+ id?: string;
14
+ type: RecordType;
15
+ payload: Record<string, unknown>;
16
+ }
17
+ /** A published record */
18
+ interface StoredRecord {
19
+ id: string;
20
+ cid: string;
21
+ type: RecordType;
22
+ payload: Record<string, unknown>;
23
+ }
24
+ /** A decoded commit, γ = (e, parent, root) plus its repo name and CAR (see CommitBlock). */
25
+ type CommitObject = CommitBlock;
26
+ interface RepoContents {
27
+ records: StoredRecord[];
28
+ }
29
+ /** Net change to a repo between two roots. */
30
+ interface RepoDiff {
31
+ /** Records that are new, or whose content changed (same id, new cid). */
32
+ puts: StoredRecord[];
33
+ /** Ids of records that are gone. */
34
+ deletes: string[];
35
+ /** CIDs of the old versions: records deleted, or replaced by a put. An index keyed by record CID drops these. */
36
+ superseded: string[];
37
+ }
38
+ /**
39
+ * Upper bound on a repo name's length. The name is stored in every commit
40
+ * block, so this is just a sanity bound keeping that block small and
41
+ * rejecting garbage input early.
42
+ */
43
+ declare const MAX_REPO_NAME_LENGTH = 256;
44
+ /**
45
+ * The root of the graph, committed to IPFS, as hex
46
+ */
47
+ declare function rootHexFromCid(commitCid: CID): Hex;
48
+ /** The update that settles `commit`. */
49
+ declare function commitUpdate(commit: CommitBlock): CommitUpdate;
50
+ /** The head the registry computes for `u`. */
51
+ declare function commitHead(u: CommitUpdate): Promise<Hex>;
52
+ /** A commit's update, signed by its publisher for anyone to submit. */
53
+ interface SignedUpdate {
54
+ publisher: Address;
55
+ update: CommitUpdate;
56
+ signature: Hex;
57
+ }
58
+ /** The CID a storage backend returned for a file, with or without an `ipfs://` prefix. */
59
+ declare function fileCid(uri: string): CID;
60
+ /** Repos must be non-empty strings whose length does not exceed MAX_REPO_NAME_LENGTH */
61
+ declare function assertValidRepoName(repo: RepoName): void;
62
+ /** One line of a commit's diff against its parent. */
63
+ interface CommitDiff {
64
+ parent: string | null;
65
+ epoch: number;
66
+ repo: string;
67
+ root: string;
68
+ /** `<ns>/<id>` of records new vs. the parent. */
69
+ added: string[];
70
+ /** `<ns>/<id>` of records whose content changed. */
71
+ updated: string[];
72
+ /** `<ns>/<id>` of records present in the parent but gone in this commit. */
73
+ removed: string[];
74
+ }
75
+ /** Input to `createCommit`: puts and deletes, by record id, under one repo. */
76
+ interface CreateCommitOptions {
77
+ repo: RepoName;
78
+ /** Parent commit this builds on (local HEAD or on-chain tip), or null for a root commit. */
79
+ base: CID | null;
80
+ /** Records to put. A put replaces any record with the same id. */
81
+ records: RecordInput[];
82
+ /** Ids of records to remove. Applied before `records`. */
83
+ deletes?: string[];
84
+ /**
85
+ * When true, the staged records REPLACE the repo's previous contents
86
+ * (a snapshot commit — anything omitted is removed). Default: puts and
87
+ * deletes apply on top of the parent state.
88
+ */
89
+ replace?: boolean;
90
+ }
91
+ declare class FangornEngine {
92
+ private storage;
93
+ private registry;
94
+ /**
95
+ * Local block cache. Written blocks land here immediately; remote blocks
96
+ * are pulled in whole-CAR-at-a-time by `loadCar`. Content addressing makes
97
+ * the cache trivially coherent.
98
+ */
99
+ private cache;
100
+ /** Commits whose CAR has already been loaded into the cache. */
101
+ private loadedCars;
102
+ /**
103
+ * Blocks from a loaded CAR, not yet hash-checked. A CAR holds every block its commit introduced
104
+ * (the first commit of a 50k-record repo: all of them), and a diff reads a handful: each block is
105
+ * checked when `getBlock` first hands it out, then moves to `cache`.
106
+ */
107
+ private unverified;
108
+ constructor(storage: MetadataStorage, registry: Registry);
109
+ /**
110
+ * Reconstructs the CID a commit's raw digest hex refers to. The contract only
111
+ * stores the bare 32-byte sha256 digest (see commitStateRoot), so rebuilding
112
+ * the CID must wrap that digest directly via Digest.create — hashing it again
113
+ * with sha256.digest() would produce an unrelated CID pointing at nothing.
114
+ */
115
+ private hexToRootCid;
116
+ /** Read and decode a commit object by CID (directly addressable — no CAR needed). */
117
+ getCommit(commitCid: CID): Promise<CommitObject>;
118
+ /** Pull every block of `commit`'s CAR into the local cache. */
119
+ private loadCar;
120
+ /**
121
+ * Resolve a data block: local cache first, then walk the commit chain from
122
+ * `hint`, loading one ancestor CAR at a time until the block turns up.
123
+ */
124
+ private getBlock;
125
+ private putLocal;
126
+ /**
127
+ * Reconstruct the current on-chain head of one publisher's repo as a
128
+ * commit CID, or null if none. Each repo is its own on-chain timeline,
129
+ * so this is per-(publisher, repo) rather than per-publisher.
130
+ */
131
+ resolveHeadCommit(publisher: Address, repo: RepoName): Promise<CID | null>;
132
+ /**
133
+ * Which repo a commit belongs to. Events carry only `keccak256(name)`, so
134
+ * this is how a subscriber to every repo recovers the name.
135
+ */
136
+ repoOf(rootHex: Hex): Promise<RepoName>;
137
+ /** The record state a commit holds. */
138
+ private stateAt;
139
+ /**
140
+ * Build a new commit on top of `base` — entirely in memory, then persisted
141
+ * as exactly TWO uploads: one CAR file holding every block this commit
142
+ * introduced (git's packfile), and the small commit block itself (stored
143
+ * individually so the on-chain digest resolves without any index).
144
+ *
145
+ * Unchanged records and MST nodes re-derive their old CIDs and are NOT
146
+ * re-uploaded. Does not touch the chain — `pushCommit` settles it.
147
+ */
148
+ createCommit(opts: CreateCommitOptions): Promise<{
149
+ commitCid: CID;
150
+ root: CID;
151
+ /** id → record CID for every record staged (including generated ids). */
152
+ recordCids: Record<string, string>;
153
+ }>;
154
+ /**
155
+ * Settle a local commit as the on-chain head of one repo — the `update` of
156
+ * WHITEPAPER_1 §3.2. The commit and its CAR are already durable in storage
157
+ * (createCommit uploads them), so this is just the compare-and-swap.
158
+ */
159
+ pushCommit(publisher: Address, repo: RepoName, commitCid: CID): Promise<{
160
+ txHash: Hash;
161
+ onChainTip: CID;
162
+ }>;
163
+ /** `pushCommit`, signed by this registry's wallet for anyone to submit with `relayCommit`. */
164
+ signCommit(publisher: Address, repo: RepoName, commitCid: CID): Promise<SignedUpdate>;
165
+ relayCommit(s: SignedUpdate): Promise<Hash>;
166
+ /** The update for `commitCid`, once it is one the registry will take as the next head. */
167
+ settleable(publisher: Address, repo: RepoName, commitCid: CID): Promise<CommitUpdate>;
168
+ /** Walk the parent chain from `tip` toward the root, newest first. */
169
+ walkParents(tip: CID, max?: number): AsyncGenerator<{
170
+ cid: CID;
171
+ commit: CommitObject;
172
+ }>;
173
+ /** The commit CID string a raw on-chain root hex points at. */
174
+ commitCidFromRootHex(hex: string): string;
175
+ /** Inverse of `commitCidFromRootHex`: the on-chain root hex for a commit CID. */
176
+ rootHexFromCommitCid(commitCid: string): Hex;
177
+ /** Decode a record block, checking it is filed under its own id. */
178
+ private decodeRecord;
179
+ /**
180
+ * Net change to a single repo between two on-chain roots — the core of
181
+ * the subscription light-client. A plain comparison of the two id → CID
182
+ * maps; only records that actually changed are decoded.
183
+ *
184
+ * Diffing root-to-root (rather than walking commits) is deliberately robust:
185
+ * it yields the correct net delta even across a force-push / non-fast-forward
186
+ * reorg — exactly what an index builder needs (what to (re)embed, what to evict).
187
+ * Reads only the nodes on changed paths (`diffMst`): 10 new records in a
188
+ * 50k-record repo cost ~10 × depth nodes, not two 50k-key walks.
189
+ */
190
+ repoDiff(oldRootHex: string | null, newRootHex: string): Promise<RepoDiff>;
191
+ /** Diff a commit against its parent. */
192
+ diffCommit(commitCid: CID): Promise<CommitDiff>;
193
+ /** check if the repo already exists (head resolves) */
194
+ repoExists(publisher: Address, repo: RepoName): Promise<boolean>;
195
+ /** Lists every record currently committed under a repo, resolved from the on-chain root. */
196
+ listRepo(publisher: Address, repo: RepoName): Promise<RepoContents>;
197
+ /** Every record in the state a commit holds; none for no commit. */
198
+ listAt(head: CID | null): Promise<RepoContents>;
199
+ /**
200
+ * Fetch the current version of one record by id — one MST path from the
201
+ * on-chain root, then the record block. Null if the repo has no such id.
202
+ */
203
+ readRecord(publisher: Address, repo: RepoName, id: string): Promise<StoredRecord | null>;
204
+ }
205
+ //#endregion
206
+ export { CommitDiff, CommitObject, CreateCommitOptions, FangornEngine, MAX_REPO_NAME_LENGTH, RecordInput, RecordType, type Ref, RepoContents, RepoDiff, RepoName, SignedUpdate, StoredRecord, assertValidRepoName, commitHead, commitUpdate, fileCid, rootHexFromCid };