@fangorn-network/sdk 0.1.5 → 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.
@@ -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 };
@@ -46,6 +46,11 @@ interface RepoDiff {
46
46
  * rejecting garbage input early.
47
47
  */
48
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;
49
54
  /**
50
55
  * The root of the graph, committed to IPFS, as hex
51
56
  */
@@ -93,6 +98,13 @@ interface CreateCommitOptions {
93
98
  * deletes apply on top of the parent state.
94
99
  */
95
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;
96
108
  }
97
109
  declare class FangornEngine {
98
110
  private storage;
@@ -268,9 +280,9 @@ declare class FangornEngine {
268
280
  listAt(head: CID | null): Promise<RepoContents>;
269
281
  /**
270
282
  * Fetch the current version of one record by id — one MST path from the
271
- * 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.
272
284
  */
273
285
  readRecord(publisher: Address, repo: RepoName, id: string): Promise<StoredRecord | null>;
274
286
  }
275
287
  //#endregion
276
- export { 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 };
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 };
@@ -18,6 +18,11 @@ const ZERO_BYTES32 = ZERO_HEAD;
18
18
  */
19
19
  const MAX_REPO_NAME_LENGTH = 256;
20
20
  /**
21
+ * Every this many positions, a commit's CAR holds the whole state (see `checkpoint`), so a
22
+ * cold read walks back at most this many CARs (~2 fetches each: under Workers' 1000 subrequests).
23
+ */
24
+ const CHECKPOINT_EVERY = 100;
25
+ /**
21
26
  * The root of the graph, committed to IPFS, as hex
22
27
  */
23
28
  function rootHexFromCid(commitCid) {
@@ -230,7 +235,14 @@ var FangornEngine = class {
230
235
  });
231
236
  state.set(id, block.cid);
232
237
  recordCids[id] = block.cid.toString();
233
- if (!oldRecordCids.has(block.cid.toString())) carBlocks.push(block);
238
+ if (opts.checkpoint || !oldRecordCids.has(block.cid.toString())) carBlocks.push(block);
239
+ }
240
+ if (opts.checkpoint) {
241
+ const staged = new Set(Object.values(recordCids));
242
+ for (const cid of state.values()) if (!staged.has(cid.toString())) carBlocks.push({
243
+ cid,
244
+ bytes: await this.getBlock(cid, base)
245
+ });
234
246
  }
235
247
  const mst = await buildMst(state);
236
248
  const delta = /* @__PURE__ */ new Map();
