@fangorn-network/sdk 0.1.6 → 0.2.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 (46) hide show
  1. package/README.md +1 -1
  2. package/lib/cli/cli.js +85 -46
  3. package/lib/cli/index.js +1 -1
  4. package/lib/cli/sell.d.ts +2 -2
  5. package/lib/cli/sell.js +14 -8
  6. package/lib/cli/stage.d.ts +21 -3
  7. package/lib/cli/stage.js +110 -24
  8. package/lib/config.d.ts +481 -155
  9. package/lib/config.js +14 -4
  10. package/lib/contracts/data-registry/abi.d.ts +41 -0
  11. package/lib/contracts/data-registry/abi.js +46 -0
  12. package/lib/contracts/data-registry/index.d.ts +45 -3
  13. package/lib/contracts/data-registry/index.js +69 -14
  14. package/lib/contracts/data-registry/mmr.d.ts +9 -2
  15. package/lib/contracts/data-registry/mmr.js +6 -2
  16. package/lib/contracts/index.d.ts +2 -2
  17. package/lib/contracts/index.js +2 -2
  18. package/lib/contracts/write.d.ts +17 -2
  19. package/lib/contracts/write.js +63 -7
  20. package/lib/crypto/encryption.js +3 -0
  21. package/lib/crypto/paid.d.ts +1 -1
  22. package/lib/crypto/paid.js +4 -1
  23. package/lib/engine/index.d.ts +9 -2
  24. package/lib/engine/index.js +33 -17
  25. package/lib/engine/records.d.ts +9 -1
  26. package/lib/engine/records.js +32 -6
  27. package/lib/erc8004.d.ts +1 -1
  28. package/lib/erc8004.js +12 -5
  29. package/lib/fangorn.d.ts +11 -1
  30. package/lib/fangorn.js +26 -16
  31. package/lib/feed.d.ts +23 -2
  32. package/lib/feed.js +43 -6
  33. package/lib/index.d.ts +3 -3
  34. package/lib/index.js +4 -4
  35. package/lib/providers/storage/index.js +1 -1
  36. package/lib/providers/storage/pinata.js +14 -6
  37. package/lib/providers/storage/signed-url.d.ts +1 -1
  38. package/lib/providers/storage/signed-url.js +23 -9
  39. package/lib/providers/storage/types.d.ts +9 -1
  40. package/lib/providers/storage/types.js +54 -1
  41. package/lib/providers/storage/utils.d.ts +3 -1
  42. package/lib/providers/storage/utils.js +3 -3
  43. package/lib/test/mem-registry.d.ts +3 -3
  44. package/lib/test/mem-registry.js +7 -5
  45. package/lib/test/testbed.d.ts +5230 -5230
  46. package/package.json +6 -3
package/lib/config.js CHANGED
@@ -1,4 +1,4 @@
1
- import { arbitrumSepolia, baseSepolia } from "viem/chains";
1
+ import { arbitrumSepolia, base, baseSepolia } from "viem/chains";
2
2
 
3
3
  //#region src/config.ts
4
4
  /**
@@ -34,6 +34,15 @@ const ArbitrumSepoliaConfig = {
34
34
  signedUrlWorker: "https://arbitrum-sepolia.storage-worker.fangorn.network",
35
35
  keyServer: "https://arbitrum-sepolia.keys-test.fangorn.network"
36
36
  };
37
+ const BaseConfig = {
38
+ dataRegistryContractAddress: "0x543D559Cf7583FE7003d4A19E26BF3A4DB75fbC8",
39
+ fromBlock: 59598762n,
40
+ chain: base,
41
+ rpcUrl: "https://base-rpc.publicnode.com",
42
+ caip2: 8453,
43
+ ipfsGateway: "https://ipfs-test.fangorn.network",
44
+ logWindow: 50000n
45
+ };
37
46
  /**
38
47
  * The default network: what `Fangorn.create` uses without a `config`, and the CLI
39
48
  * without `CHAIN_NAME`. Base Sepolia; Arbitrum Sepolia runs the same contracts.
@@ -44,10 +53,11 @@ const FangornConfig = BaseSepoliaConfig;
44
53
  */
45
54
  const SupportedNetworks = {
46
55
  baseSepolia: BaseSepoliaConfig,
47
- arbitrumSepolia: ArbitrumSepoliaConfig
56
+ arbitrumSepolia: ArbitrumSepoliaConfig,
57
+ base: BaseConfig
48
58
  };
49
59
  /**
50
- * Get a network's deployment by name ("baseSepolia" or "arbitrumSepolia").
60
+ * Get a network's deployment by name ("baseSepolia", "arbitrumSepolia" or "base").
51
61
  * @returns The corresponding config if it is supported, otherwise an error
52
62
  */
