@fangorn-network/sdk 0.1.4 → 0.1.6

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.
@@ -1,7 +1,7 @@
1
1
  //#region src/contracts/data-registry/abi.d.ts
2
2
  /**
3
3
  * Generated from `forge inspect DataRegistry abi` in fangorn-network/contracts
4
- * (solidity/src/DataRegistry.sol). Regenerate with scripts/gen-abis.sh, do not edit.
4
+ * (src/DataRegistry.sol). Regenerate with scripts/gen-abis.sh, do not edit.
5
5
  */
6
6
  declare const DATA_REGISTRY_ABI: readonly [{
7
7
  readonly type: "constructor";
@@ -72,6 +72,10 @@ declare const DATA_REGISTRY_ABI: readonly [{
72
72
  readonly name: "parent";
73
73
  readonly type: "bytes32";
74
74
  readonly internalType: "bytes32";
75
+ }, {
76
+ readonly name: "diff";
77
+ readonly type: "bytes32";
78
+ readonly internalType: "bytes32";
75
79
  }, {
76
80
  readonly name: "root";
77
81
  readonly type: "bytes32";
@@ -240,6 +244,10 @@ declare const DATA_REGISTRY_ABI: readonly [{
240
244
  readonly name: "parent";
241
245
  readonly type: "bytes32";
242
246
  readonly internalType: "bytes32";
247
+ }, {
248
+ readonly name: "diff";
249
+ readonly type: "bytes32";
250
+ readonly internalType: "bytes32";
243
251
  }, {
244
252
  readonly name: "root";
245
253
  readonly type: "bytes32";
@@ -274,6 +282,10 @@ declare const DATA_REGISTRY_ABI: readonly [{
274
282
  readonly name: "parent";
275
283
  readonly type: "bytes32";
276
284
  readonly internalType: "bytes32";
285
+ }, {
286
+ readonly name: "diff";
287
+ readonly type: "bytes32";
288
+ readonly internalType: "bytes32";
277
289
  }, {
278
290
  readonly name: "root";
279
291
  readonly type: "bytes32";
@@ -1,7 +1,7 @@
1
1
  //#region src/contracts/data-registry/abi.ts
2
2
  /**
3
3
  * Generated from `forge inspect DataRegistry abi` in fangorn-network/contracts
4
- * (solidity/src/DataRegistry.sol). Regenerate with scripts/gen-abis.sh, do not edit.
4
+ * (src/DataRegistry.sol). Regenerate with scripts/gen-abis.sh, do not edit.
5
5
  */
6
6
  const DATA_REGISTRY_ABI = [
7
7
  {
@@ -83,6 +83,11 @@ const DATA_REGISTRY_ABI = [
83
83
  type: "bytes32",
84
84
  internalType: "bytes32"
85
85
  },
86
+ {
87
+ name: "diff",
88
+ type: "bytes32",
89
+ internalType: "bytes32"
90
+ },
86
91
  {
87
92
  name: "root",
88
93
  type: "bytes32",
@@ -269,6 +274,11 @@ const DATA_REGISTRY_ABI = [
269
274
  type: "bytes32",
270
275
  internalType: "bytes32"
271
276
  },
277
+ {
278
+ name: "diff",
279
+ type: "bytes32",
280
+ internalType: "bytes32"
281
+ },
272
282
  {
273
283
  name: "root",
274
284
  type: "bytes32",
@@ -311,6 +321,11 @@ const DATA_REGISTRY_ABI = [
311
321
  type: "bytes32",
312
322
  internalType: "bytes32"
313
323
  },
324
+ {
325
+ name: "diff",
326
+ type: "bytes32",
327
+ internalType: "bytes32"
328
+ },
314
329
  {
315
330
  name: "root",
316
331
  type: "bytes32",
@@ -16,6 +16,8 @@ interface CommitUpdate {
16
16
  epoch: number;
17
17
  /** digest of the parent commit, or ZERO_HEAD */
18
18
  parent: Hex;
19
+ /** digest of the event's diff tree */
20
+ diff: Hex;
19
21
  /** digest of the state root */
20
22
  root: Hex;
21
23
  /** the CAR's CID, as bytes */
@@ -34,6 +36,9 @@ declare const UPDATE_TYPES: {
34
36
  }, {
35
37
  readonly name: "parent";
36
38
  readonly type: "bytes32";
39
+ }, {
40
+ readonly name: "diff";
41
+ readonly type: "bytes32";
37
42
  }, {
38
43
  readonly name: "root";
39
44
  readonly type: "bytes32";
@@ -48,6 +53,7 @@ declare const updateMessage: (publisher: Address, u: CommitUpdate) => {
48
53
  repo: string;
49
54
  epoch: bigint;
50
55
  parent: `0x${string}`;
56
+ diff: `0x${string}`;
51
57
  root: `0x${string}`;
52
58
  car: `0x${string}`;
53
59
  };
@@ -81,6 +87,11 @@ interface Registry {
81
87
  epoch(): Promise<number>;
82
88
  /** H(ρ): the committed head, or ZERO_HEAD for a repo never written. */
83
89
  head(ref: RepoRef): Promise<Hex>;
90
+ /** H(ρ) with its position (the repo's generation, from 1); (0, ZERO_HEAD) if never written. */
91
+ headAt(ref: RepoRef): Promise<{
92
+ pos: number;
93
+ head: Hex;
94
+ }>;
84
95
  /** Moves the signer's repo to the commit `u`. Valid only while `u.parent` is the head (Theorem 3). */
85
96
  update(u: CommitUpdate): Promise<Hash>;
86
97
  /** `update` as an unsigned transaction for `publisher` to sign. */
@@ -89,6 +100,8 @@ interface Registry {
89
100
  signUpdate(u: CommitUpdate): Promise<Hex>;
90
101
  /** `update` for `publisher`, on its signature. Anyone may submit it. */
91
102
  updateBySig(publisher: Address, u: CommitUpdate, signature: Hex): Promise<Hash>;
103
+ /** The update log's mountain range root as of clock `at` (default: now). */
104
+ logRoot(at?: bigint): Promise<Hex>;
92
105
  /** The entries of a log between two clock values, oldest first. */
93
106
  log(filter: LogFilter, from: bigint, to?: bigint): Promise<UpdateEntry[]>;
94
107
  /** Follow the log live. Returns an unsubscribe function. */
@@ -114,6 +127,11 @@ declare class ChainRegistry implements Registry {
114
127
  constructor(config: ChainRegistryConfig, publicClient: PublicClient, walletClient?: WalletClient | undefined);
115
128
  epoch(): Promise<number>;
116
129
  head(ref: RepoRef): Promise<Hex>;
130
+ headAt(ref: RepoRef): Promise<{
131
+ pos: number;
132
+ head: Hex;
133
+ }>;
134
+ logRoot(at?: bigint): Promise<Hex>;
117
135
  update(u: CommitUpdate): Promise<Hash>;
118
136
  prepareUpdate(publisher: Address, u: CommitUpdate): Promise<PreparedTx>;
119
137
  signUpdate(u: CommitUpdate): Promise<Hex>;
@@ -33,6 +33,10 @@ const UPDATE_TYPES = { Update: [
33
33
  name: "parent",
34
34
  type: "bytes32"
35
35
  },
36
+ {
37
+ name: "diff",
38
+ type: "bytes32"
39
+ },
36
40
  {
37
41
  name: "root",
38
42
  type: "bytes32"
@@ -53,6 +57,7 @@ const updateMessage = (publisher, u) => ({
53
57
  repo: u.repo,
54
58
  epoch: BigInt(u.epoch),
55
59
  parent: u.parent,
60
+ diff: u.diff,
56
61
  root: u.root,
57
62
  car: u.car
58
63
  });
@@ -75,13 +80,27 @@ var ChainRegistry = class {
75
80
  return epochOf((await this.publicClient.getBlock()).timestamp);
76
81
  }
77
82
  async head(ref) {
78
- const [, head] = await this.publicClient.readContract({
83
+ return (await this.headAt(ref)).head;
84
+ }
85
+ async headAt(ref) {
86
+ const [pos, head] = await this.publicClient.readContract({
79
87
  address: this.data,
80
88
  abi: DATA_REGISTRY_ABI,
81
89
  functionName: "getHead",
82
90
  args: [ref.publisher, repoId(ref.repo)]
83
91
  });
84
- return head;
92
+ return {
93
+ pos: Number(pos),
94
+ head
95
+ };
96
+ }
97
+ logRoot(at) {
98
+ return this.publicClient.readContract({
99
+ address: this.data,
100
+ abi: DATA_REGISTRY_ABI,
101
+ functionName: "logRoot",
102
+ ...at === void 0 ? {} : { blockNumber: at }
103
+ });
85
104
  }
86
105
  update(u) {
87
106
  return this.write("update", updateArgs(u));
@@ -162,6 +181,7 @@ function updateArgs(u) {
162
181
  u.repo,
163
182
  BigInt(u.epoch),
164
183
  u.parent,
184
+ u.diff,
165
185
  u.root,
166
186
  u.car
167
187
  ];
@@ -0,0 +1,23 @@
1
+ import { UpdateEntry } from "./index.js";
2
+ import { Hex } from "viem";
3
+
4
+ //#region src/contracts/data-registry/mmr.d.ts
5
+ /** The leaf the contract appended for one log entry. */
6
+ declare const logLeaf: (e: UpdateEntry) => Hex;
7
+ /** A mountain range as its length and peaks; `peaks[h]` is live where bit h of n is set. */
8
+ interface Mmr {
9
+ n: number;
10
+ peaks: (Hex | null)[];
11
+ }
12
+ declare const EMPTY_MMR: Mmr;
13
+ declare function mmrAppend({
14
+ n,
15
+ peaks
16
+ }: Mmr, leaf: Hex): Mmr;
17
+ /** `logRoot()` for this range. */
18
+ declare function mmrRoot({
19
+ n,
20
+ peaks
21
+ }: Mmr): Hex;
22
+ //#endregion
23
+ export { EMPTY_MMR, Mmr, logLeaf, mmrAppend, mmrRoot };
@@ -0,0 +1,65 @@
1
+ import { repoId } from "./index.js";
2
+ import { encodeAbiParameters, keccak256, stringToHex, zeroHash } from "viem";
3
+
4
+ //#region src/contracts/data-registry/mmr.ts
5
+ const tag = (s) => stringToHex(s, { size: 32 });
6
+ /** The leaf the contract appended for one log entry. */
7
+ const logLeaf = (e) => keccak256(encodeAbiParameters([
8
+ { type: "bytes32" },
9
+ { type: "address" },
10
+ { type: "bytes32" },
11
+ { type: "uint64" },
12
+ { type: "bytes32" },
13
+ { type: "uint64" }
14
+ ], [
15
+ tag("leaf"),
16
+ e.publisher,
17
+ repoId(e.repo),
18
+ BigInt(e.pos),
19
+ e.head,
20
+ e.timestamp
21
+ ]));
22
+ const EMPTY_MMR = {
23
+ n: 0,
24
+ peaks: []
25
+ };
26
+ function mmrAppend({ n, peaks }, leaf) {
27
+ const next = [...peaks];
28
+ let node = leaf;
29
+ let h = 0;
30
+ while (n >> h & 1) {
31
+ node = keccak256(encodeAbiParameters([
32
+ { type: "bytes32" },
33
+ { type: "bytes32" },
34
+ { type: "bytes32" }
35
+ ], [
36
+ tag("node"),
37
+ next[h] ?? zeroHash,
38
+ node
39
+ ]));
40
+ next[h] = null;
41
+ h++;
42
+ }
43
+ next[h] = node;
44
+ return {
45
+ n: n + 1,
46
+ peaks: next
47
+ };
48
+ }
49
+ /** `logRoot()` for this range. */
50
+ function mmrRoot({ n, peaks }) {
51
+ const live = [];
52
+ for (let h = peaks.length - 1; h >= 0; h--) if (n >> h & 1) live.push(peaks[h] ?? zeroHash);
53
+ return keccak256(encodeAbiParameters([
54
+ { type: "bytes32" },
55
+ { type: "uint64" },
56
+ { type: "bytes32[]" }
57
+ ], [
58
+ tag("mmr"),
59
+ BigInt(n),
60
+ live
61
+ ]));
62
+ }
63
+
64
+ //#endregion
65
+ export { EMPTY_MMR, logLeaf, mmrAppend, mmrRoot };
@@ -3,4 +3,5 @@ import { ChainRegistry, ChainRegistryConfig, CommitUpdate, EPOCH_SECONDS, LogFil
3
3
  import { DATA_REGISTRY_ABI } from "./data-registry/abi.js";
4
4
  import { RegisterArgs, SettleArgs, SettlementPayment, SettlementRegistryClient, TERMS_TYPES, Terms, TermsJson, WHOLE_REPO, recordKey, registerNonce, settlementDomain, subjectOf, termsFromJson, termsToJson } from "./settlement-registry/index.js";
5
5
  import { SETTLEMENT_REGISTRY_ABI } from "./settlement-registry/abi.js";
6
- export { ChainRegistry, ChainRegistryConfig, CommitUpdate, DATA_REGISTRY_ABI, EPOCH_SECONDS, LogFilter, type PreparedTx, RegisterArgs, Registry, RepoRef, SETTLEMENT_REGISTRY_ABI, SettleArgs, SettlementPayment, SettlementRegistryClient, TERMS_TYPES, Terms, TermsJson, UPDATE_TYPES, UpdateEntry, WHOLE_REPO, WINDOW, ZERO_HEAD, dataDomain, epochOf, recordKey, registerNonce, repoId, settlementDomain, subjectOf, termsFromJson, termsToJson, updateMessage };
6
+ import { EMPTY_MMR, Mmr, logLeaf, mmrAppend, mmrRoot } from "./data-registry/mmr.js";
7
+ export { ChainRegistry, ChainRegistryConfig, CommitUpdate, DATA_REGISTRY_ABI, EMPTY_MMR, EPOCH_SECONDS, LogFilter, Mmr, type PreparedTx, RegisterArgs, Registry, RepoRef, SETTLEMENT_REGISTRY_ABI, SettleArgs, SettlementPayment, SettlementRegistryClient, TERMS_TYPES, Terms, TermsJson, UPDATE_TYPES, UpdateEntry, WHOLE_REPO, WINDOW, ZERO_HEAD, dataDomain, epochOf, logLeaf, mmrAppend, mmrRoot, recordKey, registerNonce, repoId, settlementDomain, subjectOf, termsFromJson, termsToJson, updateMessage };
@@ -2,5 +2,6 @@ import { DATA_REGISTRY_ABI } from "./data-registry/abi.js";
2
2
  import { ChainRegistry, EPOCH_SECONDS, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./data-registry/index.js";
3
3
  import { SETTLEMENT_REGISTRY_ABI } from "./settlement-registry/abi.js";
4
4
  import { SettlementRegistryClient, TERMS_TYPES, WHOLE_REPO, recordKey, registerNonce, settlementDomain, subjectOf, termsFromJson, termsToJson } from "./settlement-registry/index.js";
5
+ import { EMPTY_MMR, logLeaf, mmrAppend, mmrRoot } from "./data-registry/mmr.js";
5
6
 
6
- export { ChainRegistry, DATA_REGISTRY_ABI, EPOCH_SECONDS, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, TERMS_TYPES, UPDATE_TYPES, WHOLE_REPO, WINDOW, ZERO_HEAD, dataDomain, epochOf, recordKey, registerNonce, repoId, settlementDomain, subjectOf, termsFromJson, termsToJson, updateMessage };
7
+ export { ChainRegistry, DATA_REGISTRY_ABI, EMPTY_MMR, EPOCH_SECONDS, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, TERMS_TYPES, UPDATE_TYPES, WHOLE_REPO, WINDOW, ZERO_HEAD, dataDomain, epochOf, logLeaf, mmrAppend, mmrRoot, recordKey, registerNonce, repoId, settlementDomain, subjectOf, termsFromJson, termsToJson, updateMessage };
@@ -1,7 +1,7 @@
1
1
  //#region src/contracts/settlement-registry/abi.d.ts
2
2
  /**
3
3
  * Generated from `forge inspect SettlementRegistry abi` in fangorn-network/contracts
4
- * (solidity/src/SettlementRegistry.sol). Regenerate with scripts/gen-abis.sh, do not edit.
4
+ * (src/SettlementRegistry.sol). Regenerate with scripts/gen-abis.sh, do not edit.
5
5
  */
6
6
  declare const SETTLEMENT_REGISTRY_ABI: readonly [{
7
7
  readonly type: "constructor";
@@ -1,7 +1,7 @@
1
1
  //#region src/contracts/settlement-registry/abi.ts
2
2
  /**
3
3
  * Generated from `forge inspect SettlementRegistry abi` in fangorn-network/contracts
4
- * (solidity/src/SettlementRegistry.sol). Regenerate with scripts/gen-abis.sh, do not edit.
4
+ * (src/SettlementRegistry.sol). Regenerate with scripts/gen-abis.sh, do not edit.
5
5
  */
6
6
  const SETTLEMENT_REGISTRY_ABI = [
7
7
  {
@@ -25,13 +25,22 @@ interface PreparedTx {
25
25
  * Two deliberate choices, both about transactions that would otherwise silently
26
26
  * fail on a live L2:
27
27
  *
28
- * - **30% gas headroom.** The estimate is taken against the current state; by the
29
- * time the transaction lands the state has moved. Unused gas is refunded, so
30
- * the headroom is free and running out of it is not.
28
+ * - **30% + APPEND_ALLOWANCE gas headroom.** The estimate is taken against the
29
+ * current state; by the time the transaction lands the state has moved. The
30
+ * fixed allowance covers the one jump the 30% can't: other updates landing
31
+ * first, so this one appends to the log at a length of 2^k − 1. Unused gas is
32
+ * refunded, so the headroom is free and running out of it is not.
31
33
  * - **3x maxFeePerGas.** This is a ceiling, not a payment — you pay
32
34
  * base + priority. Quoting it tightly is how a transaction gets stuck when the
33
35
  * base fee ticks up between estimate and inclusion.
34
36
  */
37
+ /**
38
+ * The most DataRegistry._append can cost over an append estimated at any other
39
+ * log length: 63 merges (cold SLOAD + keccak, ~2.5k each) and a first write to
40
+ * peaks[63] (~20k). logLength is a uint64, so this is a hard bound, not a guess.
41
+ * The contracts repo pins it: test_append_worst_case_fits_sdk_allowance.
42
+ */
43
+ declare const APPEND_ALLOWANCE = 200000n;
35
44
  declare function sendWrite(publicClient: PublicClient, walletClient: WalletClient, address: Address, abi: Abi, functionName: string, args: readonly unknown[], value?: bigint): Promise<Hash>;
36
45
  /** Guard for clients that accept a read-only construction. */
37
46
  declare function requireWallet(walletClient: WalletClient | undefined, what: string): WalletClient;
@@ -56,4 +65,4 @@ declare function prepareWrite(publicClient: PublicClient, from: Address, address
56
65
  simulate?: boolean;
57
66
  }): Promise<PreparedTx>;
58
67
  //#endregion
59
- export { PreparedTx, prepareWrite, requireWallet, sendWrite };
68
+ export { APPEND_ALLOWANCE, PreparedTx, prepareWrite, requireWallet, sendWrite };
@@ -12,26 +12,35 @@ import { encodeFunctionData, toHex } from "viem";
12
12
  * Two deliberate choices, both about transactions that would otherwise silently
13
13
  * fail on a live L2:
14
14
  *
15
- * - **30% gas headroom.** The estimate is taken against the current state; by the
16
- * time the transaction lands the state has moved. Unused gas is refunded, so
17
- * the headroom is free and running out of it is not.
15
+ * - **30% + APPEND_ALLOWANCE gas headroom.** The estimate is taken against the
16
+ * current state; by the time the transaction lands the state has moved. The
17
+ * fixed allowance covers the one jump the 30% can't: other updates landing
18
+ * first, so this one appends to the log at a length of 2^k − 1. Unused gas is
19
+ * refunded, so the headroom is free and running out of it is not.
18
20
  * - **3x maxFeePerGas.** This is a ceiling, not a payment — you pay
19
21
  * base + priority. Quoting it tightly is how a transaction gets stuck when the
20
22
  * base fee ticks up between estimate and inclusion.
21
23
  */
24
+ /**
25
+ * The most DataRegistry._append can cost over an append estimated at any other
26
+ * log length: 63 merges (cold SLOAD + keccak, ~2.5k each) and a first write to
27
+ * peaks[63] (~20k). logLength is a uint64, so this is a hard bound, not a guess.
28
+ * The contracts repo pins it: test_append_worst_case_fits_sdk_allowance.
29
+ */
30
+ const APPEND_ALLOWANCE = 200000n;
22
31
  async function sendWrite(publicClient, walletClient, address, abi, functionName, args, value) {
23
32
  if (!walletClient.chain) throw new Error("Chain required");
24
33
  if (!walletClient.account) throw new Error("Account required");
25
34
  const { chain, account } = walletClient;
26
35
  const fees = await publicClient.estimateFeesPerGas();
27
- const gas = await publicClient.estimateContractGas({
36
+ const limit = await publicClient.estimateContractGas({
28
37
  address,
29
38
  abi,
30
39
  functionName,
31
40
  args,
32
41
  account,
33
42
  value
34
- });
43
+ }) * 130n / 100n + APPEND_ALLOWANCE;
35
44
  const hash = await walletClient.writeContract({
36
45
  address,
37
46
  abi,
@@ -39,12 +48,13 @@ async function sendWrite(publicClient, walletClient, address, abi, functionName,
39
48
  args,
40
49
  chain,
41
50
  account,
42
- gas: gas * 130n / 100n,
51
+ gas: limit,
43
52
  maxFeePerGas: fees.maxFeePerGas * 3n,
44
53
  maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
45
54
  value
46
55
  });
47
- await publicClient.waitForTransactionReceipt({ hash });
56
+ const receipt = await publicClient.waitForTransactionReceipt({ hash });
57
+ if (receipt.status !== "success") throw new Error(`${functionName} reverted in tx ${hash} (gasUsed ${String(receipt.gasUsed)} of ${String(limit)})`);
48
58
  return hash;
49
59
  }
50
60
  /** Guard for clients that accept a read-only construction. */
@@ -99,4 +109,4 @@ async function prepareWrite(publicClient, from, address, abi, functionName, args
99
109
  }
100
110
 
101
111
  //#endregion
102
- export { prepareWrite, requireWallet, sendWrite };
112
+ export { APPEND_ALLOWANCE, prepareWrite, requireWallet, sendWrite };
@@ -1,7 +1,7 @@
1
1
  import { CommitUpdate, Registry } from "../contracts/data-registry/index.js";
2
2
  import "../contracts/index.js";
3
3
  import { MetadataStorage } from "../providers/storage/types.js";
4
- import { CommitBlock, Ref } from "./records.js";
4
+ import { CommitBlock, Ref, Stitch } from "./records.js";
5
5
  import { Address, Hash, Hex } from "viem";
6
6
  import { CID } from "multiformats/cid";
7
7
 
@@ -21,8 +21,13 @@ interface StoredRecord {
21
21
  type: RecordType;
22
22
  payload: Record<string, unknown>;
23
23
  }
24
- /** A decoded commit, γ = (e, parent, root) plus its repo name and CAR (see CommitBlock). */
25
- type CommitObject = CommitBlock;
24
+ /**
25
+ * A decoded commit: the event (e, parent, diff, root) plus its repo name and CAR
26
+ * (see CommitBlock). `diff` is null for commits written before events carried one.
27
+ */
28
+ type CommitObject = Omit<CommitBlock, "diff"> & {
29
+ diff: CID | null;
30
+ };
26
31
  interface RepoContents {
27
32
  records: StoredRecord[];
28
33
  }
@@ -41,12 +46,18 @@ interface RepoDiff {
41
46
  * rejecting garbage input early.
42
47
  */
43
48
  declare const MAX_REPO_NAME_LENGTH = 256;
49
+ /**
50
+ * Every this many positions, a commit's CAR holds the whole state (see `checkpoint`), so a
51
+ * cold read walks back at most this many CARs (~2 fetches each: under Workers' 1000 subrequests).
52
+ */
53
+ declare const CHECKPOINT_EVERY = 100;
44
54
  /**
45
55
  * The root of the graph, committed to IPFS, as hex
46
56
  */
47
57
  declare function rootHexFromCid(commitCid: CID): Hex;
58
+ declare function cidFromDigest(digest: Hex): CID;
48
59
  /** The update that settles `commit`. */
49
- declare function commitUpdate(commit: CommitBlock): CommitUpdate;
60
+ declare function commitUpdate(commit: CommitObject): CommitUpdate;
50
61
  /** The head the registry computes for `u`. */
51
62
  declare function commitHead(u: CommitUpdate): Promise<Hex>;
52
63
  /** A commit's update, signed by its publisher for anyone to submit. */
@@ -87,6 +98,13 @@ interface CreateCommitOptions {
87
98
  * deletes apply on top of the parent state.
88
99
  */
89
100
  replace?: boolean;
101
+ /**
102
+ * Pack the whole state (every MST node and live record) into this commit's CAR, not just
103
+ * the delta. `getBlock` walks back one CAR per commit, so this caps how far it goes.
104
+ * ponytail: a full copy of the repo every CHECKPOINT_EVERY commits; a block → commit
105
+ * index would avoid it if big repos make that costly.
106
+ */
107
+ checkpoint?: boolean;
90
108
  }
91
109
  declare class FangornEngine {
92
110
  private storage;
@@ -115,11 +133,15 @@ declare class FangornEngine {
115
133
  private hexToRootCid;
116
134
  /** Read and decode a commit object by CID (directly addressable — no CAR needed). */
117
135
  getCommit(commitCid: CID): Promise<CommitObject>;
118
- /** Pull every block of `commit`'s CAR into the local cache. */
136
+ /** A block stored on its own (a commit or stitch block), hash-checked and cached. */
137
+ private directBlock;
138
+ /** The packfile and parent of a link in a chain: a commit, or a stitch. */
139
+ private chainLink;
140
+ /** Pull every block of a chain link's CAR into the local cache. */
119
141
  private loadCar;
120
142
  /**
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.
143
+ * Resolve a data block: local cache first, then walk the chain (commits, or
144
+ * stitches) from `hint`, loading one ancestor CAR at a time until the block turns up.
123
145
  */
124
146
  private getBlock;
125
147
  private putLocal;
@@ -176,20 +198,80 @@ declare class FangornEngine {
176
198
  rootHexFromCommitCid(commitCid: string): Hex;
177
199
  /** Decode a record block, checking it is filed under its own id. */
178
200
  private decodeRecord;
201
+ /** The diff an event carries: id → new record CID, or null where the record was deleted. */
202
+ eventDiff(commitCid: CID): Promise<Map<string, CID | null>>;
203
+ /**
204
+ * The events after `old` up to `tip`, composed into one id → CID | null map, newest write
205
+ * winning. Null when `old` is not an ancestor of `tip`, or an event between them has no diff.
206
+ */
207
+ private eventsSince;
179
208
  /**
180
209
  * 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.
210
+ * the subscription light-client. Only records that actually changed are decoded.
183
211
  *
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.
212
+ * When `old` is an ancestor of `new`, this reads the diffs the events carry (WHITEPAPER_1 §3.3,
213
+ * Following) and looks each changed id up in the old tree. Otherwise, across a reset to another
214
+ * chain or a commit from before diff events, it diffs the two trees (`diffMst`). Either way the
215
+ * result is the net delta an index builder needs: what to (re)embed, what to evict.
189
216
  */
190
217
  repoDiff(oldRootHex: string | null, newRootHex: string): Promise<RepoDiff>;
191
- /** Diff a commit against its parent. */
218
+ /** Diff a commit against its parent: its event's diff, or two full states for an older commit. */
192
219
  diffCommit(commitCid: CID): Promise<CommitDiff>;
220
+ /** A stitch to the current head of (publisher, repo), at `key` if given. One `getHead` read, no logs. */
221
+ stitchTo(publisher: Address, repo: RepoName, key?: string): Promise<Stitch>;
222
+ /**
223
+ * A stitch across repos: an MST of `publisher/repo` → head commit, folded from the
224
+ * update log up to entry n and tagged with the log's root there. Pass the previous
225
+ * stitch to read only the log since it, and upload only the nodes it doesn't have
226
+ * (one CAR). Returns the stitch block's CID, its name; with nothing new, `prev`.
227
+ * Use the same `filter` every time for one stitch. `fromBlock` is where the log
228
+ * starts (the registry's deploy block).
229
+ * ponytail: rehashes the whole tree (O(repos)); and readers walk back one CAR per
230
+ * stitch to find old nodes, so checkpoint with a full CAR (`prev = null`) when the
231
+ * chain gets long.
232
+ */
233
+ restitch(prev: CID | null, filter?: (publisher: Address, repo: RepoName) => boolean, fromBlock?: bigint): Promise<CID>;
234
+ /** A stitch block: its tree root, and the log it was folded from (n entries, root `logRoot`). */
235
+ readStitch(stitch: CID): Promise<{
236
+ root: CID;
237
+ n: number;
238
+ t: bigint;
239
+ peaks: (Hex | null)[];
240
+ logRoot: Hex;
241
+ }>;
242
+ /**
243
+ * The head commit a stitch holds for (publisher, repo), or null if it doesn't
244
+ * include the repo. Every node read is hash-checked.
245
+ * ponytail: like `lookupMst`, trusts key order on the path; `readMst` proves absence.
246
+ */
247
+ stitchedHead(stitch: CID, publisher: Address, repo: RepoName): Promise<CID | null>;
248
+ /** Every (publisher, repo) → head commit a stitch holds: what an indexer follows. */
249
+ stitchHeads(stitch: CID): Promise<{
250
+ publisher: Address;
251
+ repo: RepoName;
252
+ head: CID;
253
+ }[]>;
254
+ /**
255
+ * Check a stitch without trusting whoever built it: replay the whole log, check it
256
+ * against the contract's log root, and rebuild the stitch from its first n entries
257
+ * under the same `filter`. Reads no stitch nodes, only the stitch block.
258
+ * ponytail: O(log) per check; store log roots on chain if that gets slow.
259
+ */
260
+ verifyStitch(stitch: CID, filter?: (publisher: Address, repo: RepoName) => boolean, fromBlock?: bigint): Promise<boolean>;
261
+ /**
262
+ * Check a stitch against the registry (WHITEPAPER_1 Proposition 4.2) and resolve it:
263
+ * the record at its key as of that position (null if absent), or, with no key, the event's diff.
264
+ * Throws if the repo never had `head` at `pos`. `latest` says whether the repo has moved on.
265
+ * A stitch at the current generation is checked with one `getHead` read.
266
+ * ponytail: an older stitch still scans the log from `fromBlock` (and trusts the RPC).
267
+ * Upgrade: walk parents back from the on-chain head, recomputing `commitHead` each hop
268
+ * (O(distance), no logs), or an MMR opening against `logRoot()` (O(log n), needs a proof server).
269
+ */
270
+ checkStitch(s: Stitch, fromBlock?: bigint): Promise<{
271
+ latest: boolean;
272
+ record?: StoredRecord | null;
273
+ diff?: Map<string, CID | null>;
274
+ }>;
193
275
  /** check if the repo already exists (head resolves) */
194
276
  repoExists(publisher: Address, repo: RepoName): Promise<boolean>;
195
277
  /** Lists every record currently committed under a repo, resolved from the on-chain root. */
@@ -198,9 +280,9 @@ declare class FangornEngine {
198
280
  listAt(head: CID | null): Promise<RepoContents>;
199
281
  /**
200
282
  * 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.
283
+ * on-chain root, then the record block. Null if the repo has no such id, or no commits.
202
284
  */
203
285
  readRecord(publisher: Address, repo: RepoName, id: string): Promise<StoredRecord | null>;
204
286
  }
205
287
  //#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 };
288
+ export { CHECKPOINT_EVERY, CommitDiff, CommitObject, CreateCommitOptions, FangornEngine, MAX_REPO_NAME_LENGTH, RecordInput, RecordType, type Ref, RepoContents, RepoDiff, RepoName, SignedUpdate, type Stitch, StoredRecord, assertValidRepoName, cidFromDigest, commitHead, commitUpdate, fileCid, rootHexFromCid };