@fangorn-network/sdk 0.1.0-dev
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/LICENSE.md +20 -0
- package/README.md +80 -0
- package/lib/cli/cli.d.ts +2 -0
- package/lib/cli/cli.js +571 -0
- package/lib/cli/index.d.ts +10 -0
- package/lib/cli/index.js +18 -0
- package/lib/cli/sell.d.ts +28 -0
- package/lib/cli/sell.js +95 -0
- package/lib/cli/stage.d.ts +19 -0
- package/lib/cli/stage.js +94 -0
- package/lib/config.d.ts +697 -0
- package/lib/config.js +45 -0
- package/lib/contracts/data-registry/abi.d.ts +442 -0
- package/lib/contracts/data-registry/abi.js +508 -0
- package/lib/contracts/data-registry/index.d.ts +131 -0
- package/lib/contracts/data-registry/index.js +183 -0
- package/lib/contracts/index.d.ts +6 -0
- package/lib/contracts/index.js +6 -0
- package/lib/contracts/logs.d.ts +17 -0
- package/lib/contracts/logs.js +28 -0
- package/lib/contracts/settlement-registry/abi.d.ts +810 -0
- package/lib/contracts/settlement-registry/abi.js +962 -0
- package/lib/contracts/settlement-registry/index.d.ts +143 -0
- package/lib/contracts/settlement-registry/index.js +213 -0
- package/lib/contracts/write.d.ts +59 -0
- package/lib/contracts/write.js +102 -0
- package/lib/crypto/aes.d.ts +19 -0
- package/lib/crypto/aes.js +26 -0
- package/lib/crypto/encryption.d.ts +38 -0
- package/lib/crypto/encryption.js +68 -0
- package/lib/crypto/paid.d.ts +104 -0
- package/lib/crypto/paid.js +147 -0
- package/lib/crypto/rand.d.ts +5 -0
- package/lib/crypto/rand.js +16 -0
- package/lib/crypto/types.d.ts +23 -0
- package/lib/crypto/types.js +1 -0
- package/lib/engine/car.d.ts +14 -0
- package/lib/engine/car.js +42 -0
- package/lib/engine/index.d.ts +206 -0
- package/lib/engine/index.js +377 -0
- package/lib/engine/records.d.ts +121 -0
- package/lib/engine/records.js +239 -0
- package/lib/engine/test-helpers.d.ts +38 -0
- package/lib/engine/test-helpers.js +63 -0
- package/lib/erc8004.d.ts +56 -0
- package/lib/erc8004.js +140 -0
- package/lib/fangorn.d.ts +342 -0
- package/lib/fangorn.js +642 -0
- package/lib/feed.d.ts +34 -0
- package/lib/feed.js +67 -0
- package/lib/index.d.ts +17 -0
- package/lib/index.js +16 -0
- package/lib/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.js +77 -0
- package/lib/node_modules/@vitest/expect/dist/index.js +1414 -0
- package/lib/node_modules/@vitest/pretty-format/dist/index.js +858 -0
- package/lib/node_modules/@vitest/runner/dist/chunk-tasks.js +51 -0
- package/lib/node_modules/@vitest/runner/dist/index.js +1199 -0
- package/lib/node_modules/@vitest/runner/dist/utils.js +3 -0
- package/lib/node_modules/@vitest/snapshot/dist/index.js +1075 -0
- package/lib/node_modules/@vitest/spy/dist/index.js +353 -0
- package/lib/node_modules/@vitest/utils/dist/chunk-_commonjsHelpers.js +7 -0
- package/lib/node_modules/@vitest/utils/dist/chunk-pathe.M-eThtNZ.js +81 -0
- package/lib/node_modules/@vitest/utils/dist/diff.js +1345 -0
- package/lib/node_modules/@vitest/utils/dist/display.js +534 -0
- package/lib/node_modules/@vitest/utils/dist/error.js +30 -0
- package/lib/node_modules/@vitest/utils/dist/helpers.js +118 -0
- package/lib/node_modules/@vitest/utils/dist/serialize.js +76 -0
- package/lib/node_modules/@vitest/utils/dist/source-map.js +93 -0
- package/lib/node_modules/@vitest/utils/dist/timers.js +36 -0
- package/lib/node_modules/chai/index.js +2874 -0
- package/lib/node_modules/magic-string/dist/magic-string.es.js +939 -0
- package/lib/node_modules/pathe/dist/shared/pathe.M-eThtNZ.js +81 -0
- package/lib/node_modules/tinyrainbow/dist/index.js +85 -0
- package/lib/node_modules/vitest/dist/chunks/_commonjsHelpers.D26ty3Ew.js +5 -0
- package/lib/node_modules/vitest/dist/chunks/date.Bq6ZW5rf.js +50 -0
- package/lib/node_modules/vitest/dist/chunks/utils.DvEY5TfP.js +44 -0
- package/lib/node_modules/vitest/dist/chunks/vi.2VT5v0um.js +2578 -0
- package/lib/providers/storage/car.d.ts +36 -0
- package/lib/providers/storage/car.js +81 -0
- package/lib/providers/storage/index.d.ts +5 -0
- package/lib/providers/storage/index.js +5 -0
- package/lib/providers/storage/pinata.d.ts +53 -0
- package/lib/providers/storage/pinata.js +178 -0
- package/lib/providers/storage/signed-url.d.ts +54 -0
- package/lib/providers/storage/signed-url.js +122 -0
- package/lib/providers/storage/types.d.ts +62 -0
- package/lib/providers/storage/types.js +1 -0
- package/lib/providers/storage/utils.d.ts +30 -0
- package/lib/providers/storage/utils.js +107 -0
- package/lib/repo/index.d.ts +56 -0
- package/lib/repo/index.js +73 -0
- package/lib/test/key-server.d.ts +12 -0
- package/lib/test/key-server.js +30 -0
- package/lib/test/mem-registry.d.ts +46 -0
- package/lib/test/mem-registry.js +114 -0
- package/lib/test/sdk-suite.d.ts +10 -0
- package/lib/test/sdk-suite.js +155 -0
- package/lib/test/testbed.d.ts +16786 -0
- package/lib/test/testbed.js +175 -0
- package/lib/types/index.d.ts +37 -0
- package/lib/types/index.js +1 -0
- package/package.json +87 -0
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { CID } from "multiformats/cid";
|
|
2
|
+
|
|
3
|
+
//#region src/providers/storage/car.d.ts
|
|
4
|
+
/** Result of packing items into a single CAR. */
|
|
5
|
+
interface PackedCar {
|
|
6
|
+
/** The CAR bytes, ready to upload. */
|
|
7
|
+
bytes: Uint8Array;
|
|
8
|
+
/** Directory root CID — the single root Pinata recursively pins. */
|
|
9
|
+
root: CID;
|
|
10
|
+
/**
|
|
11
|
+
* name → `ipfs://<root>/<name>` path URI. We address chunks by path through
|
|
12
|
+
* the registered root, NOT by bare sub-block CID: a CAR upload registers only
|
|
13
|
+
* the root as a "file", so a Pinata dedicated gateway 403s standalone sub-CIDs
|
|
14
|
+
* but serves `<root>/<name>` (the root + its UnixFS directory entries). The
|
|
15
|
+
* path still resolves deterministically to the file's content.
|
|
16
|
+
*/
|
|
17
|
+
uriByName: Record<string, string>;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Pack named payloads into a SINGLE CAR with a UnixFS directory root.
|
|
21
|
+
*
|
|
22
|
+
* Each item is UnixFS-encoded locally (so its real CID is known without a round
|
|
23
|
+
* trip) and linked under one directory; that directory is the CAR's lone root,
|
|
24
|
+
* so a `.car()` upload recursively pins every file block. Retrieval then uses
|
|
25
|
+
* each item's standalone CID directly — the directory wrapper exists only to
|
|
26
|
+
* give Pinata one thing to pin.
|
|
27
|
+
*
|
|
28
|
+
* Memory is ~2× the packed size (blocks held, then serialized to CAR bytes), so
|
|
29
|
+
* callers must bound how much they hand to one call (see CAR_GROUP_* in publish).
|
|
30
|
+
*/
|
|
31
|
+
declare function packCar(items: {
|
|
32
|
+
data: unknown;
|
|
33
|
+
name: string;
|
|
34
|
+
}[]): Promise<PackedCar>;
|
|
35
|
+
//#endregion
|
|
36
|
+
export { PackedCar, packCar };
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { serialize } from "./utils.js";
|
|
2
|
+
import { CarWriter } from "@ipld/car";
|
|
3
|
+
import * as UnixFS from "@ipld/unixfs";
|
|
4
|
+
|
|
5
|
+
//#region src/providers/storage/car.ts
|
|
6
|
+
const enc = new TextEncoder();
|
|
7
|
+
/** Filenames inside the CAR's UnixFS directory; ':' is legal but we keep it tidy. */
|
|
8
|
+
function sanitize(name) {
|
|
9
|
+
const sanitizeRegex = new RegExp("[/\\x00]", "g");
|
|
10
|
+
return name.replace(sanitizeRegex, "_");
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Pack named payloads into a SINGLE CAR with a UnixFS directory root.
|
|
14
|
+
*
|
|
15
|
+
* Each item is UnixFS-encoded locally (so its real CID is known without a round
|
|
16
|
+
* trip) and linked under one directory; that directory is the CAR's lone root,
|
|
17
|
+
* so a `.car()` upload recursively pins every file block. Retrieval then uses
|
|
18
|
+
* each item's standalone CID directly — the directory wrapper exists only to
|
|
19
|
+
* give Pinata one thing to pin.
|
|
20
|
+
*
|
|
21
|
+
* Memory is ~2× the packed size (blocks held, then serialized to CAR bytes), so
|
|
22
|
+
* callers must bound how much they hand to one call (see CAR_GROUP_* in publish).
|
|
23
|
+
*/
|
|
24
|
+
async function packCar(items) {
|
|
25
|
+
const blocks = [];
|
|
26
|
+
const writable = new WritableStream({ write(b) {
|
|
27
|
+
blocks.push(b);
|
|
28
|
+
} });
|
|
29
|
+
const writer = UnixFS.createWriter({ writable });
|
|
30
|
+
const dir = UnixFS.createDirectoryWriter(writer);
|
|
31
|
+
const dirNames = [];
|
|
32
|
+
for (const { data, name } of items) {
|
|
33
|
+
const bytes$1 = enc.encode(serialize(data));
|
|
34
|
+
const file = UnixFS.createFileWriter(writer);
|
|
35
|
+
await file.write(bytes$1);
|
|
36
|
+
const link = await file.close();
|
|
37
|
+
const entry = sanitize(name);
|
|
38
|
+
dir.set(entry, link);
|
|
39
|
+
dirNames.push({
|
|
40
|
+
name,
|
|
41
|
+
entry
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
const dirLink = await dir.close();
|
|
45
|
+
await writer.close();
|
|
46
|
+
const root = dirLink.cid;
|
|
47
|
+
const bytes = await writeCarBytes(root, blocks);
|
|
48
|
+
const uriByName = {};
|
|
49
|
+
for (const { name, entry } of dirNames) uriByName[name] = `ipfs://${root.toString()}/${entry}`;
|
|
50
|
+
return {
|
|
51
|
+
bytes,
|
|
52
|
+
root,
|
|
53
|
+
uriByName
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
/** Serialize blocks into CAR v1 bytes under a single known root. */
|
|
57
|
+
async function writeCarBytes(root, blocks) {
|
|
58
|
+
const { writer, out } = CarWriter.create([root]);
|
|
59
|
+
const collected = [];
|
|
60
|
+
const sink = (async () => {
|
|
61
|
+
for await (const part of out) collected.push(part);
|
|
62
|
+
})();
|
|
63
|
+
for (let i = 0; i < blocks.length; i++) {
|
|
64
|
+
await writer.put(blocks[i]);
|
|
65
|
+
blocks[i] = void 0;
|
|
66
|
+
}
|
|
67
|
+
await writer.close();
|
|
68
|
+
await sink;
|
|
69
|
+
let total = 0;
|
|
70
|
+
for (const p of collected) total += p.length;
|
|
71
|
+
const buf = new Uint8Array(total);
|
|
72
|
+
let off = 0;
|
|
73
|
+
for (const p of collected) {
|
|
74
|
+
buf.set(p, off);
|
|
75
|
+
off += p.length;
|
|
76
|
+
}
|
|
77
|
+
return buf;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
//#endregion
|
|
81
|
+
export { packCar };
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { MetadataStorage, StorageMeta } from "./types.js";
|
|
2
|
+
import { PinataBackend } from "./pinata.js";
|
|
3
|
+
import { SignedUrlBackend, SignedUrlSigner } from "./signed-url.js";
|
|
4
|
+
import { deserialize, retrieveByCid, serialize } from "./utils.js";
|
|
5
|
+
export { type MetadataStorage, PinataBackend, SignedUrlBackend, type SignedUrlSigner, type StorageMeta, deserialize, retrieveByCid, serialize };
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { MetadataStorage, RawBlock, StorageMeta } from "./types.js";
|
|
2
|
+
|
|
3
|
+
//#region src/providers/storage/pinata.d.ts
|
|
4
|
+
declare class PinataBackend implements MetadataStorage {
|
|
5
|
+
private pinata;
|
|
6
|
+
private gateway;
|
|
7
|
+
constructor(pinataJwt: string, pinataGateway: string);
|
|
8
|
+
put(data: unknown, meta?: StorageMeta): Promise<string>;
|
|
9
|
+
update(data: unknown, meta?: StorageMeta): Promise<string>;
|
|
10
|
+
/**
|
|
11
|
+
* Pack every item into ONE locally-built CAR and upload it as a single pin,
|
|
12
|
+
* collapsing N uploads into one request. Returns each item's `ipfs://<root>/<name>`
|
|
13
|
+
* path URI: a CAR upload registers only the directory root as a "file", so the
|
|
14
|
+
* dedicated gateway serves chunks by path through that root (bare sub-block CIDs
|
|
15
|
+
* 403). Callers must bound batch size — the CAR is built in memory.
|
|
16
|
+
*/
|
|
17
|
+
putMany(items: {
|
|
18
|
+
data: unknown;
|
|
19
|
+
name: string;
|
|
20
|
+
}[]): Promise<Record<string, string>>;
|
|
21
|
+
/**
|
|
22
|
+
* Upload ONE precomputed (cid, bytes) block as a plain-file pin so it's
|
|
23
|
+
* individually addressable on the dedicated gateway via its raw-codec
|
|
24
|
+
* sibling CID (see RAW_CODE comment above for why this can't go through
|
|
25
|
+
* `.car()`). Only commit blocks take this path — one small upload per
|
|
26
|
+
* commit; everything else travels inside the commit's CAR via putFile().
|
|
27
|
+
*/
|
|
28
|
+
putBlock(block: RawBlock): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Store opaque bytes (a commit's CAR file) as a single plain-file pin.
|
|
31
|
+
* Deliberately NOT `.car()`: the CAR is a packfile we read back whole, so
|
|
32
|
+
* Pinata never needs to understand its inner blocks. Returns the file's
|
|
33
|
+
* CID as the URI handle.
|
|
34
|
+
*/
|
|
35
|
+
putFile(bytes: Uint8Array, name: string): Promise<string>;
|
|
36
|
+
/** Fetch back the exact bytes stored via putFile(). */
|
|
37
|
+
getFile(uri: string): Promise<Uint8Array>;
|
|
38
|
+
get<T>(uri: string): Promise<T>;
|
|
39
|
+
/** Raw bytes for a block CID, with no decoding — what blockstore traversal needs. */
|
|
40
|
+
getRawBlock(uri: string): Promise<Uint8Array>;
|
|
41
|
+
/**
|
|
42
|
+
* Shared fetch-with-retry: resolves the raw-codec sibling CID for blocks
|
|
43
|
+
* uploaded via putBlock(), fetches from the dedicated gateway, and returns
|
|
44
|
+
* the exact bytes (never pre-decoded) plus enough context for get<T>() to
|
|
45
|
+
* decide how to decode them.
|
|
46
|
+
*/
|
|
47
|
+
private fetchRaw;
|
|
48
|
+
static getStatic<T>(uri: string, gateway?: string): Promise<T>;
|
|
49
|
+
getCidByStateRoot(stateRoot: string, retries?: number, delay?: number): Promise<string>;
|
|
50
|
+
delete(uri: string): Promise<void>;
|
|
51
|
+
}
|
|
52
|
+
//#endregion
|
|
53
|
+
export { PinataBackend };
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
import { retrieveByCid, serialize, withUploadRetry } from "./utils.js";
|
|
2
|
+
import { packCar } from "../../engine/car.js";
|
|
3
|
+
import { keccak256, stringToBytes } from "viem";
|
|
4
|
+
import { CID } from "multiformats/cid";
|
|
5
|
+
import { encode } from "multiformats/block";
|
|
6
|
+
import { PinataSDK } from "pinata";
|
|
7
|
+
import * as dagCbor from "@ipld/dag-cbor";
|
|
8
|
+
import { sha256 } from "multiformats/hashes/sha2";
|
|
9
|
+
|
|
10
|
+
//#region src/providers/storage/pinata.ts
|
|
11
|
+
const RAW_CODE = 85;
|
|
12
|
+
var PinataBackend = class {
|
|
13
|
+
pinata;
|
|
14
|
+
gateway;
|
|
15
|
+
constructor(pinataJwt, pinataGateway) {
|
|
16
|
+
this.pinata = new PinataSDK({
|
|
17
|
+
pinataJwt,
|
|
18
|
+
pinataGateway
|
|
19
|
+
});
|
|
20
|
+
this.gateway = pinataGateway;
|
|
21
|
+
}
|
|
22
|
+
async put(data, meta) {
|
|
23
|
+
const content = serialize(data);
|
|
24
|
+
const name = meta?.name ?? "file";
|
|
25
|
+
return withUploadRetry(name, async () => {
|
|
26
|
+
const file = new File([content], name, { type: "text/plain" });
|
|
27
|
+
return (await this.pinata.upload.public.file(file, { metadata: meta })).cid;
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
async update(data, meta) {
|
|
31
|
+
const content = serialize(data);
|
|
32
|
+
const name = meta?.name ?? "file";
|
|
33
|
+
return withUploadRetry(name, async () => {
|
|
34
|
+
const file = new File([content], name, { type: "text/plain" });
|
|
35
|
+
const upload = await this.pinata.upload.public.file(file).name(name);
|
|
36
|
+
const stateRoot = keccak256(stringToBytes(upload.cid)).toLowerCase();
|
|
37
|
+
await this.pinata.files.public.update({
|
|
38
|
+
id: upload.id,
|
|
39
|
+
keyvalues: { stateRoot }
|
|
40
|
+
});
|
|
41
|
+
return upload.cid;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Pack every item into ONE locally-built CAR and upload it as a single pin,
|
|
46
|
+
* collapsing N uploads into one request. Returns each item's `ipfs://<root>/<name>`
|
|
47
|
+
* path URI: a CAR upload registers only the directory root as a "file", so the
|
|
48
|
+
* dedicated gateway serves chunks by path through that root (bare sub-block CIDs
|
|
49
|
+
* 403). Callers must bound batch size — the CAR is built in memory.
|
|
50
|
+
*/
|
|
51
|
+
async putMany(items) {
|
|
52
|
+
if (items.length === 0) return {};
|
|
53
|
+
const blocks = [];
|
|
54
|
+
const uriByName = {};
|
|
55
|
+
for (const item of items) {
|
|
56
|
+
const block = await encode({
|
|
57
|
+
value: item.data,
|
|
58
|
+
codec: dagCbor,
|
|
59
|
+
hasher: sha256
|
|
60
|
+
});
|
|
61
|
+
blocks.push(block);
|
|
62
|
+
uriByName[item.name] = `ipfs://${block.cid.toString()}`;
|
|
63
|
+
}
|
|
64
|
+
const rootBlock = await encode({
|
|
65
|
+
value: uriByName,
|
|
66
|
+
codec: dagCbor,
|
|
67
|
+
hasher: sha256
|
|
68
|
+
});
|
|
69
|
+
blocks.push(rootBlock);
|
|
70
|
+
const bytes = await packCar(rootBlock.cid, blocks);
|
|
71
|
+
await withUploadRetry(`car[${items.length.toString()}f/${(bytes.length / 1e6).toFixed(1)}MB]`, async () => {
|
|
72
|
+
const file = new File([bytes.buffer], "data.car", { type: "application/vnd.ipld.car" });
|
|
73
|
+
await this.pinata.upload.public.file(file).car();
|
|
74
|
+
});
|
|
75
|
+
return uriByName;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Upload ONE precomputed (cid, bytes) block as a plain-file pin so it's
|
|
79
|
+
* individually addressable on the dedicated gateway via its raw-codec
|
|
80
|
+
* sibling CID (see RAW_CODE comment above for why this can't go through
|
|
81
|
+
* `.car()`). Only commit blocks take this path — one small upload per
|
|
82
|
+
* commit; everything else travels inside the commit's CAR via putFile().
|
|
83
|
+
*/
|
|
84
|
+
async putBlock(block) {
|
|
85
|
+
const { cid, bytes } = block;
|
|
86
|
+
await withUploadRetry(cid.toString(), async () => {
|
|
87
|
+
const file = new File([bytes], cid.toString(), { type: "application/octet-stream" });
|
|
88
|
+
await this.pinata.upload.public.file(file);
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Store opaque bytes (a commit's CAR file) as a single plain-file pin.
|
|
93
|
+
* Deliberately NOT `.car()`: the CAR is a packfile we read back whole, so
|
|
94
|
+
* Pinata never needs to understand its inner blocks. Returns the file's
|
|
95
|
+
* CID as the URI handle.
|
|
96
|
+
*/
|
|
97
|
+
async putFile(bytes, name) {
|
|
98
|
+
return withUploadRetry(name, async () => {
|
|
99
|
+
const file = new File([bytes], name, { type: "application/octet-stream" });
|
|
100
|
+
return (await this.pinata.upload.public.file(file)).cid;
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
/** Fetch back the exact bytes stored via putFile(). */
|
|
104
|
+
async getFile(uri) {
|
|
105
|
+
const { bytes } = await this.fetchRaw(uri);
|
|
106
|
+
return bytes;
|
|
107
|
+
}
|
|
108
|
+
async get(uri) {
|
|
109
|
+
const { bytes, isDagCborCid, contentType } = await this.fetchRaw(uri);
|
|
110
|
+
if (isDagCborCid || contentType === "application/octet-stream") return dagCbor.decode(bytes);
|
|
111
|
+
const text = new TextDecoder().decode(bytes);
|
|
112
|
+
try {
|
|
113
|
+
return JSON.parse(text);
|
|
114
|
+
} catch {
|
|
115
|
+
return text;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
/** Raw bytes for a block CID, with no decoding — what blockstore traversal needs. */
|
|
119
|
+
async getRawBlock(uri) {
|
|
120
|
+
const { bytes } = await this.fetchRaw(uri);
|
|
121
|
+
return bytes;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Shared fetch-with-retry: resolves the raw-codec sibling CID for blocks
|
|
125
|
+
* uploaded via putBlock(), fetches from the dedicated gateway, and returns
|
|
126
|
+
* the exact bytes (never pre-decoded) plus enough context for get<T>() to
|
|
127
|
+
* decide how to decode them.
|
|
128
|
+
*/
|
|
129
|
+
async fetchRaw(uri) {
|
|
130
|
+
let attempts = 5;
|
|
131
|
+
let lastError;
|
|
132
|
+
let fetchUri = uri;
|
|
133
|
+
const isDagCborCid = uri.startsWith("bafyrei");
|
|
134
|
+
if (isDagCborCid) try {
|
|
135
|
+
fetchUri = CID.createV1(RAW_CODE, CID.parse(uri).multihash).toString();
|
|
136
|
+
} catch {
|
|
137
|
+
fetchUri = uri;
|
|
138
|
+
}
|
|
139
|
+
while (attempts > 0) try {
|
|
140
|
+
const { data, contentType } = await this.pinata.gateways.public.get(fetchUri);
|
|
141
|
+
return {
|
|
142
|
+
bytes: data instanceof Blob ? new Uint8Array(await data.arrayBuffer()) : data instanceof ArrayBuffer ? new Uint8Array(data) : data instanceof Uint8Array ? data : new TextEncoder().encode(typeof data === "string" ? data : JSON.stringify(data)),
|
|
143
|
+
isDagCborCid,
|
|
144
|
+
contentType
|
|
145
|
+
};
|
|
146
|
+
} catch (error) {
|
|
147
|
+
lastError = error;
|
|
148
|
+
attempts--;
|
|
149
|
+
if (attempts === 0) break;
|
|
150
|
+
await new Promise((resolve) => setTimeout(resolve, 1e3));
|
|
151
|
+
}
|
|
152
|
+
const internalMessage = lastError instanceof Error ? lastError.message : typeof lastError === "string" ? lastError : String(lastError ?? "");
|
|
153
|
+
throw new Error(`Pinata SDK failed to retrieve block ${uri} after multiple attempts. Internal Error: ${internalMessage}`);
|
|
154
|
+
}
|
|
155
|
+
static async getStatic(uri, gateway) {
|
|
156
|
+
return retrieveByCid(uri, gateway);
|
|
157
|
+
}
|
|
158
|
+
async getCidByStateRoot(stateRoot, retries = 5, delay = 1e3) {
|
|
159
|
+
const formattedRoot = stateRoot.toLowerCase();
|
|
160
|
+
for (let i = 0; i < retries; i++) {
|
|
161
|
+
const response = await this.pinata.files.public.list().keyvalues({ stateRoot: formattedRoot });
|
|
162
|
+
if (response.files.length > 0) return response.files[0].cid;
|
|
163
|
+
if (i < retries - 1) {
|
|
164
|
+
console.warn(`
|
|
165
|
+
[Pinata] Indexing lag detected for root ${formattedRoot}. Retrying in ${(delay * (i + 1)).toString()}ms...
|
|
166
|
+
`);
|
|
167
|
+
await new Promise((resolve) => setTimeout(resolve, delay * (i + 1)));
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
throw new Error(`No matching IPFS CID found for state root: ${stateRoot} after ${retries.toString()} retrieval attempts.`);
|
|
171
|
+
}
|
|
172
|
+
async delete(uri) {
|
|
173
|
+
await this.pinata.files.public.delete([uri]);
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
//#endregion
|
|
178
|
+
export { PinataBackend };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { MetadataStorage, RawBlock, StorageMeta } from "./types.js";
|
|
2
|
+
import { Hex } from "viem";
|
|
3
|
+
|
|
4
|
+
//#region src/providers/storage/signed-url.d.ts
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The hosted worker for the default network (Base Sepolia). Used when neither
|
|
8
|
+
* a worker URL nor the network's config names one. `Fangorn.create` passes the
|
|
9
|
+
* config's `signedUrlWorker`, so a Base client reaches Base's worker.
|
|
10
|
+
*/
|
|
11
|
+
declare const DEFAULT_SIGNED_URL_WORKER: string;
|
|
12
|
+
/** Just enough of a wallet to run the worker's ownership handshake. */
|
|
13
|
+
interface SignedUrlSigner {
|
|
14
|
+
address: Hex;
|
|
15
|
+
/** EIP-191 personal_sign of `message` (what the worker recovers against). */
|
|
16
|
+
signMessage(message: string): Promise<Hex>;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Storage backend for users who don't bring their own Pinata JWT.
|
|
20
|
+
*
|
|
21
|
+
* Uploads go through the pinata-url-provider Worker. Prove wallet ownership by
|
|
22
|
+
* signing the worker's challenge, and it hands back a short-lived, single-use
|
|
23
|
+
* Pinata presigned upload URL that users POST the file to.
|
|
24
|
+
* Reads need no auth: every Fangorn block is public content, so it's
|
|
25
|
+
* fetched straight from a public IPFS gateway by CID (privacy is cryptographic,
|
|
26
|
+
* not access-controlled). Each upload runs a fresh handshake because the
|
|
27
|
+
* presigned URL is one-time and expires in minutes.
|
|
28
|
+
*
|
|
29
|
+
* JWT-only operations (server-side metadata queries / deletes) are unavailable
|
|
30
|
+
* here. Switch to a PinataBackend they're needed.
|
|
31
|
+
*
|
|
32
|
+
* Every upload is charged to the signing publisher's storage quota.
|
|
33
|
+
*/
|
|
34
|
+
declare class SignedUrlBackend implements MetadataStorage {
|
|
35
|
+
private readonly signer;
|
|
36
|
+
private readonly gateway;
|
|
37
|
+
private readonly workerUrl;
|
|
38
|
+
constructor(workerUrl: string | undefined, signer: SignedUrlSigner, gateway: string);
|
|
39
|
+
/** Run the worker challenge handshake → one-time presigned upload URL + network. */
|
|
40
|
+
private requestUploadUrl;
|
|
41
|
+
private workerJson;
|
|
42
|
+
/** Upload bytes via a fresh one-time presigned URL; returns the pinned CID. */
|
|
43
|
+
private uploadBytes;
|
|
44
|
+
put(data: unknown, meta?: StorageMeta): Promise<string>;
|
|
45
|
+
putFile(bytes: Uint8Array, name: string): Promise<string>;
|
|
46
|
+
putBlock(block: RawBlock): Promise<void>;
|
|
47
|
+
getFile(uri: string): Promise<Uint8Array>;
|
|
48
|
+
getRawBlock(uri: string): Promise<Uint8Array>;
|
|
49
|
+
get<T>(uri: string): Promise<T>;
|
|
50
|
+
putMany(): Promise<Record<string, string>>;
|
|
51
|
+
delete(): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
//#endregion
|
|
54
|
+
export { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner };
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { FangornConfig } from "../../config.js";
|
|
2
|
+
import { fetchRawByCid, serialize, withUploadRetry } from "./utils.js";
|
|
3
|
+
|
|
4
|
+
//#region src/providers/storage/signed-url.ts
|
|
5
|
+
/**
|
|
6
|
+
* The hosted worker for the default network (Base Sepolia). Used when neither
|
|
7
|
+
* a worker URL nor the network's config names one. `Fangorn.create` passes the
|
|
8
|
+
* config's `signedUrlWorker`, so a Base client reaches Base's worker.
|
|
9
|
+
*/
|
|
10
|
+
const DEFAULT_SIGNED_URL_WORKER = FangornConfig.signedUrlWorker;
|
|
11
|
+
/** A human-readable reason from a worker error response, detail included. */
|
|
12
|
+
function workerError(r) {
|
|
13
|
+
const base = r.error ?? "unknown error";
|
|
14
|
+
return r.detail ? `${base} (${r.detail})` : base;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Storage backend for users who don't bring their own Pinata JWT.
|
|
18
|
+
*
|
|
19
|
+
* Uploads go through the pinata-url-provider Worker. Prove wallet ownership by
|
|
20
|
+
* signing the worker's challenge, and it hands back a short-lived, single-use
|
|
21
|
+
* Pinata presigned upload URL that users POST the file to.
|
|
22
|
+
* Reads need no auth: every Fangorn block is public content, so it's
|
|
23
|
+
* fetched straight from a public IPFS gateway by CID (privacy is cryptographic,
|
|
24
|
+
* not access-controlled). Each upload runs a fresh handshake because the
|
|
25
|
+
* presigned URL is one-time and expires in minutes.
|
|
26
|
+
*
|
|
27
|
+
* JWT-only operations (server-side metadata queries / deletes) are unavailable
|
|
28
|
+
* here. Switch to a PinataBackend they're needed.
|
|
29
|
+
*
|
|
30
|
+
* Every upload is charged to the signing publisher's storage quota.
|
|
31
|
+
*/
|
|
32
|
+
var SignedUrlBackend = class {
|
|
33
|
+
workerUrl;
|
|
34
|
+
constructor(workerUrl, signer, gateway) {
|
|
35
|
+
this.signer = signer;
|
|
36
|
+
this.gateway = gateway;
|
|
37
|
+
this.workerUrl = workerUrl?.trim() ? workerUrl : DEFAULT_SIGNED_URL_WORKER;
|
|
38
|
+
}
|
|
39
|
+
/** Run the worker challenge handshake → one-time presigned upload URL + network. */
|
|
40
|
+
async requestUploadUrl(size, uploadId) {
|
|
41
|
+
const address = this.signer.address;
|
|
42
|
+
const challenge = await this.workerJson({
|
|
43
|
+
address,
|
|
44
|
+
size,
|
|
45
|
+
uploadId
|
|
46
|
+
});
|
|
47
|
+
if (!challenge.challenge) throw new Error(`Presigned-URL worker did not issue a challenge: ${workerError(challenge)}`);
|
|
48
|
+
const signature = await this.signer.signMessage(challenge.challenge);
|
|
49
|
+
const grant = await this.workerJson({
|
|
50
|
+
address,
|
|
51
|
+
message: challenge.challenge,
|
|
52
|
+
signature,
|
|
53
|
+
size,
|
|
54
|
+
uploadId
|
|
55
|
+
});
|
|
56
|
+
if (!grant.ok || !grant.uploadUrl) throw new Error(`Presigned-URL worker denied an upload URL: ${workerError(grant)}`);
|
|
57
|
+
return {
|
|
58
|
+
uploadUrl: grant.uploadUrl,
|
|
59
|
+
network: grant.network ?? "public"
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
async workerJson(body) {
|
|
63
|
+
const res = await fetch(this.workerUrl, {
|
|
64
|
+
method: "POST",
|
|
65
|
+
headers: { "content-type": "application/json" },
|
|
66
|
+
body: JSON.stringify(body)
|
|
67
|
+
});
|
|
68
|
+
return await res.json().catch(() => null) ?? { error: `HTTP ${res.status.toString()}` };
|
|
69
|
+
}
|
|
70
|
+
/** Upload bytes via a fresh one-time presigned URL; returns the pinned CID. */
|
|
71
|
+
uploadBytes(bytes, name, type) {
|
|
72
|
+
const uploadId = globalThis.crypto.randomUUID();
|
|
73
|
+
return withUploadRetry(name, async () => {
|
|
74
|
+
const { uploadUrl, network } = await this.requestUploadUrl(bytes.length, uploadId);
|
|
75
|
+
const fd = new FormData();
|
|
76
|
+
fd.append("network", network);
|
|
77
|
+
fd.append("file", new File([bytes], name, { type }));
|
|
78
|
+
const res = await fetch(uploadUrl, {
|
|
79
|
+
method: "POST",
|
|
80
|
+
body: fd
|
|
81
|
+
});
|
|
82
|
+
const data = await res.json().catch(() => null);
|
|
83
|
+
if (!res.ok) throw Object.assign(/* @__PURE__ */ new Error(`Pinata upload failed: ${data ? JSON.stringify(data) : "(no body)"}`), { statusCode: res.status });
|
|
84
|
+
const cid = data?.data?.cid;
|
|
85
|
+
if (!cid) throw new Error(`Pinata upload returned no CID: ${JSON.stringify(data)}`);
|
|
86
|
+
return cid;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
async put(data, meta) {
|
|
90
|
+
return this.uploadBytes(new TextEncoder().encode(serialize(data)), meta?.name ?? "file", "text/plain");
|
|
91
|
+
}
|
|
92
|
+
async putFile(bytes, name) {
|
|
93
|
+
return this.uploadBytes(bytes, name, "application/octet-stream");
|
|
94
|
+
}
|
|
95
|
+
async putBlock(block) {
|
|
96
|
+
await this.uploadBytes(block.bytes, block.cid.toString(), "application/octet-stream");
|
|
97
|
+
}
|
|
98
|
+
async getFile(uri) {
|
|
99
|
+
return fetchRawByCid(uri, this.gateway);
|
|
100
|
+
}
|
|
101
|
+
async getRawBlock(uri) {
|
|
102
|
+
return fetchRawByCid(uri, this.gateway);
|
|
103
|
+
}
|
|
104
|
+
async get(uri) {
|
|
105
|
+
const bytes = await fetchRawByCid(uri, this.gateway);
|
|
106
|
+
const text = new TextDecoder().decode(bytes);
|
|
107
|
+
try {
|
|
108
|
+
return JSON.parse(text);
|
|
109
|
+
} catch {
|
|
110
|
+
return text;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
putMany() {
|
|
114
|
+
throw new Error("putMany (batched CAR upload) is not available with signed URLs — provide your own Pinata JWT.");
|
|
115
|
+
}
|
|
116
|
+
delete() {
|
|
117
|
+
throw new Error("delete is not available with signed URLs — provide your own Pinata JWT.");
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
//#endregion
|
|
122
|
+
export { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { CID } from "multiformats/cid";
|
|
2
|
+
|
|
3
|
+
//#region src/providers/storage/types.d.ts
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* A backend-agnostic interface for storing and retrieving opaque content.
|
|
7
|
+
*/
|
|
8
|
+
interface StorageMeta {
|
|
9
|
+
name?: string;
|
|
10
|
+
[key: string]: unknown;
|
|
11
|
+
}
|
|
12
|
+
/** A content-addressed block whose CID is already known to the caller. */
|
|
13
|
+
interface RawBlock {
|
|
14
|
+
cid: CID;
|
|
15
|
+
bytes: Uint8Array;
|
|
16
|
+
}
|
|
17
|
+
interface MetadataStorage {
|
|
18
|
+
/**
|
|
19
|
+
* Store content and return an opaque URI.
|
|
20
|
+
* Callers never construct or parse URIs, they should be treated as handles.
|
|
21
|
+
*/
|
|
22
|
+
put(data: unknown, meta?: StorageMeta): Promise<string>;
|
|
23
|
+
/**
|
|
24
|
+
* Pack multiple items into a single upload
|
|
25
|
+
* Returns a map of { name -> identifier } for each item
|
|
26
|
+
*/
|
|
27
|
+
putMany(items: {
|
|
28
|
+
data: unknown;
|
|
29
|
+
name: string;
|
|
30
|
+
}[]): Promise<Record<string, string>>;
|
|
31
|
+
/**
|
|
32
|
+
* Upload ONE precomputed (cid, bytes) block, preserving its exact CID so it
|
|
33
|
+
* stays retrievable via `getRawBlock(cid.toString())`. Used only for commit
|
|
34
|
+
* blocks — one small upload per commit; bulk data travels inside CAR files
|
|
35
|
+
* via `putFile`.
|
|
36
|
+
*/
|
|
37
|
+
putBlock(block: RawBlock): Promise<void>;
|
|
38
|
+
/**
|
|
39
|
+
* Store an opaque byte payload (e.g. a CAR file) and return its CID.
|
|
40
|
+
* The backend is NOT expected to understand the contents.
|
|
41
|
+
*/
|
|
42
|
+
putFile(bytes: Uint8Array, name: string): Promise<string>;
|
|
43
|
+
/**
|
|
44
|
+
* Retrieve the exact bytes previously stored with putFile().
|
|
45
|
+
*/
|
|
46
|
+
getFile(uri: string): Promise<Uint8Array>;
|
|
47
|
+
/**
|
|
48
|
+
* Retrieve content by URI previously returned from put().
|
|
49
|
+
*/
|
|
50
|
+
get<T>(uri: string): Promise<T>;
|
|
51
|
+
/**
|
|
52
|
+
* Retrieve the exact raw bytes for a block CID, with no decoding applied —
|
|
53
|
+
* how commit blocks written with putBlock() are read back.
|
|
54
|
+
*/
|
|
55
|
+
getRawBlock(uri: string): Promise<Uint8Array>;
|
|
56
|
+
/**
|
|
57
|
+
* Delete content by URI
|
|
58
|
+
*/
|
|
59
|
+
delete(uri: string): Promise<void>;
|
|
60
|
+
}
|
|
61
|
+
//#endregion
|
|
62
|
+
export { MetadataStorage, RawBlock, StorageMeta };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { PinataBackend } from "./pinata.js";
|
|
2
|
+
import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./signed-url.js";
|
|
3
|
+
|
|
4
|
+
//#region src/providers/storage/utils.d.ts
|
|
5
|
+
declare function serialize(data: unknown): string;
|
|
6
|
+
declare function deserialize(text: string): unknown;
|
|
7
|
+
declare const MAX_UPLOAD_ATTEMPTS: number;
|
|
8
|
+
declare function isTransientUpload(err: unknown): boolean;
|
|
9
|
+
declare function withUploadRetry<T>(label: string, fn: () => Promise<T>): Promise<T>;
|
|
10
|
+
/**
|
|
11
|
+
* Fetch the exact raw bytes for a CID from a public IPFS gateway (no decoding),
|
|
12
|
+
* retrying to ride out gateway replication lag right after an upload. Blocks
|
|
13
|
+
* written via putBlock() are addressed by their raw-codec (0x55) sibling, so a
|
|
14
|
+
* dag-cbor ("bafyrei…") CID is translated before fetching — the same handling
|
|
15
|
+
* PinataBackend.fetchRaw does, but over a public gateway with no JWT.
|
|
16
|
+
*/
|
|
17
|
+
declare function fetchRawByCid(cid: string, gateway?: string, {
|
|
18
|
+
retries,
|
|
19
|
+
timeoutMs
|
|
20
|
+
}?: {
|
|
21
|
+
retries?: number | undefined;
|
|
22
|
+
timeoutMs?: number | undefined;
|
|
23
|
+
}): Promise<Uint8Array>;
|
|
24
|
+
/**
|
|
25
|
+
* Fetch any content by CID from a public IPFS gateway.
|
|
26
|
+
* No auth required — all Fangorn content is public; privacy is cryptographic.
|
|
27
|
+
*/
|
|
28
|
+
declare function retrieveByCid<T>(cid: string, gateway?: string, timeoutSecond?: number): Promise<T>;
|
|
29
|
+
//#endregion
|
|
30
|
+
export { DEFAULT_SIGNED_URL_WORKER, MAX_UPLOAD_ATTEMPTS, PinataBackend, SignedUrlBackend, SignedUrlSigner, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry };
|