53
63
  function getNetwork(name) {
@@ -57,4 +67,4 @@ function getNetwork(name) {
57
67
  }
58
68
 
59
69
  //#endregion
60
- export { ArbitrumSepoliaConfig, BaseSepoliaConfig, FangornConfig, SupportedNetworks, getNetwork as default, nonBlank };
70
+ export { ArbitrumSepoliaConfig, BaseConfig, BaseSepoliaConfig, FangornConfig, SupportedNetworks, getNetwork as default, nonBlank };
@@ -47,6 +47,12 @@ declare const DATA_REGISTRY_ABI: readonly [{
47
47
  readonly internalType: "uint64";
48
48
  }];
49
49
  readonly stateMutability: "view";
50
+ }, {
51
+ readonly type: "function";
52
+ readonly name: "acceptAdmin";
53
+ readonly inputs: readonly [];
54
+ readonly outputs: readonly [];
55
+ readonly stateMutability: "nonpayable";
50
56
  }, {
51
57
  readonly type: "function";
52
58
  readonly name: "admin";
@@ -177,6 +183,16 @@ declare const DATA_REGISTRY_ABI: readonly [{
177
183
  readonly internalType: "bytes32";
178
184
  }];
179
185
  readonly stateMutability: "view";
186
+ }, {
187
+ readonly type: "function";
188
+ readonly name: "pendingAdmin";
189
+ readonly inputs: readonly [];
190
+ readonly outputs: readonly [{
191
+ readonly name: "";
192
+ readonly type: "address";
193
+ readonly internalType: "address";
194
+ }];
195
+ readonly stateMutability: "view";
180
196
  }, {
181
197
  readonly type: "function";
182
198
  readonly name: "proxiableUUID";
@@ -334,6 +350,21 @@ declare const DATA_REGISTRY_ABI: readonly [{
334
350
  readonly internalType: "address";
335
351
  }];
336
352
  readonly anonymous: false;
353
+ }, {
354
+ readonly type: "event";
355
+ readonly name: "AdminProposed";
356
+ readonly inputs: readonly [{
357
+ readonly name: "admin";
358
+ readonly type: "address";
359
+ readonly indexed: false;
360
+ readonly internalType: "address";
361
+ }, {
362
+ readonly name: "pending_admin";
363
+ readonly type: "address";
364
+ readonly indexed: false;
365
+ readonly internalType: "address";
366
+ }];
367
+ readonly anonymous: false;
337
368
  }, {
338
369
  readonly type: "event";
339
370
  readonly name: "Initialized";
@@ -377,6 +408,16 @@ declare const DATA_REGISTRY_ABI: readonly [{
377
408
  readonly type: "bytes32";
378
409
  readonly indexed: false;
379
410
  readonly internalType: "bytes32";
411
+ }, {
412
+ readonly name: "index";
413
+ readonly type: "uint64";
414
+ readonly indexed: false;
415
+ readonly internalType: "uint64";
416
+ }, {
417
+ readonly name: "timestamp";
418
+ readonly type: "uint64";
419
+ readonly indexed: false;
420
+ readonly internalType: "uint64";
380
421
  }];
381
422
  readonly anonymous: false;
382
423
  }, {
@@ -53,6 +53,13 @@ const DATA_REGISTRY_ABI = [
53
53
  }],
54
54
  stateMutability: "view"
55
55
  },
56
+ {
57
+ type: "function",
58
+ name: "acceptAdmin",
59
+ inputs: [],
60
+ outputs: [],
61
+ stateMutability: "nonpayable"
62
+ },
56
63
  {
57
64
  type: "function",
58
65
  name: "admin",
@@ -199,6 +206,17 @@ const DATA_REGISTRY_ABI = [
199
206
  }],
200
207
  stateMutability: "view"
201
208
  },
209
+ {
210
+ type: "function",
211
+ name: "pendingAdmin",
212
+ inputs: [],
213
+ outputs: [{
214
+ name: "",
215
+ type: "address",
216
+ internalType: "address"
217
+ }],
218
+ stateMutability: "view"
219
+ },
202
220
  {
203
221
  type: "function",
204
222
  name: "proxiableUUID",
@@ -380,6 +398,22 @@ const DATA_REGISTRY_ABI = [
380
398
  }],
381
399
  anonymous: false
382
400
  },
