@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.
package/lib/fangorn.js CHANGED
@@ -5,9 +5,9 @@ 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
- import { createPublicClient, createWalletClient, http } from "viem";
10
+ import { createPublicClient, createWalletClient, http, toHex } from "viem";
11
11
  import { privateKeyToAccount } from "viem/accounts";
12
12
  import { CID } from "multiformats/cid";
13
13
 
@@ -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 {
@@ -426,6 +433,46 @@ var Fangorn = class Fangorn {
426
433
  async show(commitCid) {
427
434
  return this.engine.diffCommit(CID.parse(commitCid));
428
435
  }
436
+ /** A stitch (WHITEPAPER_1 §4) to the current head of a repo, at `key` if given. */
437
+ stitchTo(publisher, repo, key) {
438
+ return this.engine.stitchTo(publisher, repo, key);
439
+ }
440
+ /** Check a stitch against the registry, and resolve what it names. */
441
+ checkStitch(s) {
442
+ return this.engine.checkStitch(s, this.ctx.config.fromBlock);
443
+ }
444
+ /**
445
+ * Build or update a stitch across the repos `patterns` match (see `stitchFilter`),
446
+ * from the update log. Pass the previous stitch to update it. Returns the stitch's CID.
447
+ */
448
+ async restitch(patterns, prev) {
449
+ return (await this.engine.restitch(prev ? CID.parse(prev) : null, stitchFilter(patterns), this.ctx.config.fromBlock)).toString();
450
+ }
451
+ /** A stitch's tree root, and the log it was folded from: n entries, with root `logRoot`. */
452
+ async readStitch(stitch) {
453
+ const s = await this.engine.readStitch(CID.parse(stitch));
454
+ return {
455
+ root: s.root.toString(),
456
+ n: s.n,
457
+ logRoot: s.logRoot
458
+ };
459
+ }
460
+ /** Check a stitch against the contract's log root, rebuilding it under the same patterns. */
461
+ verifyStitch(stitch, patterns) {
462
+ return this.engine.verifyStitch(CID.parse(stitch), stitchFilter(patterns), this.ctx.config.fromBlock);
463
+ }
464
+ /** The head commit a stitch holds for a repo, or null if it doesn't include it. */
465
+ async stitchedHead(stitch, publisher, repo) {
466
+ return (await this.engine.stitchedHead(CID.parse(stitch), publisher, repo))?.toString() ?? null;
467
+ }
468
+ /** Every repo a stitch holds, at its head (the on-chain digest, as `repoDiff` takes it). */
469
+ async stitchHeads(stitch) {
470
+ return (await this.engine.stitchHeads(CID.parse(stitch))).map((h) => ({
471
+ publisher: h.publisher,
472
+ repo: h.repo,
473
+ head: toHex(h.head.multihash.digest)
474
+ }));
475
+ }
429
476
  /**
430
477
  * Lists every record currently committed under a repo, resolved
431
478
  * from the publisher's on-chain root — useful for verifying what actually
@@ -637,6 +684,27 @@ var Fangorn = class Fangorn {
637
684
  return address;
638
685
  }
639
686
  };
687
+ /**
688
+ * Which repos a stitch covers. A pattern is `publisher/repo`, a repo name (every
689
+ * publisher's), `*` (every repo), or `/regex/` matched against `publisher/repo`
690
+ * (publisher lowercased).
691
+ */
692
+ function stitchFilter(patterns) {
693
+ const tests = patterns.map((p) => {
694
+ if (p === "*") return () => true;
695
+ if (p.length > 2 && p.startsWith("/") && p.endsWith("/")) {
696
+ const re = new RegExp(p.slice(1, -1));
697
+ return (id) => re.test(id);
698
+ }
699
+ const i = p.indexOf("/");
700
+ const want = i < 0 ? null : `${p.slice(0, i).toLowerCase()}${p.slice(i)}`;
701
+ return (id, repo) => want ? id === want : repo === p;
702
+ });
703
+ return (publisher, repo) => {
704
+ const id = `${publisher.toLowerCase()}/${repo}`;
705
+ return tests.some((t) => t(id, repo));
706
+ };
707
+ }
640
708
 
641
709
  //#endregion
642
- export { CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn };
710
+ export { CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn, stitchFilter };
package/lib/index.d.ts CHANGED
@@ -3,15 +3,18 @@ import { ChainRegistry, ChainRegistryConfig, CommitUpdate, EPOCH_SECONDS, LogFil
3
3
  import { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
4
4
  import { RegisterArgs, SettleArgs, SettlementPayment, SettlementRegistryClient, TERMS_TYPES, Terms, TermsJson, WHOLE_REPO, recordKey, registerNonce, settlementDomain, subjectOf, termsFromJson, termsToJson } from "./contracts/settlement-registry/index.js";
5
5
  import { SETTLEMENT_REGISTRY_ABI } from "./contracts/settlement-registry/abi.js";
6
+ import { EMPTY_MMR, Mmr, logLeaf, mmrAppend, mmrRoot } from "./contracts/data-registry/mmr.js";
6
7
  import "./contracts/index.js";
8
+ import { Ref, Stitch } from "./engine/records.js";
9
+ import "./engine/index.js";
7
10
  import { ArbitrumSepoliaConfig, BaseSepoliaConfig, FangornConfig, NetworkConfig, SupportedNetworks, nonBlank } from "./config.js";
8
11
  import { FangornContext, FangornCreateOptions, StorageConfig } from "./types/index.js";
9
12
  import { CommitFeed } from "./feed.js";
10
- import { AgentCard, CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn, RepoChange, SubscribeOptions } from "./fangorn.js";
13
+ import { AgentCard, CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn, RepoChange, SubscribeOptions, stitchFilter } from "./fangorn.js";
11
14
  import { SellOptions, sealRecords } from "./cli/sell.js";
12
15
  import { AccessSigner, GADGET_SELF_HKDF_V1, X25519_PUBKEY_LENGTH, seal, sealSelf, unseal, unsealSelf } from "./crypto/encryption.js";
13
16
  import { AccessRequest, Deposit, FieldHandle, GADGET_FIELD_V1, PaidScope, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement } from "./crypto/paid.js";
14
17
  import { PinataBackend } from "./providers/storage/pinata.js";
15
18
  import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./providers/storage/signed-url.js";
16
19
  import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
17
- export { AccessRequest, AccessSigner, AgentCard, ArbitrumSepoliaConfig, BaseSepoliaConfig, CARD_RECORD, ChainRegistry, ChainRegistryConfig, CommitFeed, CommitUpdate, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, Deposit, EPOCH_SECONDS, FANGORN_REPO_EXTENSION, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FieldHandle, GADGET_FIELD_V1, GADGET_SELF_HKDF_V1, LogFilter, MAX_UPLOAD_ATTEMPTS, NetworkConfig, PaidScope, PinataBackend, PreparedTx, RegisterArgs, Registry, RepoChange, RepoRef, SETTLEMENT_REGISTRY_ABI, SellOptions, SettleArgs, SettlementPayment, SettlementRegistryClient, SignedUrlBackend, SignedUrlSigner, StorageConfig, SubscribeOptions, SupportedNetworks, TERMS_TYPES, Terms, TermsJson, UPDATE_TYPES, UpdateEntry, WHOLE_REPO, WINDOW, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessage, buildAccessRequest, dataDomain, decryptField, deriveRecordKey, deserialize, encryptField, epochOf, fetchRawByCid, isTransientUpload, makeDeposit, newRepoKey, nonBlank, openField, recordKey, registerNonce, repoId, requestKey, retrieveByCid, seal, sealField, sealRecords, sealSelf, serialize, settlementDomain, statement, subjectOf, termsFromJson, termsToJson, unseal, unsealSelf, updateMessage, withUploadRetry };
20
+ export { AccessRequest, AccessSigner, AgentCard, ArbitrumSepoliaConfig, BaseSepoliaConfig, CARD_RECORD, ChainRegistry, ChainRegistryConfig, CommitFeed, CommitUpdate, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, Deposit, EMPTY_MMR, EPOCH_SECONDS, FANGORN_REPO_EXTENSION, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FieldHandle, GADGET_FIELD_V1, GADGET_SELF_HKDF_V1, LogFilter, MAX_UPLOAD_ATTEMPTS, Mmr, NetworkConfig, PaidScope, PinataBackend, PreparedTx, type Ref, RegisterArgs, Registry, RepoChange, RepoRef, SETTLEMENT_REGISTRY_ABI, SellOptions, SettleArgs, SettlementPayment, SettlementRegistryClient, SignedUrlBackend, SignedUrlSigner, type Stitch, StorageConfig, SubscribeOptions, SupportedNetworks, TERMS_TYPES, Terms, TermsJson, UPDATE_TYPES, UpdateEntry, WHOLE_REPO, WINDOW, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessage, buildAccessRequest, dataDomain, decryptField, deriveRecordKey, deserialize, encryptField, epochOf, fetchRawByCid, isTransientUpload, logLeaf, makeDeposit, mmrAppend, mmrRoot, newRepoKey, nonBlank, openField, recordKey, registerNonce, repoId, requestKey, retrieveByCid, seal, sealField, sealRecords, sealSelf, serialize, settlementDomain, statement, stitchFilter, subjectOf, termsFromJson, termsToJson, unseal, unsealSelf, updateMessage, withUploadRetry };
package/lib/index.js CHANGED
@@ -6,11 +6,12 @@ import { DATA_REGISTRY_ABI } from "./contracts/data-registry/abi.js";
6
6
  import { ChainRegistry, EPOCH_SECONDS, UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, repoId, updateMessage } from "./contracts/data-registry/index.js";
7
7
  import { SETTLEMENT_REGISTRY_ABI } from "./contracts/settlement-registry/abi.js";
8
8
  import { SettlementRegistryClient, TERMS_TYPES, WHOLE_REPO, recordKey, registerNonce, settlementDomain, subjectOf, termsFromJson, termsToJson } from "./contracts/settlement-registry/index.js";
9
+ import { EMPTY_MMR, logLeaf, mmrAppend, mmrRoot } from "./contracts/data-registry/mmr.js";
9
10
  import "./contracts/index.js";
10
11
  import { CommitFeed } from "./feed.js";
11
- import { CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn } from "./fangorn.js";
12
+ import { CARD_RECORD, FANGORN_REPO_EXTENSION, Fangorn, stitchFilter } from "./fangorn.js";
12
13
  import { GADGET_SELF_HKDF_V1, X25519_PUBKEY_LENGTH, seal, sealSelf, unseal, unsealSelf } from "./crypto/encryption.js";
13
14
  import { GADGET_FIELD_V1, accessMessage, buildAccessRequest, decryptField, deriveRecordKey, encryptField, makeDeposit, newRepoKey, openField, requestKey, sealField, statement } from "./crypto/paid.js";
14
15
  import { sealRecords } from "./cli/sell.js";
15
16
 
16
- export { ArbitrumSepoliaConfig, BaseSepoliaConfig, CARD_RECORD, ChainRegistry, CommitFeed, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, EPOCH_SECONDS, FANGORN_REPO_EXTENSION, Fangorn, FangornConfig, GADGET_FIELD_V1, GADGET_SELF_HKDF_V1, MAX_UPLOAD_ATTEMPTS, PinataBackend, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, SignedUrlBackend, SupportedNetworks, TERMS_TYPES, UPDATE_TYPES, WHOLE_REPO, WINDOW, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessage, buildAccessRequest, dataDomain, decryptField, deriveRecordKey, deserialize, encryptField, epochOf, fetchRawByCid, isTransientUpload, makeDeposit, newRepoKey, nonBlank, openField, recordKey, registerNonce, repoId, requestKey, retrieveByCid, seal, sealField, sealRecords, sealSelf, serialize, settlementDomain, statement, subjectOf, termsFromJson, termsToJson, unseal, unsealSelf, updateMessage, withUploadRetry };
17
+ export { ArbitrumSepoliaConfig, BaseSepoliaConfig, CARD_RECORD, ChainRegistry, CommitFeed, DATA_REGISTRY_ABI, DEFAULT_SIGNED_URL_WORKER, EMPTY_MMR, EPOCH_SECONDS, FANGORN_REPO_EXTENSION, Fangorn, FangornConfig, GADGET_FIELD_V1, GADGET_SELF_HKDF_V1, MAX_UPLOAD_ATTEMPTS, PinataBackend, SETTLEMENT_REGISTRY_ABI, SettlementRegistryClient, SignedUrlBackend, SupportedNetworks, TERMS_TYPES, UPDATE_TYPES, WHOLE_REPO, WINDOW, X25519_PUBKEY_LENGTH, ZERO_HEAD, accessMessage, buildAccessRequest, dataDomain, decryptField, deriveRecordKey, deserialize, encryptField, epochOf, fetchRawByCid, isTransientUpload, logLeaf, makeDeposit, mmrAppend, mmrRoot, newRepoKey, nonBlank, openField, recordKey, registerNonce, repoId, requestKey, retrieveByCid, seal, sealField, sealRecords, sealSelf, serialize, settlementDomain, statement, stitchFilter, subjectOf, termsFromJson, termsToJson, unseal, unsealSelf, updateMessage, withUploadRetry };
@@ -1,12 +1,14 @@
1
1
  import { PreparedTx } from "../contracts/write.js";
2
2
  import { CommitUpdate, LogFilter, Registry, RepoRef, UpdateEntry } from "../contracts/data-registry/index.js";
3
+ import { Mmr } from "../contracts/data-registry/mmr.js";
3
4
  import "../contracts/index.js";
4
- import * as viem5999 from "viem";
5
+ import "../index.js";
6
+ import * as viem5837 from "viem";
5
7
  import { Address, Hash, Hex, LocalAccount } from "viem";
6
8
 
7
9
  //#region src/test/mem-registry.d.ts
8
10
  /** The EIP-712 domain a MemRegistry signs under. */
9
- declare const MEM_DOMAIN: viem5999.TypedDataDomain;
11
+ declare const MEM_DOMAIN: viem5837.TypedDataDomain;
10
12
  /** One ordering and the registry state over it, shared by every signer of a MemRegistry. */
11
13
  declare class MemLedger {
12
14
  /** H: position and head */
@@ -19,6 +21,9 @@ declare class MemLedger {
19
21
  /** The clock: one tick per entry of the ordering. */
20
22
  t: bigint;
21
23
  listeners: Set<(entry: UpdateEntry) => void>;
24
+ /** The contract's log root after each tick, fixed once written (like chain state). */
25
+ mmr: Mmr;
26
+ logRoots: `0x${string}`[];
22
27
  append(entry: Omit<UpdateEntry, "t" | "id">): void;
23
28
  }
24
29
  /**
@@ -33,11 +38,16 @@ declare class MemRegistry implements Registry {
33
38
  constructor(signer: Address, ledger?: MemLedger, now?: () => number, account?: LocalAccount | undefined);
34
39
  epoch(): Promise<number>;
35
40
  head(ref: RepoRef): Promise<Hex>;
41
+ headAt(ref: RepoRef): Promise<{
42
+ pos: number;
43
+ head: Hex;
44
+ }>;
36
45
  update(u: CommitUpdate): Promise<Hash>;
37
46
  signUpdate(u: CommitUpdate): Promise<Hex>;
38
47
  updateBySig(publisher: Address, u: CommitUpdate, signature: Hex): Promise<Hash>;
39
48
  private apply;
40
49
  prepareUpdate(): Promise<PreparedTx>;
50
+ logRoot(at?: bigint): Promise<Hex>;
41
51
  log(filter: LogFilter, from: bigint, to?: bigint): Promise<UpdateEntry[]>;
42
52
  watch(filter: LogFilter, onEntry: (entry: UpdateEntry) => void): () => void;
43
53
  clock(): Promise<bigint>;
@@ -1,4 +1,5 @@
1
1
  import { UPDATE_TYPES, WINDOW, ZERO_HEAD, dataDomain, epochOf, updateMessage } from "../contracts/data-registry/index.js";
2
+ import { EMPTY_MMR, logLeaf, mmrAppend, mmrRoot } from "../contracts/data-registry/mmr.js";
2
3
  import "../contracts/index.js";
3
4
  import { commitHead } from "../engine/index.js";
4
5
  import { verifyTypedData } from "viem";
@@ -16,6 +17,9 @@ var MemLedger = class {
16
17
  /** The clock: one tick per entry of the ordering. */
17
18
  t = 0n;
18
19
  listeners = /* @__PURE__ */ new Set();
20
+ /** The contract's log root after each tick, fixed once written (like chain state). */
21
+ mmr = EMPTY_MMR;
22
+ logRoots = [mmrRoot(EMPTY_MMR)];
19
23
  append(entry) {
20
24
  this.t++;
21
25
  const e = {
@@ -24,6 +28,8 @@ var MemLedger = class {
24
28
  id: this.entries.length.toString()
25
29
  };
26
30
  this.entries.push(e);
31
+ this.mmr = mmrAppend(this.mmr, logLeaf(e));
32
+ this.logRoots.push(mmrRoot(this.mmr));
27
33
  for (const listener of this.listeners) listener(e);
28
34
  }
29
35
  };
@@ -45,6 +51,12 @@ var MemRegistry = class {
45
51
  head(ref) {
46
52
  return Promise.resolve(this.ledger.heads.get(refKey(ref))?.head ?? ZERO_HEAD);
47
53
  }
54
+ headAt(ref) {
55
+ return Promise.resolve(this.ledger.heads.get(refKey(ref)) ?? {
56
+ pos: 0,
57
+ head: ZERO_HEAD
58
+ });
59
+ }
48
60
  update(u) {
49
61
  return this.apply(this.signer, u);
50
62
  }
@@ -95,6 +107,9 @@ var MemRegistry = class {
95
107
  prepareUpdate() {
96
108
  return Promise.reject(/* @__PURE__ */ new Error("MemRegistry has no transactions to prepare"));
97
109
  }
110
+ logRoot(at = this.ledger.t) {
111
+ return Promise.resolve(this.ledger.logRoots[Number(at)]);
112
+ }
98
113
  log(filter, from, to) {
99
114
  return Promise.resolve(this.ledger.entries.filter((e) => e.t >= from && (to === void 0 || e.t <= to) && matches(filter, e)));
100
115
  }