-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArweaveSDK.js
More file actions
62 lines (52 loc) · 1.94 KB
/
ArweaveSDK.js
File metadata and controls
62 lines (52 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import fs from "fs";
import path from "path";
import Arweave from "arweave";
import mime from "mime";
import { TurboFactory, ArweaveSigner } from "@ardrive/turbo-sdk/node";
// const gateway = "https://arweave.net";
const gateway = "https://v1.filedust.workers.dev";
const arweave = Arweave.init({
host: gateway,
port: 443,
protocol: "https",
});
const WALLET_PATH = path.resolve("wallet.json");
async function initTurboClient() {
let jwk;
if (fs.existsSync(WALLET_PATH)) {
jwk = JSON.parse(fs.readFileSync(WALLET_PATH, "utf-8"));
} else {
console.log("未找到 wallet.json,正在生成新钱包...");
jwk = await arweave.wallets.generate();
fs.writeFileSync(WALLET_PATH, JSON.stringify(jwk, null, 2));
console.log("新钱包生成并保存到 wallet.json(请备份!)");
}
const signer = new ArweaveSigner(jwk);
const turbo = TurboFactory.authenticated({ signer });
return turbo;
}
export async function uploadDataStream(data, filename) {
if (!Buffer.isBuffer(data)) {
throw new Error("data 必须是 Buffer 类型");
}
const dataSize = data.byteLength;
const contentType = mime.getType(filename) || "application/octet-stream";
const turbo = await initTurboClient();
try {
const uploadResult = await turbo.uploadFile({
fileStreamFactory: () => data,
fileSizeFactory: () => dataSize,
dataItemOpts: {
tags: [
{ name: "Content-Type", value: contentType },
{ name: "App-Name", value: "FileDust" },
{ name: "File-Name", value: filename },
{ name: "Uploaded-With", value: "@ardrive/turbo-sdk" },
],
},
});
return gateway + "/" + uploadResult.id;
} catch (error) {
throw new Error(`上传失败: ${error.message} (File: ${filename}, Size: ${dataSize})`);
}
}