401
+ {
402
+ type: "event",
403
+ name: "AdminProposed",
404
+ inputs: [{
405
+ name: "admin",
406
+ type: "address",
407
+ indexed: false,
408
+ internalType: "address"
409
+ }, {
410
+ name: "pending_admin",
411
+ type: "address",
412
+ indexed: false,
413
+ internalType: "address"
414
+ }],
415
+ anonymous: false
416
+ },
383
417
  {
384
418
  type: "event",
385
419
  name: "Initialized",
@@ -430,6 +464,18 @@ const DATA_REGISTRY_ABI = [
430
464
  type: "bytes32",
431
465
  indexed: false,
432
466
  internalType: "bytes32"
467
+ },
468
+ {
469
+ name: "index",
470
+ type: "uint64",
471
+ indexed: false,
472
+ internalType: "uint64"
473
+ },
474
+ {
475
+ name: "timestamp",
476
+ type: "uint64",
477
+ indexed: false,
478
+ internalType: "uint64"
433
479
  }
434
480
  ],
435
481
  anonymous: false
@@ -74,8 +74,12 @@ interface UpdateEntry {
74
74
  t: bigint;
75
75
  /** That block's timestamp: the `t` of the paper's entry, and what the contract's log leaf hashes. */
76
76
  timestamp: bigint;
77
+ /** The entry's position in the whole log (every repo), from 0. Absent on pre-upgrade (V0) logs. */
78
+ index?: bigint;
77
79
  /** Unique per entry, for de-duplication across catch-up and live. */
78
80
  id: string;
81
+ /** The event's indexed repo id, where the entry came from one (the contract hashes the raw name). */
82
+ repoId?: Hex;
79
83
  }
80
84
  /** A slice of the update log: every repo, one publisher's, one repo name across publishers, or one repo. */
