@fangorn-network/sdk 2026.7.24 → 2026.7.27
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/cli/cli.js +28 -33
- package/lib/cli/index.d.ts +13 -13
- package/lib/config.d.ts +76 -76
- package/lib/fangorn.d.ts +7 -1
- package/lib/fangorn.js +27 -7
- package/lib/index.d.ts +4 -2
- package/lib/index.js +3 -2
- package/lib/providers/storage/index.d.ts +2 -1
- package/lib/providers/storage/index.js +2 -1
- package/lib/providers/storage/pinata.js +1 -19
- package/lib/providers/storage/signed-url.d.ts +52 -0
- package/lib/providers/storage/signed-url.js +119 -0
- package/lib/providers/storage/utils.d.ts +19 -1
- package/lib/providers/storage/utils.js +55 -1
- package/lib/types/index.d.ts +5 -0
- package/package.json +1 -1
package/lib/cli/cli.js
CHANGED
|
@@ -21,7 +21,8 @@ function loadConfig() {
|
|
|
21
21
|
const privateKey = process.env.ETH_PRIVATE_KEY;
|
|
22
22
|
const pinataJwt = process.env.PINATA_JWT;
|
|
23
23
|
const pinataGateway = process.env.PINATA_GATEWAY;
|
|
24
|
-
const
|
|
24
|
+
const accessWorkerUrl = process.env.ACCESS_WORKER_URL;
|
|
25
|
+
const signedUrlWorkerUrl = process.env.SIGNED_URL_WORKER_URL;
|
|
25
26
|
if (existsSync(CONFIG_PATH)) {
|
|
26
27
|
const stored = JSON.parse(readFileSync(CONFIG_PATH, "utf-8"));
|
|
27
28
|
_config = {
|
|
@@ -29,26 +30,24 @@ function loadConfig() {
|
|
|
29
30
|
cfg: FangornConfig,
|
|
30
31
|
pinataJwt: stored.pinataJwt,
|
|
31
32
|
pinataGateway: stored.pinataGateway,
|
|
32
|
-
|
|
33
|
+
accessWorkerUrl: stored.accessWorkerUrl ?? "",
|
|
34
|
+
signedUrlWorkerUrl: stored.signedUrlWorkerUrl ?? ""
|
|
33
35
|
};
|
|
34
36
|
return _config;
|
|
35
37
|
}
|
|
36
|
-
if (privateKey || pinataJwt || pinataGateway) {
|
|
37
|
-
|
|
38
|
-
if (!privateKey) missing.push("ETH_PRIVATE_KEY");
|
|
39
|
-
if (!pinataJwt) missing.push("PINATA_JWT");
|
|
40
|
-
if (!pinataGateway) missing.push("PINATA_GATEWAY");
|
|
41
|
-
if (missing.length > 0) throw new Error(`Incomplete environment configuration. Missing: ${missing.join(", ")}\nSet all required env vars or run \`fangorn init\` to use a config file.`);
|
|
38
|
+
if (privateKey || pinataJwt || pinataGateway || signedUrlWorkerUrl) {
|
|
39
|
+
if (!privateKey) throw new Error("Incomplete environment configuration. Missing: ETH_PRIVATE_KEY\nSet it or run `fangorn init` to use a config file.");
|
|
42
40
|
_config = {
|
|
43
41
|
privateKey,
|
|
44
42
|
cfg: FangornConfig,
|
|
45
43
|
pinataJwt: pinataJwt ?? "",
|
|
46
44
|
pinataGateway: pinataGateway ?? "",
|
|
47
|
-
|
|
45
|
+
accessWorkerUrl: accessWorkerUrl ?? "",
|
|
46
|
+
signedUrlWorkerUrl: signedUrlWorkerUrl ?? ""
|
|
48
47
|
};
|
|
49
48
|
return _config;
|
|
50
49
|
}
|
|
51
|
-
throw new Error("No configuration found. Run `fangorn init` or set
|
|
50
|
+
throw new Error("No configuration found. Run `fangorn init` or set ETH_PRIVATE_KEY\n(with no config, uploads go to Fangorn's shared Pinata account — a best-effort testnet convenience; files may be unpinned without notice. Set PINATA_JWT + PINATA_GATEWAY to use your own storage).");
|
|
52
51
|
}
|
|
53
52
|
function getAccount() {
|
|
54
53
|
if (_account) return _account;
|
|
@@ -58,12 +57,13 @@ function getAccount() {
|
|
|
58
57
|
function getFangorn() {
|
|
59
58
|
if (_fangorn) return _fangorn;
|
|
60
59
|
const cfg = loadConfig();
|
|
60
|
+
const storage = cfg.pinataJwt ? { pinata: {
|
|
61
|
+
jwt: cfg.pinataJwt,
|
|
62
|
+
gateway: cfg.pinataGateway
|
|
63
|
+
} } : { signedUrl: { workerUrl: cfg.signedUrlWorkerUrl } };
|
|
61
64
|
_fangorn = Fangorn.create({
|
|
62
65
|
privateKey: cfg.privateKey,
|
|
63
|
-
storage
|
|
64
|
-
jwt: cfg.pinataJwt,
|
|
65
|
-
gateway: cfg.pinataGateway
|
|
66
|
-
} },
|
|
66
|
+
storage,
|
|
67
67
|
domain: "localhost",
|
|
68
68
|
config: cfg.cfg
|
|
69
69
|
});
|
|
@@ -127,35 +127,30 @@ program.command("init").description("Configure your Fangorn credentials").action
|
|
|
127
127
|
}
|
|
128
128
|
});
|
|
129
129
|
handleCancel(privateKey);
|
|
130
|
-
const pinataJwt = await text({
|
|
131
|
-
message: "Pinata JWT:",
|
|
132
|
-
validate: (v) => {
|
|
133
|
-
if (!v) return "Required";
|
|
134
|
-
}
|
|
135
|
-
});
|
|
130
|
+
const pinataJwt = await text({ message: "Pinata JWT — leave blank to use Fangorn's shared Pinata account (testnet convenience; files may be unpinned without notice):" });
|
|
136
131
|
handleCancel(pinataJwt);
|
|
137
132
|
const pinataGateway = await text({
|
|
138
|
-
message: "Pinata Gateway URL:",
|
|
139
|
-
placeholder: "https://your-gateway.mypinata.cloud"
|
|
140
|
-
validate: (v) => {
|
|
141
|
-
if (!v) return "Required";
|
|
142
|
-
}
|
|
133
|
+
message: "Pinata Gateway URL (optional; blank uses a public IPFS gateway):",
|
|
134
|
+
placeholder: "https://your-gateway.mypinata.cloud"
|
|
143
135
|
});
|
|
144
136
|
handleCancel(pinataGateway);
|
|
145
|
-
const
|
|
146
|
-
message: "
|
|
147
|
-
placeholder: "https://
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
137
|
+
const accessWorkerUrl = await text({
|
|
138
|
+
message: "Access-gating worker URL (optional):",
|
|
139
|
+
placeholder: "https://access-worker.your-subdomain.workers.dev"
|
|
140
|
+
});
|
|
141
|
+
handleCancel(accessWorkerUrl);
|
|
142
|
+
const signedUrlWorkerUrl = await text({
|
|
143
|
+
message: "Presigned-URL worker URL (optional; blank uses the hosted default):",
|
|
144
|
+
placeholder: "https://pinata-url-provider.your-subdomain.workers.dev"
|
|
151
145
|
});
|
|
152
|
-
handleCancel(
|
|
146
|
+
handleCancel(signedUrlWorkerUrl);
|
|
153
147
|
const stored = {
|
|
154
148
|
privateKey,
|
|
155
149
|
chainName: "Arbitrum Sepolia",
|
|
156
150
|
pinataJwt,
|
|
157
151
|
pinataGateway,
|
|
158
|
-
|
|
152
|
+
accessWorkerUrl,
|
|
153
|
+
signedUrlWorkerUrl
|
|
159
154
|
};
|
|
160
155
|
if (!existsSync(CONFIG_DIR)) mkdirSync(CONFIG_DIR, { recursive: true });
|
|
161
156
|
writeFileSync(CONFIG_PATH, JSON.stringify(stored, null, 2), "utf-8");
|
package/lib/cli/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "./cli.js";
|
|
2
|
-
import * as
|
|
2
|
+
import * as viem89 from "viem";
|
|
3
3
|
|
|
4
4
|
//#region src/cli/index.d.ts
|
|
5
5
|
declare const getChain: (chainStr: string) => {
|
|
@@ -35,17 +35,17 @@ declare const getChain: (chainStr: string) => {
|
|
|
35
35
|
testnet: true;
|
|
36
36
|
custom?: Record<string, unknown> | undefined;
|
|
37
37
|
extendSchema?: Record<string, unknown> | undefined;
|
|
38
|
-
fees?:
|
|
38
|
+
fees?: viem89.ChainFees<undefined> | undefined;
|
|
39
39
|
formatters?: undefined;
|
|
40
|
-
prepareTransactionRequest?: ((args:
|
|
40
|
+
prepareTransactionRequest?: ((args: viem89.PrepareTransactionRequestParameters, options: {
|
|
41
41
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
42
|
-
}) => Promise<
|
|
42
|
+
}) => Promise<viem89.PrepareTransactionRequestParameters>) | [fn: ((args: viem89.PrepareTransactionRequestParameters, options: {
|
|
43
43
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
44
|
-
}) => Promise<
|
|
44
|
+
}) => Promise<viem89.PrepareTransactionRequestParameters>) | undefined, options: {
|
|
45
45
|
runAt: readonly ("beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters")[];
|
|
46
46
|
}] | undefined;
|
|
47
|
-
serializers?:
|
|
48
|
-
verifyHash?: ((client:
|
|
47
|
+
serializers?: viem89.ChainSerializers<undefined, viem89.TransactionSerializable> | undefined;
|
|
48
|
+
verifyHash?: ((client: viem89.Client, parameters: viem89.VerifyHashActionParameters) => Promise<viem89.VerifyHashActionReturnType>) | undefined;
|
|
49
49
|
};
|
|
50
50
|
declare const handleCancel: (value: unknown) => void;
|
|
51
51
|
declare const selectChain: () => Promise<{
|
|
@@ -81,17 +81,17 @@ declare const selectChain: () => Promise<{
|
|
|
81
81
|
testnet: true;
|
|
82
82
|
custom?: Record<string, unknown> | undefined;
|
|
83
83
|
extendSchema?: Record<string, unknown> | undefined;
|
|
84
|
-
fees?:
|
|
84
|
+
fees?: viem89.ChainFees<undefined> | undefined;
|
|
85
85
|
formatters?: undefined;
|
|
86
|
-
prepareTransactionRequest?: ((args:
|
|
86
|
+
prepareTransactionRequest?: ((args: viem89.PrepareTransactionRequestParameters, options: {
|
|
87
87
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
88
|
-
}) => Promise<
|
|
88
|
+
}) => Promise<viem89.PrepareTransactionRequestParameters>) | [fn: ((args: viem89.PrepareTransactionRequestParameters, options: {
|
|
89
89
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
90
|
-
}) => Promise<
|
|
90
|
+
}) => Promise<viem89.PrepareTransactionRequestParameters>) | undefined, options: {
|
|
91
91
|
runAt: readonly ("beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters")[];
|
|
92
92
|
}] | undefined;
|
|
93
|
-
serializers?:
|
|
94
|
-
verifyHash?: ((client:
|
|
93
|
+
serializers?: viem89.ChainSerializers<undefined, viem89.TransactionSerializable> | undefined;
|
|
94
|
+
verifyHash?: ((client: viem89.Client, parameters: viem89.VerifyHashActionParameters) => Promise<viem89.VerifyHashActionReturnType>) | undefined;
|
|
95
95
|
}>;
|
|
96
96
|
declare function parseGadgetArg(raw: string): {
|
|
97
97
|
type: string;
|
package/lib/config.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as viem_chains0 from "viem/chains";
|
|
2
|
-
import * as
|
|
2
|
+
import * as viem0 from "viem";
|
|
3
3
|
import { Chain, Hex } from "viem";
|
|
4
4
|
import * as abitype0 from "abitype";
|
|
5
5
|
|
|
@@ -43,17 +43,17 @@ declare const SupportedNetworks: {
|
|
|
43
43
|
testnet: true;
|
|
44
44
|
custom?: Record<string, unknown> | undefined;
|
|
45
45
|
extendSchema?: Record<string, unknown> | undefined;
|
|
46
|
-
fees?:
|
|
46
|
+
fees?: viem0.ChainFees<undefined> | undefined;
|
|
47
47
|
formatters?: undefined;
|
|
48
|
-
prepareTransactionRequest?: ((args:
|
|
48
|
+
prepareTransactionRequest?: ((args: viem0.PrepareTransactionRequestParameters, options: {
|
|
49
49
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
50
|
-
}) => Promise<
|
|
50
|
+
}) => Promise<viem0.PrepareTransactionRequestParameters>) | [fn: ((args: viem0.PrepareTransactionRequestParameters, options: {
|
|
51
51
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
52
|
-
}) => Promise<
|
|
52
|
+
}) => Promise<viem0.PrepareTransactionRequestParameters>) | undefined, options: {
|
|
53
53
|
runAt: readonly ("beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters")[];
|
|
54
54
|
}] | undefined;
|
|
55
|
-
serializers?:
|
|
56
|
-
verifyHash?: ((client:
|
|
55
|
+
serializers?: viem0.ChainSerializers<undefined, viem0.TransactionSerializable> | undefined;
|
|
56
|
+
verifyHash?: ((client: viem0.Client, parameters: viem0.VerifyHashActionParameters) => Promise<viem0.VerifyHashActionReturnType>) | undefined;
|
|
57
57
|
};
|
|
58
58
|
};
|
|
59
59
|
BaseSepolia: {
|
|
@@ -131,7 +131,7 @@ declare const SupportedNetworks: {
|
|
|
131
131
|
testnet: true;
|
|
132
132
|
custom?: Record<string, unknown> | undefined;
|
|
133
133
|
extendSchema?: Record<string, unknown> | undefined;
|
|
134
|
-
fees?:
|
|
134
|
+
fees?: viem0.ChainFees<undefined> | undefined;
|
|
135
135
|
formatters: {
|
|
136
136
|
readonly block: {
|
|
137
137
|
exclude: [] | undefined;
|
|
@@ -140,28 +140,28 @@ declare const SupportedNetworks: {
|
|
|
140
140
|
blobGasUsed: bigint;
|
|
141
141
|
difficulty: bigint;
|
|
142
142
|
excessBlobGas: bigint;
|
|
143
|
-
extraData:
|
|
143
|
+
extraData: viem0.Hex;
|
|
144
144
|
gasLimit: bigint;
|
|
145
145
|
gasUsed: bigint;
|
|
146
146
|
hash: `0x${string}` | null;
|
|
147
147
|
logsBloom: `0x${string}` | null;
|
|
148
148
|
miner: abitype0.Address;
|
|
149
|
-
mixHash:
|
|
149
|
+
mixHash: viem0.Hash;
|
|
150
150
|
nonce: `0x${string}` | null;
|
|
151
151
|
number: bigint | null;
|
|
152
152
|
parentBeaconBlockRoot?: `0x${string}` | undefined;
|
|
153
|
-
parentHash:
|
|
154
|
-
receiptsRoot:
|
|
155
|
-
sealFields:
|
|
156
|
-
sha3Uncles:
|
|
153
|
+
parentHash: viem0.Hash;
|
|
154
|
+
receiptsRoot: viem0.Hex;
|
|
155
|
+
sealFields: viem0.Hex[];
|
|
156
|
+
sha3Uncles: viem0.Hash;
|
|
157
157
|
size: bigint;
|
|
158
|
-
stateRoot:
|
|
158
|
+
stateRoot: viem0.Hash;
|
|
159
159
|
timestamp: bigint;
|
|
160
160
|
totalDifficulty: bigint | null;
|
|
161
161
|
transactions: `0x${string}`[] | viem_chains0.OpStackTransaction<boolean>[];
|
|
162
|
-
transactionsRoot:
|
|
163
|
-
uncles:
|
|
164
|
-
withdrawals?:
|
|
162
|
+
transactionsRoot: viem0.Hash;
|
|
163
|
+
uncles: viem0.Hash[];
|
|
164
|
+
withdrawals?: viem0.Withdrawal[] | undefined | undefined;
|
|
165
165
|
withdrawalsRoot?: `0x${string}` | undefined;
|
|
166
166
|
} & {};
|
|
167
167
|
type: "block";
|
|
@@ -173,14 +173,14 @@ declare const SupportedNetworks: {
|
|
|
173
173
|
blockNumber: bigint | null;
|
|
174
174
|
from: abitype0.Address;
|
|
175
175
|
gas: bigint;
|
|
176
|
-
hash:
|
|
177
|
-
input:
|
|
176
|
+
hash: viem0.Hash;
|
|
177
|
+
input: viem0.Hex;
|
|
178
178
|
nonce: number;
|
|
179
|
-
r:
|
|
180
|
-
s:
|
|
179
|
+
r: viem0.Hex;
|
|
180
|
+
s: viem0.Hex;
|
|
181
181
|
to: abitype0.Address | null;
|
|
182
182
|
transactionIndex: number | null;
|
|
183
|
-
typeHex:
|
|
183
|
+
typeHex: viem0.Hex | null;
|
|
184
184
|
v: bigint;
|
|
185
185
|
value: bigint;
|
|
186
186
|
yParity: number;
|
|
@@ -190,11 +190,11 @@ declare const SupportedNetworks: {
|
|
|
190
190
|
maxPriorityFeePerGas: bigint;
|
|
191
191
|
isSystemTx?: boolean;
|
|
192
192
|
mint?: bigint | undefined | undefined;
|
|
193
|
-
sourceHash:
|
|
193
|
+
sourceHash: viem0.Hex;
|
|
194
194
|
type: "deposit";
|
|
195
195
|
} | {
|
|
196
|
-
r:
|
|
197
|
-
s:
|
|
196
|
+
r: viem0.Hex;
|
|
197
|
+
s: viem0.Hex;
|
|
198
198
|
v: bigint;
|
|
199
199
|
to: abitype0.Address | null;
|
|
200
200
|
from: abitype0.Address;
|
|
@@ -203,10 +203,10 @@ declare const SupportedNetworks: {
|
|
|
203
203
|
value: bigint;
|
|
204
204
|
blockHash: `0x${string}` | null;
|
|
205
205
|
blockNumber: bigint | null;
|
|
206
|
-
hash:
|
|
207
|
-
input:
|
|
206
|
+
hash: viem0.Hash;
|
|
207
|
+
input: viem0.Hex;
|
|
208
208
|
transactionIndex: number | null;
|
|
209
|
-
typeHex:
|
|
209
|
+
typeHex: viem0.Hex | null;
|
|
210
210
|
accessList?: undefined | undefined;
|
|
211
211
|
authorizationList?: undefined | undefined;
|
|
212
212
|
blobVersionedHashes?: undefined | undefined;
|
|
@@ -225,18 +225,18 @@ declare const SupportedNetworks: {
|
|
|
225
225
|
blockNumber: bigint | null;
|
|
226
226
|
from: abitype0.Address;
|
|
227
227
|
gas: bigint;
|
|
228
|
-
hash:
|
|
229
|
-
input:
|
|
228
|
+
hash: viem0.Hash;
|
|
229
|
+
input: viem0.Hex;
|
|
230
230
|
nonce: number;
|
|
231
|
-
r:
|
|
232
|
-
s:
|
|
231
|
+
r: viem0.Hex;
|
|
232
|
+
s: viem0.Hex;
|
|
233
233
|
to: abitype0.Address | null;
|
|
234
234
|
transactionIndex: number | null;
|
|
235
|
-
typeHex:
|
|
235
|
+
typeHex: viem0.Hex | null;
|
|
236
236
|
v: bigint;
|
|
237
237
|
value: bigint;
|
|
238
238
|
yParity: number;
|
|
239
|
-
accessList:
|
|
239
|
+
accessList: viem0.AccessList;
|
|
240
240
|
authorizationList?: undefined | undefined;
|
|
241
241
|
blobVersionedHashes?: undefined | undefined;
|
|
242
242
|
chainId: number;
|
|
@@ -253,18 +253,18 @@ declare const SupportedNetworks: {
|
|
|
253
253
|
blockNumber: bigint | null;
|
|
254
254
|
from: abitype0.Address;
|
|
255
255
|
gas: bigint;
|
|
256
|
-
hash:
|
|
257
|
-
input:
|
|
256
|
+
hash: viem0.Hash;
|
|
257
|
+
input: viem0.Hex;
|
|
258
258
|
nonce: number;
|
|
259
|
-
r:
|
|
260
|
-
s:
|
|
259
|
+
r: viem0.Hex;
|
|
260
|
+
s: viem0.Hex;
|
|
261
261
|
to: abitype0.Address | null;
|
|
262
262
|
transactionIndex: number | null;
|
|
263
|
-
typeHex:
|
|
263
|
+
typeHex: viem0.Hex | null;
|
|
264
264
|
v: bigint;
|
|
265
265
|
value: bigint;
|
|
266
266
|
yParity: number;
|
|
267
|
-
accessList:
|
|
267
|
+
accessList: viem0.AccessList;
|
|
268
268
|
authorizationList?: undefined | undefined;
|
|
269
269
|
blobVersionedHashes?: undefined | undefined;
|
|
270
270
|
chainId: number;
|
|
@@ -281,20 +281,20 @@ declare const SupportedNetworks: {
|
|
|
281
281
|
blockNumber: bigint | null;
|
|
282
282
|
from: abitype0.Address;
|
|
283
283
|
gas: bigint;
|
|
284
|
-
hash:
|
|
285
|
-
input:
|
|
284
|
+
hash: viem0.Hash;
|
|
285
|
+
input: viem0.Hex;
|
|
286
286
|
nonce: number;
|
|
287
|
-
r:
|
|
288
|
-
s:
|
|
287
|
+
r: viem0.Hex;
|
|
288
|
+
s: viem0.Hex;
|
|
289
289
|
to: abitype0.Address | null;
|
|
290
290
|
transactionIndex: number | null;
|
|
291
|
-
typeHex:
|
|
291
|
+
typeHex: viem0.Hex | null;
|
|
292
292
|
v: bigint;
|
|
293
293
|
value: bigint;
|
|
294
294
|
yParity: number;
|
|
295
|
-
accessList:
|
|
295
|
+
accessList: viem0.AccessList;
|
|
296
296
|
authorizationList?: undefined | undefined;
|
|
297
|
-
blobVersionedHashes: readonly
|
|
297
|
+
blobVersionedHashes: readonly viem0.Hex[];
|
|
298
298
|
chainId: number;
|
|
299
299
|
type: "eip4844";
|
|
300
300
|
gasPrice?: undefined | undefined;
|
|
@@ -309,19 +309,19 @@ declare const SupportedNetworks: {
|
|
|
309
309
|
blockNumber: bigint | null;
|
|
310
310
|
from: abitype0.Address;
|
|
311
311
|
gas: bigint;
|
|
312
|
-
hash:
|
|
313
|
-
input:
|
|
312
|
+
hash: viem0.Hash;
|
|
313
|
+
input: viem0.Hex;
|
|
314
314
|
nonce: number;
|
|
315
|
-
r:
|
|
316
|
-
s:
|
|
315
|
+
r: viem0.Hex;
|
|
316
|
+
s: viem0.Hex;
|
|
317
317
|
to: abitype0.Address | null;
|
|
318
318
|
transactionIndex: number | null;
|
|
319
|
-
typeHex:
|
|
319
|
+
typeHex: viem0.Hex | null;
|
|
320
320
|
v: bigint;
|
|
321
321
|
value: bigint;
|
|
322
322
|
yParity: number;
|
|
323
|
-
accessList:
|
|
324
|
-
authorizationList:
|
|
323
|
+
accessList: viem0.AccessList;
|
|
324
|
+
authorizationList: viem0.SignedAuthorizationList;
|
|
325
325
|
blobVersionedHashes?: undefined | undefined;
|
|
326
326
|
chainId: number;
|
|
327
327
|
type: "eip7702";
|
|
@@ -340,7 +340,7 @@ declare const SupportedNetworks: {
|
|
|
340
340
|
format: (args: viem_chains0.OpStackRpcTransactionReceipt, action?: string | undefined) => {
|
|
341
341
|
blobGasPrice?: bigint | undefined;
|
|
342
342
|
blobGasUsed?: bigint | undefined;
|
|
343
|
-
blockHash:
|
|
343
|
+
blockHash: viem0.Hash;
|
|
344
344
|
blockNumber: bigint;
|
|
345
345
|
blockTimestamp?: bigint | undefined;
|
|
346
346
|
contractAddress: abitype0.Address | null | undefined;
|
|
@@ -348,14 +348,14 @@ declare const SupportedNetworks: {
|
|
|
348
348
|
effectiveGasPrice: bigint;
|
|
349
349
|
from: abitype0.Address;
|
|
350
350
|
gasUsed: bigint;
|
|
351
|
-
logs:
|
|
352
|
-
logsBloom:
|
|
351
|
+
logs: viem0.Log<bigint, number, false>[];
|
|
352
|
+
logsBloom: viem0.Hex;
|
|
353
353
|
root?: `0x${string}` | undefined;
|
|
354
354
|
status: "success" | "reverted";
|
|
355
355
|
to: abitype0.Address | null;
|
|
356
|
-
transactionHash:
|
|
356
|
+
transactionHash: viem0.Hash;
|
|
357
357
|
transactionIndex: number;
|
|
358
|
-
type:
|
|
358
|
+
type: viem0.TransactionType;
|
|
359
359
|
l1GasPrice: bigint | null;
|
|
360
360
|
l1GasUsed: bigint | null;
|
|
361
361
|
l1Fee: bigint | null;
|
|
@@ -364,17 +364,17 @@ declare const SupportedNetworks: {
|
|
|
364
364
|
type: "transactionReceipt";
|
|
365
365
|
};
|
|
366
366
|
};
|
|
367
|
-
prepareTransactionRequest?: ((args:
|
|
367
|
+
prepareTransactionRequest?: ((args: viem0.PrepareTransactionRequestParameters, options: {
|
|
368
368
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
369
|
-
}) => Promise<
|
|
369
|
+
}) => Promise<viem0.PrepareTransactionRequestParameters>) | [fn: ((args: viem0.PrepareTransactionRequestParameters, options: {
|
|
370
370
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
371
|
-
}) => Promise<
|
|
371
|
+
}) => Promise<viem0.PrepareTransactionRequestParameters>) | undefined, options: {
|
|
372
372
|
runAt: readonly ("beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters")[];
|
|
373
373
|
}] | undefined;
|
|
374
374
|
serializers: {
|
|
375
375
|
readonly transaction: typeof viem_chains0.serializeTransactionOpStack;
|
|
376
376
|
};
|
|
377
|
-
verifyHash?: ((client:
|
|
377
|
+
verifyHash?: ((client: viem0.Client, parameters: viem0.VerifyHashActionParameters) => Promise<viem0.VerifyHashActionReturnType>) | undefined;
|
|
378
378
|
readonly network: "base-sepolia";
|
|
379
379
|
};
|
|
380
380
|
};
|
|
@@ -417,17 +417,17 @@ declare function getNetwork(name: string): {
|
|
|
417
417
|
testnet: true;
|
|
418
418
|
custom?: Record<string, unknown> | undefined;
|
|
419
419
|
extendSchema?: Record<string, unknown> | undefined;
|
|
420
|
-
fees?:
|
|
420
|
+
fees?: viem0.ChainFees<undefined> | undefined;
|
|
421
421
|
formatters?: undefined;
|
|
422
|
-
prepareTransactionRequest?: ((args:
|
|
422
|
+
prepareTransactionRequest?: ((args: viem0.PrepareTransactionRequestParameters, options: {
|
|
423
423
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
424
|
-
}) => Promise<
|
|
424
|
+
}) => Promise<viem0.PrepareTransactionRequestParameters>) | [fn: ((args: viem0.PrepareTransactionRequestParameters, options: {
|
|
425
425
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
426
|
-
}) => Promise<
|
|
426
|
+
}) => Promise<viem0.PrepareTransactionRequestParameters>) | undefined, options: {
|
|
427
427
|
runAt: readonly ("beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters")[];
|
|
428
428
|
}] | undefined;
|
|
429
|
-
serializers?:
|
|
430
|
-
verifyHash?: ((client:
|
|
429
|
+
serializers?: viem0.ChainSerializers<undefined, viem0.TransactionSerializable> | undefined;
|
|
430
|
+
verifyHash?: ((client: viem0.Client, parameters: viem0.VerifyHashActionParameters) => Promise<viem0.VerifyHashActionReturnType>) | undefined;
|
|
431
431
|
};
|
|
432
432
|
interface AppConfig {
|
|
433
433
|
dataRegistryContractAddress: Hex;
|
|
@@ -471,17 +471,17 @@ declare const FangornConfig: {
|
|
|
471
471
|
testnet: true;
|
|
472
472
|
custom?: Record<string, unknown> | undefined;
|
|
473
473
|
extendSchema?: Record<string, unknown> | undefined;
|
|
474
|
-
fees?:
|
|
474
|
+
fees?: viem0.ChainFees<undefined> | undefined;
|
|
475
475
|
formatters?: undefined;
|
|
476
|
-
prepareTransactionRequest?: ((args:
|
|
476
|
+
prepareTransactionRequest?: ((args: viem0.PrepareTransactionRequestParameters, options: {
|
|
477
477
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
478
|
-
}) => Promise<
|
|
478
|
+
}) => Promise<viem0.PrepareTransactionRequestParameters>) | [fn: ((args: viem0.PrepareTransactionRequestParameters, options: {
|
|
479
479
|
phase: "beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters";
|
|
480
|
-
}) => Promise<
|
|
480
|
+
}) => Promise<viem0.PrepareTransactionRequestParameters>) | undefined, options: {
|
|
481
481
|
runAt: readonly ("beforeFillTransaction" | "beforeFillParameters" | "afterFillParameters")[];
|
|
482
482
|
}] | undefined;
|
|
483
|
-
serializers?:
|
|
484
|
-
verifyHash?: ((client:
|
|
483
|
+
serializers?: viem0.ChainSerializers<undefined, viem0.TransactionSerializable> | undefined;
|
|
484
|
+
verifyHash?: ((client: viem0.Client, parameters: viem0.VerifyHashActionParameters) => Promise<viem0.VerifyHashActionReturnType>) | undefined;
|
|
485
485
|
};
|
|
486
486
|
rpcUrl: string;
|
|
487
487
|
caip2: number;
|
package/lib/fangorn.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { DataRegistryClient } from "./contracts/data-registry/index.js";
|
|
|
3
3
|
import "./contracts/index.js";
|
|
4
4
|
import { MetadataStorage } from "./providers/storage/types.js";
|
|
5
5
|
import { CommitDiff, FangornEngine, MetagraphRegistry, NamespaceContents, NamespaceDiff } from "./engine/index.js";
|
|
6
|
-
import { FangornCreateOptions } from "./types/index.js";
|
|
6
|
+
import { FangornCreateOptions, StorageConfig } from "./types/index.js";
|
|
7
7
|
import { Hex, WalletClient } from "viem";
|
|
8
8
|
|
|
9
9
|
//#region src/fangorn.d.ts
|
|
@@ -159,6 +159,12 @@ declare class Fangorn {
|
|
|
159
159
|
getConfig(): AppConfig;
|
|
160
160
|
getDataRegistry(): DataRegistryClient;
|
|
161
161
|
getStorage(): MetadataStorage;
|
|
162
|
+
/**
|
|
163
|
+
* Swap the storage backend at runtime — e.g. move from access-worker signed
|
|
164
|
+
* URLs to your own Pinata JWT (or back). Rebuilds the engine on next use so it
|
|
165
|
+
* picks up the new backend.
|
|
166
|
+
*/
|
|
167
|
+
setStorage(storage: StorageConfig): void;
|
|
162
168
|
getWalletClient(): WalletClient;
|
|
163
169
|
getAddress(): Hex;
|
|
164
170
|
}
|
package/lib/fangorn.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { FangornConfig } from "./config.js";
|
|
2
|
+
import { SignedUrlBackend } from "./providers/storage/signed-url.js";
|
|
2
3
|
import { PinataBackend } from "./providers/storage/pinata.js";
|
|
3
4
|
import { FangornEngine, MetagraphRegistry, assertValidNamespace } from "./engine/index.js";
|
|
4
5
|
import { DataRegistryClient } from "./contracts/data-registry/index.js";
|
|
@@ -8,13 +9,23 @@ import { CID } from "multiformats/cid";
|
|
|
8
9
|
|
|
9
10
|
//#region src/fangorn.ts
|
|
10
11
|
const ZERO_BYTES32 = "0x0000000000000000000000000000000000000000000000000000000000000000";
|
|
11
|
-
|
|
12
|
-
|
|
12
|
+
/** Build a signer for the access worker's ownership handshake from a wallet. */
|
|
13
|
+
function walletSigner(walletClient) {
|
|
14
|
+
const account = walletClient.account;
|
|
15
|
+
if (!account) throw new Error("Signed-url storage requires a wallet account to sign the access worker's challenge.");
|
|
16
|
+
return {
|
|
17
|
+
address: account.address,
|
|
18
|
+
signMessage: (message) => walletClient.signMessage({
|
|
19
|
+
account,
|
|
20
|
+
message
|
|
21
|
+
})
|
|
22
|
+
};
|
|
13
23
|
}
|
|
14
|
-
function resolveStorage(storage) {
|
|
24
|
+
function resolveStorage(storage, walletClient, config) {
|
|
15
25
|
if (!storage) return void 0;
|
|
16
|
-
if (
|
|
17
|
-
|
|
26
|
+
if ("pinata" in storage) return new PinataBackend(storage.pinata.jwt, storage.pinata.gateway);
|
|
27
|
+
if ("signedUrl" in storage) return new SignedUrlBackend(storage.signedUrl.workerUrl, walletSigner(walletClient), storage.signedUrl.gateway ?? config.ipfsGateway);
|
|
28
|
+
throw new Error(`Invalid storage config: must be { pinata: … } or { signedUrl: … }, got ${JSON.stringify(storage)}`);
|
|
18
29
|
}
|
|
19
30
|
var Fangorn = class Fangorn {
|
|
20
31
|
ctx;
|
|
@@ -39,7 +50,7 @@ var Fangorn = class Fangorn {
|
|
|
39
50
|
chain: resolvedConfig.chain,
|
|
40
51
|
transport: http(resolvedConfig.rpcUrl)
|
|
41
52
|
});
|
|
42
|
-
const metadataStorage = resolveStorage(options.storage);
|
|
53
|
+
const metadataStorage = resolveStorage(options.storage, walletClient, resolvedConfig);
|
|
43
54
|
const domain = options.domain ?? new URL(resolvedConfig.rpcUrl).hostname;
|
|
44
55
|
const publicClient = createPublicClient({ transport: http(resolvedConfig.rpcUrl) });
|
|
45
56
|
return new Fangorn({
|
|
@@ -325,9 +336,18 @@ var Fangorn = class Fangorn {
|
|
|
325
336
|
return this.ctx.dataRegistry;
|
|
326
337
|
}
|
|
327
338
|
getStorage() {
|
|
328
|
-
if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } to Fangorn.create()");
|
|
339
|
+
if (!this.ctx.metadataStorage) throw new Error("storage is not configured. Pass { pinata: { ... } } or { signedUrl: { ... } } to Fangorn.create()");
|
|
329
340
|
return this.ctx.metadataStorage;
|
|
330
341
|
}
|
|
342
|
+
/**
|
|
343
|
+
* Swap the storage backend at runtime — e.g. move from access-worker signed
|
|
344
|
+
* URLs to your own Pinata JWT (or back). Rebuilds the engine on next use so it
|
|
345
|
+
* picks up the new backend.
|
|
346
|
+
*/
|
|
347
|
+
setStorage(storage) {
|
|
348
|
+
this.ctx.metadataStorage = resolveStorage(storage, this.ctx.walletClient, this.ctx.config);
|
|
349
|
+
this._engine = null;
|
|
350
|
+
}
|
|
331
351
|
getWalletClient() {
|
|
332
352
|
return this.ctx.walletClient;
|
|
333
353
|
}
|
package/lib/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { AppConfig, FangornConfig, SupportedNetworks } from "./config.js";
|
|
2
2
|
import { AccessRequest, AccessSigner, DecryptHandleParams, EncryptAndUploadParams, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf } from "./crypto/encryption.js";
|
|
3
|
+
import { FangornContext, FangornCreateOptions, StorageConfig } from "./types/index.js";
|
|
3
4
|
import { Fangorn, NamespaceChange, SubscribeOptions } from "./fangorn.js";
|
|
4
5
|
import { AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, Edge, FileFacade, ProcessorResult, Vertex, buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
|
|
5
6
|
import { PinataBackend } from "./providers/storage/pinata.js";
|
|
6
|
-
import {
|
|
7
|
-
|
|
7
|
+
import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./providers/storage/signed-url.js";
|
|
8
|
+
import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
|
|
9
|
+
export { AccessRequest, AccessSigner, AppConfig, AssetProcessor, BuildAssetGraphOptions, CommitFileGraph, DEFAULT_SIGNED_URL_WORKER, DecryptHandleParams, Edge, EncryptAndUploadParams, Fangorn, FangornConfig, FangornContext, FangornCreateOptions, FileFacade, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, Gadget, HandleFieldInput, MAX_UPLOAD_ATTEMPTS, NamespaceChange, PinataBackend, ProcessorResult, SignedUrlBackend, SignedUrlSigner, StorageConfig, SubscribeOptions, SupportedNetworks, Vertex, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, fetchRawByCid, isTransientUpload, retrieveByCid, seal, sealSelf, serialize, sha256Hex, unseal, unsealSelf, withUploadRetry };
|
package/lib/index.js
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { FangornConfig, SupportedNetworks } from "./config.js";
|
|
2
|
-
import {
|
|
2
|
+
import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend } from "./providers/storage/signed-url.js";
|
|
3
|
+
import { MAX_UPLOAD_ATTEMPTS, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry } from "./providers/storage/utils.js";
|
|
3
4
|
import { PinataBackend } from "./providers/storage/pinata.js";
|
|
4
5
|
import { Fangorn } from "./fangorn.js";
|
|
5
6
|
import { buildAssetGraph, buildMarkdownGraph, extractMarkdownLinks } from "./harness/index.js";
|
|
6
7
|
import { GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, decryptHandle, encryptAndUpload, seal, sealSelf, sha256Hex, unseal, unsealSelf } from "./crypto/encryption.js";
|
|
7
8
|
|
|
8
|
-
export { Fangorn, FangornConfig, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, PinataBackend, SupportedNetworks, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, retrieveByCid, seal, sealSelf, serialize, sha256Hex, unseal, unsealSelf };
|
|
9
|
+
export { DEFAULT_SIGNED_URL_WORKER, Fangorn, FangornConfig, GADGET_SELF_HKDF_V1, GADGET_WORKER_USDC_V1, MAX_UPLOAD_ATTEMPTS, PinataBackend, SignedUrlBackend, SupportedNetworks, X25519_PUBKEY_LENGTH, accessMessageHash, buildAccessRequest, buildAssetGraph, buildMarkdownGraph, decryptHandle, deserialize, encryptAndUpload, extractMarkdownLinks, fetchRawByCid, isTransientUpload, retrieveByCid, seal, sealSelf, serialize, sha256Hex, unseal, unsealSelf, withUploadRetry };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { MetadataStorage, StorageMeta } from "./types.js";
|
|
2
2
|
import { PinataBackend } from "./pinata.js";
|
|
3
|
+
import { SignedUrlBackend, SignedUrlSigner } from "./signed-url.js";
|
|
3
4
|
import { deserialize, retrieveByCid, serialize } from "./utils.js";
|
|
4
|
-
export { type MetadataStorage, PinataBackend, type StorageMeta, deserialize, retrieveByCid, serialize };
|
|
5
|
+
export { type MetadataStorage, PinataBackend, SignedUrlBackend, type SignedUrlSigner, type StorageMeta, deserialize, retrieveByCid, serialize };
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
+
import { SignedUrlBackend } from "./signed-url.js";
|
|
1
2
|
import { deserialize, retrieveByCid, serialize } from "./utils.js";
|
|
2
3
|
import { PinataBackend } from "./pinata.js";
|
|
3
4
|
|
|
4
|
-
export { PinataBackend, deserialize, retrieveByCid, serialize };
|
|
5
|
+
export { PinataBackend, SignedUrlBackend, deserialize, retrieveByCid, serialize };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { retrieveByCid, serialize } from "./utils.js";
|
|
1
|
+
import { retrieveByCid, serialize, withUploadRetry } from "./utils.js";
|
|
2
2
|
import { packCar } from "../../engine/car.js";
|
|
3
3
|
import { keccak256, stringToBytes } from "viem";
|
|
4
4
|
import { CID } from "multiformats/cid";
|
|
@@ -9,24 +9,6 @@ import { sha256 } from "multiformats/hashes/sha2";
|
|
|
9
9
|
|
|
10
10
|
//#region src/providers/storage/pinata.ts
|
|
11
11
|
const RAW_CODE = 85;
|
|
12
|
-
const MAX_UPLOAD_ATTEMPTS = Math.max(1, Number(process.env.PINATA_UPLOAD_RETRIES ?? 6));
|
|
13
|
-
function isTransientUpload(err) {
|
|
14
|
-
const e = err;
|
|
15
|
-
const s = typeof e.statusCode === "number" ? e.statusCode : 0;
|
|
16
|
-
if (s === 408 || s === 425 || s === 429 || s >= 500) return true;
|
|
17
|
-
const m = `${e.code ?? ""} ${e.message ?? ""}`;
|
|
18
|
-
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);
|
|
19
|
-
}
|
|
20
|
-
async function withUploadRetry(label, fn) {
|
|
21
|
-
for (let attempt = 1;; attempt++) try {
|
|
22
|
-
return await fn();
|
|
23
|
-
} catch (err) {
|
|
24
|
-
if (attempt >= MAX_UPLOAD_ATTEMPTS || !isTransientUpload(err)) throw err;
|
|
25
|
-
const delay = Math.min(3e4, 500 * 2 ** (attempt - 1)) + Math.floor(Math.random() * 500);
|
|
26
|
-
console.warn(` [pinata] upload "${label}" failed (attempt ${attempt.toString()}/${MAX_UPLOAD_ATTEMPTS.toString()}), retrying in ${(delay / 1e3).toFixed(1)}s: ${err.message}`);
|
|
27
|
-
await new Promise((r) => setTimeout(r, delay));
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
12
|
var PinataBackend = class {
|
|
31
13
|
pinata;
|
|
32
14
|
gateway;
|
|
@@ -0,0 +1,52 @@
|
|
|
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 pinata-url-provider worker. Used when no worker URL is supplied, so
|
|
8
|
+
* callers can upload via signed URLs with zero configuration. Point at your own
|
|
9
|
+
* deployment by passing a workerUrl.
|
|
10
|
+
*/
|
|
11
|
+
declare const DEFAULT_SIGNED_URL_WORKER = "https://pinata-url-provider.fangorn-0be.workers.dev";
|
|
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 we POST the file to — the JWT never leaves
|
|
24
|
+
* the worker. Reads need no auth: every Fangorn block is public content, so we
|
|
25
|
+
* fetch it 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 (your own JWT) if you need them.
|
|
31
|
+
*/
|
|
32
|
+
declare class SignedUrlBackend implements MetadataStorage {
|
|
33
|
+
private readonly signer;
|
|
34
|
+
private readonly gateway;
|
|
35
|
+
private readonly workerUrl;
|
|
36
|
+
constructor(workerUrl: string | undefined, signer: SignedUrlSigner, gateway: string);
|
|
37
|
+
/** Run the worker challenge handshake → one-time presigned upload URL + network. */
|
|
38
|
+
private requestUploadUrl;
|
|
39
|
+
private workerJson;
|
|
40
|
+
/** Upload bytes via a fresh one-time presigned URL; returns the pinned CID. */
|
|
41
|
+
private uploadBytes;
|
|
42
|
+
put(data: unknown, meta?: StorageMeta): Promise<string>;
|
|
43
|
+
putFile(bytes: Uint8Array, name: string): Promise<string>;
|
|
44
|
+
putBlock(block: RawBlock): Promise<void>;
|
|
45
|
+
getFile(uri: string): Promise<Uint8Array>;
|
|
46
|
+
getRawBlock(uri: string): Promise<Uint8Array>;
|
|
47
|
+
get<T>(uri: string): Promise<T>;
|
|
48
|
+
putMany(): Promise<Record<string, string>>;
|
|
49
|
+
delete(): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
//#endregion
|
|
52
|
+
export { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner };
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { fetchRawByCid, serialize, withUploadRetry } from "./utils.js";
|
|
2
|
+
|
|
3
|
+
//#region src/providers/storage/signed-url.ts
|
|
4
|
+
/**
|
|
5
|
+
* The hosted pinata-url-provider worker. Used when no worker URL is supplied, so
|
|
6
|
+
* callers can upload via signed URLs with zero configuration. Point at your own
|
|
7
|
+
* deployment by passing a workerUrl.
|
|
8
|
+
*/
|
|
9
|
+
const DEFAULT_SIGNED_URL_WORKER = "https://pinata-url-provider.fangorn-0be.workers.dev";
|
|
10
|
+
/** A human-readable reason from a worker error response, detail included. */
|
|
11
|
+
function workerError(r) {
|
|
12
|
+
const base = r.error ?? "unknown error";
|
|
13
|
+
return r.detail ? `${base} (${r.detail})` : base;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Storage backend for users who don't bring their own Pinata JWT.
|
|
17
|
+
*
|
|
18
|
+
* Uploads go through the pinata-url-provider Worker: prove wallet ownership by
|
|
19
|
+
* signing the worker's challenge, and it hands back a short-lived, single-use
|
|
20
|
+
* Pinata presigned upload URL that we POST the file to — the JWT never leaves
|
|
21
|
+
* the worker. Reads need no auth: every Fangorn block is public content, so we
|
|
22
|
+
* fetch it straight from a public IPFS gateway by CID (privacy is cryptographic,
|
|
23
|
+
* not access-controlled). Each upload runs a fresh handshake because the
|
|
24
|
+
* presigned URL is one-time and expires in minutes.
|
|
25
|
+
*
|
|
26
|
+
* JWT-only operations (server-side metadata queries / deletes) are unavailable
|
|
27
|
+
* here — switch to a PinataBackend (your own JWT) if you need them.
|
|
28
|
+
*/
|
|
29
|
+
var SignedUrlBackend = class {
|
|
30
|
+
workerUrl;
|
|
31
|
+
constructor(workerUrl, signer, gateway) {
|
|
32
|
+
this.signer = signer;
|
|
33
|
+
this.gateway = gateway;
|
|
34
|
+
this.workerUrl = workerUrl?.trim() ? workerUrl : DEFAULT_SIGNED_URL_WORKER;
|
|
35
|
+
}
|
|
36
|
+
/** Run the worker challenge handshake → one-time presigned upload URL + network. */
|
|
37
|
+
async requestUploadUrl(size, uploadId) {
|
|
38
|
+
const address = this.signer.address;
|
|
39
|
+
const challenge = await this.workerJson({
|
|
40
|
+
address,
|
|
41
|
+
size,
|
|
42
|
+
uploadId
|
|
43
|
+
});
|
|
44
|
+
if (!challenge.challenge) throw new Error(`Presigned-URL worker did not issue a challenge: ${workerError(challenge)}`);
|
|
45
|
+
const signature = await this.signer.signMessage(challenge.challenge);
|
|
46
|
+
const grant = await this.workerJson({
|
|
47
|
+
address,
|
|
48
|
+
message: challenge.challenge,
|
|
49
|
+
signature,
|
|
50
|
+
size,
|
|
51
|
+
uploadId
|
|
52
|
+
});
|
|
53
|
+
if (!grant.ok || !grant.uploadUrl) throw new Error(`Presigned-URL worker denied an upload URL: ${workerError(grant)}`);
|
|
54
|
+
return {
|
|
55
|
+
uploadUrl: grant.uploadUrl,
|
|
56
|
+
network: grant.network ?? "public"
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
async workerJson(body) {
|
|
60
|
+
const res = await fetch(this.workerUrl, {
|
|
61
|
+
method: "POST",
|
|
62
|
+
headers: { "content-type": "application/json" },
|
|
63
|
+
body: JSON.stringify(body)
|
|
64
|
+
});
|
|
65
|
+
return await res.json().catch(() => null) ?? { error: `HTTP ${res.status.toString()}` };
|
|
66
|
+
}
|
|
67
|
+
/** Upload bytes via a fresh one-time presigned URL; returns the pinned CID. */
|
|
68
|
+
uploadBytes(bytes, name, type) {
|
|
69
|
+
const uploadId = globalThis.crypto.randomUUID();
|
|
70
|
+
return withUploadRetry(name, async () => {
|
|
71
|
+
const { uploadUrl, network } = await this.requestUploadUrl(bytes.length, uploadId);
|
|
72
|
+
const fd = new FormData();
|
|
73
|
+
fd.append("network", network);
|
|
74
|
+
fd.append("file", new File([bytes], name, { type }));
|
|
75
|
+
const res = await fetch(uploadUrl, {
|
|
76
|
+
method: "POST",
|
|
77
|
+
body: fd
|
|
78
|
+
});
|
|
79
|
+
const data = await res.json().catch(() => null);
|
|
80
|
+
if (!res.ok) throw Object.assign(/* @__PURE__ */ new Error(`Pinata upload failed: ${data ? JSON.stringify(data) : "(no body)"}`), { statusCode: res.status });
|
|
81
|
+
const cid = data?.data?.cid;
|
|
82
|
+
if (!cid) throw new Error(`Pinata upload returned no CID: ${JSON.stringify(data)}`);
|
|
83
|
+
return cid;
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async put(data, meta) {
|
|
87
|
+
return this.uploadBytes(new TextEncoder().encode(serialize(data)), meta?.name ?? "file", "text/plain");
|
|
88
|
+
}
|
|
89
|
+
async putFile(bytes, name) {
|
|
90
|
+
return this.uploadBytes(bytes, name, "application/octet-stream");
|
|
91
|
+
}
|
|
92
|
+
async putBlock(block) {
|
|
93
|
+
await this.uploadBytes(block.bytes, block.cid.toString(), "application/octet-stream");
|
|
94
|
+
}
|
|
95
|
+
async getFile(uri) {
|
|
96
|
+
return fetchRawByCid(uri, this.gateway);
|
|
97
|
+
}
|
|
98
|
+
async getRawBlock(uri) {
|
|
99
|
+
return fetchRawByCid(uri, this.gateway);
|
|
100
|
+
}
|
|
101
|
+
async get(uri) {
|
|
102
|
+
const bytes = await fetchRawByCid(uri, this.gateway);
|
|
103
|
+
const text = new TextDecoder().decode(bytes);
|
|
104
|
+
try {
|
|
105
|
+
return JSON.parse(text);
|
|
106
|
+
} catch {
|
|
107
|
+
return text;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
putMany() {
|
|
111
|
+
throw new Error("putMany (batched CAR upload) is not available with signed URLs — provide your own Pinata JWT.");
|
|
112
|
+
}
|
|
113
|
+
delete() {
|
|
114
|
+
throw new Error("delete is not available with signed URLs — provide your own Pinata JWT.");
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
//#endregion
|
|
119
|
+
export { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend };
|
|
@@ -1,12 +1,30 @@
|
|
|
1
1
|
import { PinataBackend } from "./pinata.js";
|
|
2
|
+
import { DEFAULT_SIGNED_URL_WORKER, SignedUrlBackend, SignedUrlSigner } from "./signed-url.js";
|
|
2
3
|
|
|
3
4
|
//#region src/providers/storage/utils.d.ts
|
|
4
5
|
declare function serialize(data: unknown): string;
|
|
5
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>;
|
|
6
24
|
/**
|
|
7
25
|
* Fetch any content by CID from a public IPFS gateway.
|
|
8
26
|
* No auth required — all Fangorn content is public; privacy is cryptographic.
|
|
9
27
|
*/
|
|
10
28
|
declare function retrieveByCid<T>(cid: string, gateway?: string, timeoutSecond?: number): Promise<T>;
|
|
11
29
|
//#endregion
|
|
12
|
-
export { PinataBackend, deserialize, retrieveByCid, serialize };
|
|
30
|
+
export { DEFAULT_SIGNED_URL_WORKER, MAX_UPLOAD_ATTEMPTS, PinataBackend, SignedUrlBackend, SignedUrlSigner, deserialize, fetchRawByCid, isTransientUpload, retrieveByCid, serialize, withUploadRetry };
|
|
@@ -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 };
|
package/lib/types/index.d.ts
CHANGED