@@ -240,7 +252,7 @@ var FangornEngine = class {
240
252
  const fresh = /* @__PURE__ */ new Set();
241
253
  for (const node of [...mst.nodes, ...diff.nodes]) {
242
254
  const key = node.cid.toString();
243
- if (!old.nodeCids.has(key) && !fresh.has(key)) {
255
+ if ((opts.checkpoint || !old.nodeCids.has(key)) && !fresh.has(key)) {
244
256
  fresh.add(key);
245
257
  carBlocks.push(node);
246
258
  }
@@ -589,11 +601,11 @@ var FangornEngine = class {
589
601
  }
590
602
  /**
591
603
  * Fetch the current version of one record by id — one MST path from the
592
- * on-chain root, then the record block. Null if the repo has no such id.
604
+ * on-chain root, then the record block. Null if the repo has no such id, or no commits.
593
605
  */
594
606
  async readRecord(publisher, repo, id) {
595
607
  const head = await this.resolveHeadCommit(publisher, repo);
596
- if (!head) throw new Error(`publisher ${publisher} has no on-chain commits in repo ${repo}`);
608
+ if (!head) return null;
597
609
  const get = (cid$1) => this.getBlock(cid$1, head);
598
610
  const cid = await lookupMst((await this.getCommit(head)).root, id, get);
599
611
  return cid ? this.decodeRecord(id, cid, head) : null;
@@ -601,4 +613,4 @@ var FangornEngine = class {
601
613
  };
602
614
 
603
615
  //#endregion
604
- export { FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, cidFromDigest, commitHead, commitUpdate, fileCid, rootHexFromCid };
616
+ export { CHECKPOINT_EVERY, FangornEngine, MAX_REPO_NAME_LENGTH, assertValidRepoName, cidFromDigest, commitHead, commitUpdate, fileCid, rootHexFromCid };
package/lib/erc8004.js CHANGED
@@ -116,7 +116,8 @@ async function setAgentFile(c, agentId, file) {
116
116
  chain: c.chain,
117
117
  account: c.walletClient.account ?? null
118
118
  });
119
- await c.publicClient.waitForTransactionReceipt({ hash });
119
+ const { status } = await c.publicClient.waitForTransactionReceipt({ hash });
120
+ if (status !== "success") throw new Error(`setAgentURI reverted in tx ${hash}`);
120
121
  return hash;
121
122
  }
122
123
  /** Mint an agent with no URI yet, and return its id. */
package/lib/fangorn.d.ts CHANGED
@@ -91,7 +91,7 @@ declare class Fangorn {
91
91
  txHash: Hash;
92
92
  onChainTip: CID;
93
93
  }>;
94
- /** Stage records into one commit on top of `base`. */
94
+ /** Stage records into one commit on top of `base`, a checkpoint every CHECKPOINT_EVERY positions. */
95
95
  private createCommit;
96
96
  /**
97
97
  * Allocates a repo in the publisher's root map.
package/lib/fangorn.js CHANGED
@@ -5,7 +5,7 @@ import { PinataBackend } from "./providers/storage/pinata.js";
5
5
  import { ChainRegistry, ZERO_HEAD } from "./contracts/data-registry/index.js";
6
6
  import { SettlementRegistryClient } from "./contracts/settlement-registry/index.js";
7
7
  import "./contracts/index.js";
8
- import { FangornEngine, assertValidRepoName, commitUpdate, rootHexFromCid } from "./engine/index.js";
8
+ import { CHECKPOINT_EVERY, FangornEngine, assertValidRepoName, commitUpdate, rootHexFromCid } from "./engine/index.js";
9
9
  import { CommitFeed } from "./feed.js";
10
10
  import { createPublicClient, createWalletClient, http, toHex } from "viem";
11
11
  import { privateKeyToAccount } from "viem/accounts";
@@ -109,11 +109,17 @@ var Fangorn = class Fangorn {
109
109
  });
110
110
  return this.engine.pushCommit(publisher, repo, commitCid);
111
111
  }
112
- /** Stage records into one commit on top of `base`. */
113
- createCommit(opts) {
112
+ /** Stage records into one commit on top of `base`, a checkpoint every CHECKPOINT_EVERY positions. */
113
+ async createCommit(opts) {
114
+ const { publisher, ...rest } = opts;
115
+ const { pos } = await this.ctx.registry.headAt({
116
+ publisher: publisher ?? this.getAddress(),
117
+ repo: opts.repo
118
+ });
114
119
  return this.engine.createCommit({
115
- ...opts,
116
- records: opts.records.map((r) => ({
120
+ ...rest,
121
+ checkpoint: (pos + 1) % CHECKPOINT_EVERY === 0,
122
+ records: rest.records.map((r) => ({
117
123
  id: r.id,
118
124
  type: r.type,
119
125
  payload: r.payload && typeof r.payload === "object" && !Array.isArray(r.payload) ? r.payload : { value: r.payload }
@@ -246,7 +252,8 @@ var Fangorn = class Fangorn {
246
252
  base: oldRoot === ZERO_BYTES32 ? null : CID.parse(this.engine.commitCidFromRootHex(oldRoot)),
247
253
  records: opts.records ?? [],
248
254
  deletes: opts.deletes,
249
- replace: opts.replace
255
+ replace: opts.replace,
256
+ publisher: opts.owner
250
257
  });
251
258
  const newRoot = rootHexFromCid(commitCid);
252
259
  return {
@@ -3,12 +3,12 @@ import { CommitUpdate, LogFilter, Registry, RepoRef, UpdateEntry } from "../cont
3
3
  import { Mmr } from "../contracts/data-registry/mmr.js";
4
4
  import "../contracts/index.js";
5
5
  import "../index.js";
6
- import * as viem161 from "viem";
6
+ import * as viem5837 from "viem";
7
7
  import { Address, Hash, Hex, LocalAccount } from "viem";
8
8
 
9
9
  //#region src/test/mem-registry.d.ts
10
10
  /** The EIP-712 domain a MemRegistry signs under. */
11
- declare const MEM_DOMAIN: viem161.TypedDataDomain;
11
+ declare const MEM_DOMAIN: viem5837.TypedDataDomain;
12
12
  /** One ordering and the registry state over it, shared by every signer of a MemRegistry. */
13
13
  declare class MemLedger {
14
14
  /** H: position and head */