81
85
  interface LogFilter {
@@ -137,13 +141,51 @@ declare class ChainRegistry implements Registry {
137
141
  signUpdate(u: CommitUpdate): Promise<Hex>;
138
142
  updateBySig(publisher: Address, u: CommitUpdate, signature: Hex): Promise<Hash>;
139
143
  private write;
140
- /** U's `Updated` events, narrowed on-chain by publisher and repo. */
144
+ /** U's `Updated` events of one version, narrowed on-chain by publisher and repo. */
141
145
  private source;
142
146
  log(filter: LogFilter, from: bigint, to?: bigint): Promise<UpdateEntry[]>;
143
- /** Logs don't carry their block's timestamp: one block read per distinct block. */
147
+ /**
148
+ * Old-version logs don't carry their block's timestamp: one block read per
149
+ * distinct block. New-version logs carry it.
150
+ */
144
151
  private withTimestamps;
145
152
  watch(filter: LogFilter, onEntry: (entry: UpdateEntry) => void, onError?: (err: Error) => void, pollingInterval?: number): () => void;
146
153
  clock(): Promise<bigint>;
147
154
  }
155
+ /**
156
+ * `Updated` as the contract emitted it before it gained `index` and `timestamp`
157
+ * (contracts 0f178bb). The proxy is upgraded in place, so the log before the
158
+ * upgrade has this topic.
159
+ */
160
+ declare const UPDATED_V0: {
161
+ readonly type: "event";
162
+ readonly name: "Updated";
163
+ readonly anonymous: false;
164
+ readonly inputs: readonly [{
165
+ readonly name: "publisher";
166
+ readonly type: "address";
167
+ readonly indexed: true;
168
+ }, {
169
+ readonly name: "repo_id";
170
+ readonly type: "bytes32";
171
+ readonly indexed: true;
172
+ }, {
173
+ readonly name: "repo";
174
+ readonly type: "string";
175
+ readonly indexed: false;
176
+ }, {
177
+ readonly name: "pos";
178
+ readonly type: "uint64";
179
+ readonly indexed: false;
180
+ }, {
181
+ readonly name: "parent";
182
+ readonly type: "bytes32";
183
+ readonly indexed: false;
184
+ }, {
185
+ readonly name: "head";
186
+ readonly type: "bytes32";
187
+ readonly indexed: false;
188
+ }];
189
+ };
148
190
  //#endregion
149
- export { ChainRegistry, ChainRegistryConfig, CommitUpdate, EPOCH_SECONDS, LogFilter, Registry, RepoRef, UPDATE_TYPES, UpdateEntry, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage };
191
+ export { ChainRegistry, ChainRegistryConfig, CommitUpdate, EPOCH_SECONDS, LogFilter, Registry, RepoRef, UPDATED_V0, UPDATE_TYPES, UpdateEntry, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage };
@@ -1,6 +1,6 @@
1
+ import { prepareWrite, requireWallet, sendWrite } from "../write.js";
1
2
  import { DATA_REGISTRY_ABI } from "./abi.js";
2
3
  import { getLogsInWindows } from "../logs.js";
3
- import { prepareWrite, requireWallet, sendWrite } from "../write.js";
4
4
  import { keccak256, toHex } from "viem";
5
5
 
6
6
  //#region src/contracts/data-registry/index.ts
@@ -129,13 +129,13 @@ var ChainRegistry = class {
129
129
  write(fn, args) {
130
130
  return sendWrite(this.publicClient, requireWallet(this.walletClient, fn), this.data, DATA_REGISTRY_ABI, fn, args);
131
131
  }
132
- /** U's `Updated` events, narrowed on-chain by publisher and repo. */
133
- source(filter) {
132
+ /** U's `Updated` events of one version, narrowed on-chain by publisher and repo. */
133
+ source(filter, event) {
134
134
  const ids = filter.repo === void 0 ? {} : { repo_id: repoId(filter.repo) };
135
135
  const who = filter.publisher === void 0 ? {} : { publisher: filter.publisher };
136
136
  return {
137
137
  address: this.data,
138
- abi: DATA_REGISTRY_ABI,
138
+ abi: [event],
139
139
  eventName: "Updated",
140
140
  args: {
141
141
  ...who,
@@ -144,28 +144,36 @@ var ChainRegistry = class {
144
144
  };
145
145
  }
146
146
  async log(filter, from, to) {
147
- const sorted = (await getLogsInWindows(this.publicClient, from, to, (fromBlock, toBlock) => this.publicClient.getContractEvents({
148
- ...this.source(filter),
147
+ const sorted = (await getLogsInWindows(this.publicClient, from, to, async (fromBlock, toBlock) => (await Promise.all(UPDATED_EVENTS.map((event) => this.publicClient.getContractEvents({
148
+ ...this.source(filter, event),
149
149
  fromBlock,
150
150
  toBlock,
151
151
  strict: true
152
- }), this.logWindow)).sort((a, b) => a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1);
152
+ })))).flat(), this.logWindow)).sort((a, b) => a.blockNumber === b.blockNumber ? a.logIndex - b.logIndex : a.blockNumber < b.blockNumber ? -1 : 1);
153
153
  return this.withTimestamps(sorted);
154
154
  }
155
- /** Logs don't carry their block's timestamp: one block read per distinct block. */
155
+ /**
156
+ * Old-version logs don't carry their block's timestamp: one block read per
157
+ * distinct block. New-version logs carry it.
158
+ */
156
159
  async withTimestamps(logs) {
157
- const blocks = [...new Set(logs.map((l) => l.blockNumber))];
160
+ const blocks = [...new Set(logs.filter((l) => l.args.timestamp === void 0).map((l) => l.blockNumber))];
158
161
  const times = new Map(await Promise.all(blocks.map(async (n) => [n, (await this.publicClient.getBlock({ blockNumber: n })).timestamp])));
159
- return logs.map((l) => toEntry(l, times.get(l.blockNumber) ?? 0n));
162
+ return logs.map((l) => toEntry(l, l.args.timestamp ?? times.get(l.blockNumber) ?? 0n));
160
163
  }
161
164
  watch(filter, onEntry, onError, pollingInterval) {
162
165
  let queue = Promise.resolve();
166
+ const publisher = filter.publisher?.toLowerCase();
167
+ const id = filter.repo === void 0 ? void 0 : repoId(filter.repo);
163
168
  return this.publicClient.watchContractEvent({
164
- ...this.source(filter),
169
+ address: this.data,
170
+ abi: UPDATED_EVENTS,
165
171
  strict: true,
166
172
  pollingInterval,
167
173
  onLogs: (logs) => {
168
- queue = queue.then(() => this.withTimestamps(logs)).then((entries) => {
174
+ const live = logs.filter((l) => !l.removed && l.eventName === "Updated" && (publisher === void 0 || l.args.publisher.toLowerCase() === publisher) && (id === void 0 || l.args.repo_id === id));
175
+ if (!live.length) return;
176
+ queue = queue.then(() => this.withTimestamps(live)).then((entries) => {
169
177
  for (const e of entries) onEntry(e);
170
178
  }).catch((e) => onError?.(e));
171
179
  },
@@ -186,6 +194,51 @@ function updateArgs(u) {
186
194
  u.car
187
195
  ];
188
196
  }
197
+ /** `Updated` as the contract emits it. */
198
+ const UPDATED = DATA_REGISTRY_ABI.find((i) => i.type === "event" && i.name === "Updated");
199
+ /**
200
+ * `Updated` as the contract emitted it before it gained `index` and `timestamp`
201
+ * (contracts 0f178bb). The proxy is upgraded in place, so the log before the
202
+ * upgrade has this topic.
203
+ */
204
+ const UPDATED_V0 = {
205
+ type: "event",
206
+ name: "Updated",
207
+ anonymous: false,
208
+ inputs: [
209
+ {
210
+ name: "publisher",
211
+ type: "address",
212
+ indexed: true
213
+ },
214
+ {
215
+ name: "repo_id",
216
+ type: "bytes32",
217
+ indexed: true
218
+ },
219
+ {
220
+ name: "repo",
221
+ type: "string",
222
+ indexed: false
223
+ },
224
+ {
225
+ name: "pos",
226
+ type: "uint64",
227
+ indexed: false
228
+ },
229
+ {
230
+ name: "parent",
231
+ type: "bytes32",
232
+ indexed: false
233
+ },
234
+ {
235
+ name: "head",
236
+ type: "bytes32",
237
+ indexed: false
238
+ }
239
+ ]
240
+ };
241
+ const UPDATED_EVENTS = [UPDATED_V0, UPDATED];
189
242
  function toEntry(log, timestamp) {
190
243
  return {
191
244
  publisher: log.args.publisher,
@@ -195,9 +248,11 @@ function toEntry(log, timestamp) {
195
248
  head: log.args.head,
196
249
  t: log.blockNumber,
197
250
  timestamp,
198
- id: `${log.transactionHash}:${log.logIndex.toString()}`
251
+ index: log.args.index,
252
+ id: `${log.transactionHash}:${log.logIndex.toString()}`,
253
+ repoId: log.args.repo_id
199
254
  };
200
255
  }
201
256
 
202
257
  //#endregion
203
- export { ChainRegistry, EPOCH_SECONDS, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage };
258
+ export { ChainRegistry, EPOCH_SECONDS, UPDATED_V0, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage };
@@ -2,8 +2,15 @@ import { UpdateEntry } from "./index.js";
2
2
  import { Hex } from "viem";
3
3
 
4
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;
5
+
6
+ /**
7
+ * The leaf the contract appended for one log entry. The contract hashes the repo's raw bytes,
8
+ * which need not be UTF-8: a decoded `repo` with U+FFFD in it re-hashes to another id, so pass
9
+ * the event's indexed `repo_id` as `repoId` where the entry has it.
10
+ */
11
+ declare const logLeaf: (e: UpdateEntry & {
12
+ repoId?: Hex;
13
+ }) => Hex;
7
14
  /** A mountain range as its length and peaks; `peaks[h]` is live where bit h of n is set. */
8
15
  interface Mmr {
9
16
  n: number;
@@ -3,7 +3,11 @@ import { encodeAbiParameters, keccak256, stringToHex, zeroHash } from "viem";
3
3
 
4
4
  //#region src/contracts/data-registry/mmr.ts
5
5
  const tag = (s) => stringToHex(s, { size: 32 });
6
- /** The leaf the contract appended for one log entry. */
6
+ /**
7
+ * The leaf the contract appended for one log entry. The contract hashes the repo's raw bytes,
8
+ * which need not be UTF-8: a decoded `repo` with U+FFFD in it re-hashes to another id, so pass
9
+ * the event's indexed `repo_id` as `repoId` where the entry has it.
10
+ */
7
11
  const logLeaf = (e) => keccak256(encodeAbiParameters([
8
12
  { type: "bytes32" },
9
13
  { type: "address" },
@@ -14,7 +18,7 @@ const logLeaf = (e) => keccak256(encodeAbiParameters([
14
18
  ], [
15
19
  tag("leaf"),
16
20
  e.publisher,
17
- repoId(e.repo),
21
+ e.repoId ?? repoId(e.repo),
18
22
  BigInt(e.pos),
19
23
  e.head,
20
24
  e.timestamp
@@ -1,7 +1,7 @@
1
1
  import { PreparedTx } from "./write.js";
2
- import { ChainRegistry, ChainRegistryConfig, CommitUpdate, EPOCH_SECONDS, LogFilter, Registry, RepoRef, UPDATE_TYPES, UpdateEntry, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./data-registry/index.js";
2
+ import { ChainRegistry, ChainRegistryConfig, CommitUpdate, EPOCH_SECONDS, LogFilter, Registry, RepoRef, UPDATED_V0, UPDATE_TYPES, UpdateEntry, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./data-registry/index.js";
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
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 };
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, UPDATED_V0, UPDATE_TYPES, UpdateEntry, WHOLE_REPO, WINDOW, ZERO_HEAD, dataDomain, epochOf, logLeaf, mmrAppend, mmrRoot, recordKey, registerNonce, repoId, settlementDomain, subjectOf, termsFromJson, termsToJson, updateMessage };
@@ -1,7 +1,7 @@
1
1
  import { DATA_REGISTRY_ABI } from "./data-registry/abi.js";
2
- import { ChainRegistry, EPOCH_SECONDS, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./data-registry/index.js";
2
+ import { ChainRegistry, EPOCH_SECONDS, UPDATED_V0, 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
5
  import { EMPTY_MMR, logLeaf, mmrAppend, mmrRoot } from "./data-registry/mmr.js";
6
6
 
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 };
7
+ export { ChainRegistry, DATA_REGISTRY_ABI, EMPTY_MMR, EPOCH_SECONDS, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, TERMS_TYPES, UPDATED_V0, UPDATE_TYPES, WHOLE_REPO, WINDOW, ZERO_HEAD, dataDomain, epochOf, logLeaf, mmrAppend, mmrRoot, recordKey, registerNonce, repoId, settlementDomain, subjectOf, termsFromJson, termsToJson, updateMessage };
@@ -1,4 +1,4 @@
1
- import { Abi, Address, Hash, Hex, PublicClient, WalletClient } from "viem";
1
+ import { Abi, Address, Hash, Hex, PublicClient, TransactionReceipt, WalletClient } from "viem";
2
2
 
3
3
  //#region src/contracts/write.d.ts
4
4
 
@@ -42,6 +42,21 @@ interface PreparedTx {
42
42
  */
43
43
  declare const APPEND_ALLOWANCE = 200000n;
44
44
  declare function sendWrite(publicClient: PublicClient, walletClient: WalletClient, address: Address, abi: Abi, functionName: string, args: readonly unknown[], value?: bigint): Promise<Hash>;
45
+ /**
46
+ * Wait for `hash` to be mined and throw unless it is what took effect.
47
+ *
48
+ * - A mined revert still yields a receipt; without the status check it reads as success.
49
+ * - viem resolves with the REPLACEMENT's receipt when another transaction takes the
50
+ * nonce (a second process on the same key, a wallet "cancel"). That receipt says
51
+ * nothing about this call, so only a reprice (same to, value and data: a wallet
52
+ * speed-up) counts.
53
+ * - A timeout is not a failure: the transaction may still land. Say so, so nobody
54
+ * resends blind (a push resent onto its own landed head reverts as stale).
55
+ */
56
+ declare function confirmTx(publicClient: PublicClient, hash: Hash, what: string, gasLimit?: bigint): Promise<{
57
+ receipt: TransactionReceipt;
58
+ hash: Hash;
59
+ }>;
45
60
  /** Guard for clients that accept a read-only construction. */
46
61
  declare function requireWallet(walletClient: WalletClient | undefined, what: string): WalletClient;
47
62
  /**
@@ -65,4 +80,4 @@ declare function prepareWrite(publicClient: PublicClient, from: Address, address
65
80
  simulate?: boolean;
66
81
  }): Promise<PreparedTx>;
67
82
  //#endregion
68
- export { APPEND_ALLOWANCE, PreparedTx, prepareWrite, requireWallet, sendWrite };
83
+ export { APPEND_ALLOWANCE, PreparedTx, confirmTx, prepareWrite, requireWallet, sendWrite };
@@ -1,4 +1,4 @@
1
- import { encodeFunctionData, toHex } from "viem";
1
+ import { WaitForTransactionReceiptTimeoutError, encodeFunctionData, toHex, zeroAddress } from "viem";
2
2
 
3
3
  //#region src/contracts/write.ts
4
4
  /**
@@ -28,9 +28,24 @@ import { encodeFunctionData, toHex } from "viem";
28
28
  * The contracts repo pins it: test_append_worst_case_fits_sdk_allowance.
29
29
  */
30
30
  const APPEND_ALLOWANCE = 200000n;
31
+ /**
32
+ * writeContract reads the nonce as the node's pending count. Two sends from one key
33
+ * that overlap both read it before either reaches the pool, take the same nonce, and
34
+ * the second is rejected as "replacement transaction underpriced". So sends from one
35
+ * account go one at a time, each only until the node has it (not until it is mined):
36
+ * the next then reads a count that includes it. A failed send leaves no gap, unlike
37
+ * viem's nonceManager, which never gives back a nonce it handed out.
38
+ */
39
+ const sending = /* @__PURE__ */ new Map();
40
+ function oneAtATime(key, f) {
41
+ const run = (sending.get(key) ?? Promise.resolve()).then(f, f);
42
+ sending.set(key, run.catch(() => void 0));
43
+ return run;
44
+ }
31
45
  async function sendWrite(publicClient, walletClient, address, abi, functionName, args, value) {
32
46
  if (!walletClient.chain) throw new Error("Chain required");
33
47
  if (!walletClient.account) throw new Error("Account required");
48
+ assertDeployed(address, functionName);
34
49
  const { chain, account } = walletClient;
35
50
  const fees = await publicClient.estimateFeesPerGas();
36
51
  const limit = await publicClient.estimateContractGas({
@@ -41,7 +56,7 @@ async function sendWrite(publicClient, walletClient, address, abi, functionName,
41
56
  account,
42
57
  value
43
58
  }) * 130n / 100n + APPEND_ALLOWANCE;
44
- const hash = await walletClient.writeContract({
59
+ return (await confirmTx(publicClient, await oneAtATime(`${account.address}.${String(chain.id)}`, () => walletClient.writeContract({
45
60
  address,
46
61
  abi,
47
62
  functionName,
@@ -52,10 +67,50 @@ async function sendWrite(publicClient, walletClient, address, abi, functionName,
52
67
  maxFeePerGas: fees.maxFeePerGas * 3n,
53
68
  maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
54
69
  value
55
- });
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)})`);
58
- return hash;
70
+ })), functionName, limit)).hash;
71
+ }
72
+ /**
73
+ * Wait for `hash` to be mined and throw unless it is what took effect.
74
+ *
75
+ * - A mined revert still yields a receipt; without the status check it reads as success.
76
+ * - viem resolves with the REPLACEMENT's receipt when another transaction takes the
77
+ * nonce (a second process on the same key, a wallet "cancel"). That receipt says
78
+ * nothing about this call, so only a reprice (same to, value and data: a wallet
79
+ * speed-up) counts.
80
+ * - A timeout is not a failure: the transaction may still land. Say so, so nobody
81
+ * resends blind (a push resent onto its own landed head reverts as stale).
82
+ */
83
+ async function confirmTx(publicClient, hash, what, gasLimit) {
84
+ let replaced;
85
+ let receipt;
86
+ try {
87
+ receipt = await publicClient.waitForTransactionReceipt({
88
+ hash,
89
+ onReplaced: (r) => {
90
+ replaced = {
91
+ reason: r.reason,
92
+ hash: r.transactionReceipt.transactionHash
93
+ };
94
+ }
95
+ });
96
+ } catch (err) {
97
+ if (err instanceof WaitForTransactionReceiptTimeoutError) throw new Error(`${what}: tx ${hash} was not confirmed in time. It may still land — re-read the chain before retrying.`, { cause: err });
98
+ throw err;
99
+ }
100
+ if (replaced && replaced.reason !== "repriced") throw new Error(`${what}: tx ${hash} was ${replaced.reason} by tx ${replaced.hash} (another transaction took its nonce); it did not take effect`);
101
+ const mined = replaced?.hash ?? hash;
102
+ if (receipt.status !== "success") throw new Error(`${what} reverted in tx ${mined}` + (gasLimit === void 0 ? "" : ` (gasUsed ${String(receipt.gasUsed)} of ${String(gasLimit)})`));
103
+ return {
104
+ receipt,
105
+ hash: mined
106
+ };
107
+ }
108
+ /**
109
+ * A call to the zero address (an undeployed network's placeholder) runs no code, so
110
+ * it estimates, mines and reports success while doing nothing.
111
+ */
112
+ function assertDeployed(address, functionName) {
113
+ if (address.toLowerCase() === zeroAddress) throw new Error(`${functionName}: the contract address is the zero address — this network's contract is not deployed (or not configured)`);
59
114
  }
60
115
  /** Guard for clients that accept a read-only construction. */
61
116
  function requireWallet(walletClient, what) {
@@ -79,6 +134,7 @@ function requireWallet(walletClient, what) {
79
134
  * approval); `fallbackGas` is then the gas, as it is when the RPC fails.
80
135
  */
81
136
  async function prepareWrite(publicClient, from, address, abi, functionName, args, opts) {
137
+ assertDeployed(address, functionName);
82
138
  const data = encodeFunctionData({
83
139
  abi,
84
140
  functionName,
@@ -109,4 +165,4 @@ async function prepareWrite(publicClient, from, address, abi, functionName, args
109
165
  }
110
166
 
111
167
  //#endregion
112
- export { APPEND_ALLOWANCE, prepareWrite, requireWallet, sendWrite };
168
+ export { APPEND_ALLOWANCE, confirmTx, prepareWrite, requireWallet, sendWrite };
@@ -41,6 +41,9 @@ function seal(plaintext, recipientPubkey, resourceId) {
41
41
  /** Inverse of {@link seal}, with the recipient's secret and the same resourceId. */
42
42
  function unseal(ciphertext, recipientSecret, resourceId) {
43
43
  const ephPub = ciphertext.slice(0, X25519_PUBKEY_LENGTH);
44
+ let u = 0n;
45
+ for (let i = X25519_PUBKEY_LENGTH - 1; i >= 0; i--) u = u << 8n | BigInt(ephPub[i]);
46
+ if (u >= 2n ** 255n - 19n) throw new Error("non-canonical ephemeral public key");
44
47
  const nonce = ciphertext.slice(X25519_PUBKEY_LENGTH, X25519_PUBKEY_LENGTH + GCM_NONCE_LENGTH);
45
48
  const aesCt = ciphertext.slice(X25519_PUBKEY_LENGTH + GCM_NONCE_LENGTH);
46
49
  return aesGcmDecrypt(hkdfSha256(x25519.getSharedSecret(recipientSecret, ephPub), void 0, sealInfo(resourceId), 32), aesCt, nonce);
@@ -70,7 +70,7 @@ declare function sealField(p: {
70
70
  /** `recordKey(id)` */
71
71
  key: Hex;
72
72
  field: string;
73
- storage: Pick<MetadataStorage, "putFile">;
73
+ storage: Pick<MetadataStorage, "putFile"> & Partial<Pick<MetadataStorage, "getRawBlock">>;
74
74
  }): Promise<FieldHandle>;
75
75
  /** What the reader signs (EIP-191, raw): the statement, the key asked for, the reply key and the time. */
76
76
  declare const accessMessage: (stmt: Hex, key: Hex, readerKey: Hex, timestamp: number) => Hex;
@@ -1,3 +1,4 @@
1
+ import { assertStoredFile } from "../providers/storage/types.js";
1
2
  import { GCM_NONCE_LENGTH, aesGcmDecrypt, aesGcmEncrypt } from "./aes.js";
2
3
  import { getRandomValues } from "./rand.js";
3
4
  import { seal, unseal } from "./encryption.js";
@@ -77,11 +78,13 @@ function makeDeposit(p) {
77
78
  async function sealField(p) {
78
79
  const stmt = statement(p.scope);
79
80
  const ct = encryptField(deriveRecordKey(p.kRepo, stmt, p.key), p.plaintext, stmt, p.key, p.field);
81
+ const cid = await p.storage.putFile(ct, `${p.key}.${p.field}`);
82
+ await assertStoredFile(cid, ct, p.storage);
80
83
  return {
81
84
  "@type": "handle",
82
85
  gadget: GADGET_FIELD_V1,
83
86
  generation: p.scope.generation.toString(),
84
- cid: await p.storage.putFile(ct, `${p.key}.${p.field}`)
87
+ cid
85
88
  };
86
89
  }
87
90
  /** What the reader signs (EIP-191, raw): the statement, the key asked for, the reply key and the time. */
@@ -68,7 +68,10 @@ interface SignedUpdate {
68
68
  }
69
69
  /** The CID a storage backend returned for a file, with or without an `ipfs://` prefix. */
70
70
  declare function fileCid(uri: string): CID;
71
- /** Repos must be non-empty strings whose length does not exceed MAX_REPO_NAME_LENGTH */
71
+ /**
72
+ * Repos must be non-empty, well-formed strings whose length does not exceed MAX_REPO_NAME_LENGTH.
73
+ * Well-formed: a lone UTF-16 surrogate encodes as U+FFFD, so two such names would be one repo on chain.
74
+ */
72
75
  declare function assertValidRepoName(repo: RepoName): void;
73
76
  /** One line of a commit's diff against its parent. */
74
77
  interface CommitDiff {
@@ -214,7 +217,11 @@ declare class FangornEngine {
214
217
  * chain or a commit from before diff events, it diffs the two trees (`diffMst`). Either way the
215
218
  * result is the net delta an index builder needs: what to (re)embed, what to evict.
216
219
  */
217
- repoDiff(oldRootHex: string | null, newRootHex: string): Promise<RepoDiff>;
220
+ repoDiff(oldRootHex: string | null, newRootHex: string, {
221
+ useEventDiff
222
+ }?: {
223
+ useEventDiff?: boolean | undefined;
224
+ }): Promise<RepoDiff>;
218
225
  /** Diff a commit against its parent: its event's diff, or two full states for an older commit. */
219
226
  diffCommit(commitCid: CID): Promise<CommitDiff>;
220
227
  /** A stitch to the current head of (publisher, repo), at `key` if given. One `getHead` read, no logs. */