@fangorn-network/sdk 2026.7.24 → 2026.7.28

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,6 +1,9 @@
1
+ import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend } from "./signed-url.js";
1
2
  import { PinataBackend } from "./pinata.js";
3
+ import { CID } from "multiformats/cid";
2
4
 
3
5
  //#region src/providers/storage/utils.ts
6
+ const RAW_CODE = 85;
4
7
  const REVIVERS = [(_key, value) => {
5
8
  if (value !== null && typeof value === "object" && "__type" in value && "data" in value && value.__type === "Uint8Array") return new Uint8Array(Buffer.from(value.data, "base64"));
6
9
  return value;
@@ -24,6 +27,57 @@ function deserialize(text) {
24
27
  return value;
25
28
  });
26
29
  }
30
+ const MAX_UPLOAD_ATTEMPTS = Math.max(1, Number(process.env.PINATA_UPLOAD_RETRIES ?? 6));
31
+ function isTransientUpload(err) {
32
+ const e = err;
33
+ const s = typeof e.statusCode === "number" ? e.statusCode : 0;
34
+ if (s === 408 || s === 425 || s === 429 || s >= 500) return true;
35
+ const m = `${e.code ?? ""} ${e.message ?? ""}`;
36
+ return /HTTP_ERROR|disconnect|timed?\s?out|timeout|ECONN|ETIMEDOUT|EAI_AGAIN|socket hang up|network|fetch failed|terminated|aborted|429|408|50\d/i.test(m);
37
+ }
38
+ async function withUploadRetry(label, fn) {
39
+ for (let attempt = 1;; attempt++) try {
40
+ return await fn();
41
+ } catch (err) {
42
+ if (attempt >= MAX_UPLOAD_ATTEMPTS || !isTransientUpload(err)) throw err;
43
+ const delay = Math.min(3e4, 500 * 2 ** (attempt - 1)) + Math.floor(Math.random() * 500);
44
+ console.warn(` [upload] "${label}" failed (attempt ${attempt.toString()}/${MAX_UPLOAD_ATTEMPTS.toString()}), retrying in ${(delay / 1e3).toFixed(1)}s: ${err.message}`);
45
+ await new Promise((r) => setTimeout(r, delay));
46
+ }
47
+ }
48
+ /**
49
+ * Fetch the exact raw bytes for a CID from a public IPFS gateway (no decoding),
50
+ * retrying to ride out gateway replication lag right after an upload. Blocks
51
+ * written via putBlock() are addressed by their raw-codec (0x55) sibling, so a
52
+ * dag-cbor ("bafyrei…") CID is translated before fetching — the same handling
53
+ * PinataBackend.fetchRaw does, but over a public gateway with no JWT.
54
+ */
55
+ async function fetchRawByCid(cid, gateway = "https://ipfs.io", { retries = 5, timeoutMs = 16e3 } = {}) {
56
+ let fetchCid = cid.replace(/^ipfs:\/\//, "");
57
+ if (fetchCid.startsWith("bafyrei")) try {
58
+ fetchCid = CID.createV1(RAW_CODE, CID.parse(fetchCid).multihash).toString();
59
+ } catch {}
60
+ const base = (gateway || "https://ipfs.io").replace(/\/$/, "");
61
+ const url = `${/^https?:\/\//.test(base) ? base : `https://${base}`}/ipfs/${fetchCid}`;
62
+ let lastError;
63
+ for (let attempt = 0; attempt < retries; attempt++) {
64
+ const controller = new AbortController();
65
+ const timeout = setTimeout(() => {
66
+ controller.abort();
67
+ }, timeoutMs);
68
+ try {
69
+ const res = await fetch(url, { signal: controller.signal });
70
+ if (!res.ok) throw new Error(`HTTP ${res.status.toString()} ${res.statusText}`);
71
+ return new Uint8Array(await res.arrayBuffer());
72
+ } catch (err) {
73
+ lastError = err;
74
+ if (attempt < retries - 1) await new Promise((r) => setTimeout(r, 1e3));
75
+ } finally {
76
+ clearTimeout(timeout);
77
+ }
78
+ }
79
+ throw new Error(`Failed to retrieve ${cid} from ${url} after ${retries.toString()} attempts: ${lastError instanceof Error ? lastError.message : String(lastError)}`);
80
+ }
27
81
  /**
28
82
  * Fetch any content by CID from a public IPFS gateway.
29
83
  * No auth required — all Fangorn content is public; privacy is cryptographic.
@@ -48,4 +102,4 @@ async function retrieveByCid(cid, gateway = "https://ipfs.io", timeoutSecond = 1
48
102
  }
49
103
 
50
104
  //#endregion
51
- export { PinataBackend, deserialize, retrieveByCid, serialize };
105
+ export { DEFAULT_SIGNED_URL_WORKER, MAX_UPLOAD_ATTEMPTS, PinataBackend, SignedUrlBackend, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry };
@@ -6,9 +6,23 @@ import { Hex } from "viem";
6
6
  declare class TestBed {
7
7
  private readonly f_list;
8
8
  private constructor();
9
- static init(sks: Hex[]): TestBed;
9
+ /**
10
+ * @param sks one wallet per publisher in the forest
11
+ * @param appName the app namespace to publish under; defaults to the SDK's
12
+ * own. Pass an unclaimed name to exercise the AppNotFound path.
13
+ */
14
+ static init(sks: Hex[], appName?: string): TestBed;
10
15
  getFangorn(index: number): Fangorn;
11
- resetContractState(index: number): Promise<void>;
16
+ /**
17
+ * Claim the configured app namespace, if nobody has yet.
18
+ *
19
+ * Orthogonal to `register`: an app claims a unique namespace prefix that
20
+ * publishers may write under, while a publisher registers for the right to
21
+ * write at all. Neither implies the other — one app hosts many publishers,
22
+ * and one publisher writes into many apps. Idempotent, and safe when someone
23
+ * else already owns it: apps are shared, not per-test.
24
+ */
25
+ registerApp(index: number): Promise<void>;
12
26
  register(index: number): Promise<void>;
13
27
  initRepo(index: number, name: string): Promise<{
14
28
  cid: undefined;
@@ -39,11 +53,15 @@ declare class TestBed {
39
53
  txHash: `0x${string}`;
40
54
  vertexCids: Record<string, string>;
41
55
  }>;
42
- fetch(index: number, cid: string): Promise<{
56
+ fetch(index: number, cid: string, namespace: string): Promise<{
43
57
  cid: string;
44
58
  schemaId: SchemaID;
45
59
  payload: Record<string, unknown>;
46
60
  }>;
61
+ /** Owner of the configured app namespace, or the zero address if unclaimed. */
62
+ appOwner(index: number): Promise<`0x${string}`>;
63
+ /** The raw on-chain head of one namespace — the slot the CAS actually guards. */
64
+ head(index: number, namespace: string): Promise<`0x${string}`>;
47
65
  inspect(index: number, namespace: string): Promise<NamespaceContents>;
48
66
  }
49
67
  //#endregion
@@ -1,3 +1,4 @@
1
+ import { FangornConfig, appId } from "../config.js";
1
2
  import { Fangorn } from "../fangorn.js";
2
3
 
3
4
  //#region src/test/testbed.ts
@@ -5,11 +6,21 @@ var TestBed = class TestBed {
5
6
  constructor(f_list) {
6
7
  this.f_list = f_list;
7
8
  }
8
- static init(sks) {
9
+ /**
10
+ * @param sks one wallet per publisher in the forest
11
+ * @param appName the app namespace to publish under; defaults to the SDK's
12
+ * own. Pass an unclaimed name to exercise the AppNotFound path.
13
+ */
14
+ static init(sks, appName) {
15
+ const config = appName ? {
16
+ ...FangornConfig,
17
+ appId: appId(appName)
18
+ } : FangornConfig;
9
19
  const f_list = [];
10
20
  sks.forEach((sk) => {
11
21
  f_list.push(Fangorn.create({
12
22
  privateKey: sk,
23
+ config,
13
24
  storage: { pinata: {
14
25
  jwt: process.env.PINATA_JWT ?? "",
15
26
  gateway: process.env.PINATA_GATEWAY ?? ""
@@ -22,10 +33,21 @@ var TestBed = class TestBed {
22
33
  if (index > this.f_list.length) throw new Error("index out of bounds");
23
34
  return this.f_list[index];
24
35
  }
25
- async resetContractState(index) {
26
- const fangorn = this.getFangorn(index);
27
- const currentRoot = await fangorn.getDataRegistry().getNamespaceHead(fangorn.getAddress());
28
- await fangorn.getDataRegistry().commitStateRoot(currentRoot, "0x0000000000000000000000000000000000000000000000000000000000000000");
36
+ /**
37
+ * Claim the configured app namespace, if nobody has yet.
38
+ *
39
+ * Orthogonal to `register`: an app claims a unique namespace prefix that
40
+ * publishers may write under, while a publisher registers for the right to
41
+ * write at all. Neither implies the other — one app hosts many publishers,
42
+ * and one publisher writes into many apps. Idempotent, and safe when someone
43
+ * else already owns it: apps are shared, not per-test.
44
+ */
45
+ async registerApp(index) {
46
+ const registry = this.getFangorn(index).getDataRegistry();
47
+ if (await registry.getAppOwner() === "0x0000000000000000000000000000000000000000") {
48
+ console.log(`Registering app ${registry.getAppId()} on-chain...`);
49
+ await registry.registerApp();
50
+ }
29
51
  }
30
52
  async register(index) {
31
53
  const fangorn = this.getFangorn(index);
@@ -45,9 +67,18 @@ var TestBed = class TestBed {
45
67
  async uploadBatch(index, namespace, vertices, edges = []) {
46
68
  return this.getFangorn(index).uploadBatch(namespace, vertices, edges);
47
69
  }
48
- async fetch(index, cid) {
70
+ async fetch(index, cid, namespace) {
71
+ const fangorn = this.getFangorn(index);
72
+ return fangorn.engine.readVertex(cid, fangorn.getAddress(), namespace);
73
+ }
74
+ /** Owner of the configured app namespace, or the zero address if unclaimed. */
75
+ async appOwner(index) {
76
+ return this.getFangorn(index).getDataRegistry().getAppOwner();
77
+ }
78
+ /** The raw on-chain head of one namespace — the slot the CAS actually guards. */
79
+ async head(index, namespace) {
49
80
  const fangorn = this.getFangorn(index);
50
- return fangorn.engine.readVertex(cid, fangorn.getAddress());
81
+ return fangorn.getDataRegistry().getNamespaceHead(fangorn.getAddress(), namespace);
51
82
  }
52
83
  async inspect(index, namespace) {
53
84
  return this.getFangorn(index).inspectNamespace(namespace);
@@ -16,6 +16,11 @@ type StorageConfig = {
16
16
  jwt: string;
17
17
  gateway: string;
18
18
  };
19
+ } | {
20
+ signedUrl: {
21
+ workerUrl?: string;
22
+ gateway?: string;
23
+ };
19
24
  };
20
25
  interface FangornCreateOptions {
21
26
  storage?: StorageConfig;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fangorn-network/sdk",
3
- "version": "2026.07.24",
3
+ "version": "2026.07.28",
4
4
  "description": "Git for knowledge graphs",
5
5
  "repository": {
6
6
  "type": "git",