Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

deal params #48

Merged
merged 1 commit into from
Nov 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions packages/nextjs/app/api/lighthouse/data-depot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// utils/data-depot.ts
import lighthouse from "@lighthouse-web3/sdk";
import fs from "fs";
import path from "path";

const LIGHTHOUSE_API_KEY = process.env.LIGHTHOUSE_API_KEY!;
const dataDepotUrl = "https://data-depot.lighthouse.storage";

const deleteFile = async (filePath: string): Promise<void> => {
try {
await fs.promises.unlink(filePath);
console.log("File deleted successfully");
} catch (error) {
console.error("Error deleting file:", error);
}
};

interface FileParam {
id: string;
fileName: string;
carSize: number;
payloadCid: string;
pieceCid: string;
pieceSize: number;
mimeType: string;
}

export const uploadToLighthouseDataDepot = async (
file: File,
): Promise<{
carLink: string;
carSize: number;
pieceCid: string;
pieceSize: number;
mimeType: string;
}> => {
try {
const uploadDir = path.join(process.cwd(), "uploads");
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir);
}
const filePath = path.join(uploadDir, file.name);
const buffer = Buffer.from(await file.arrayBuffer());
await fs.promises.writeFile(filePath, buffer);

const authToken = await lighthouse.dataDepotAuth(LIGHTHOUSE_API_KEY);
let response = await lighthouse.viewCarFiles(1, authToken.data.access_token);
let fileParams: FileParam[] = response.data.filter((item: any) => item.fileName === file.name);

if (!fileParams.length) {
await lighthouse.createCar(filePath, authToken.data.access_token);

for (let i = 0; i < 180; i++) {
response = await lighthouse.viewCarFiles(1, authToken.data.access_token);
fileParams = response.data.filter((item: any) => item.fileName === file.name);

if (fileParams.length && fileParams[0].pieceCid) {
break;
}

await new Promise(resolve => setTimeout(resolve, 5000));
}
}

if (fileParams.length === 0 || !fileParams[0].pieceCid) {
throw new Error("Failed to upload file to Lighthouse Data Depot.");
}

const carLink = `${dataDepotUrl}/api/download/download_car?fileId=${fileParams[0].id}.car`;
const pieceData = {
carLink,
carSize: fileParams[0].carSize,
pieceCid: fileParams[0].pieceCid,
pieceSize: fileParams[0].pieceSize,
mimeType: fileParams[0].mimeType,
};

await deleteFile(filePath);
return pieceData;
} catch (err) {
console.error(err);
throw new Error("Upload failed");
}
};
23 changes: 23 additions & 0 deletions packages/nextjs/app/api/lighthouse/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { NextRequest, NextResponse } from "next/server";
import { uploadToLighthouseDataDepot } from "./data-depot";
import dotenv from "dotenv";

dotenv.config();

export async function POST(request: NextRequest) {
try {
const form = await request.formData();
const file = form.get("file") as File;

if (!file) {
return NextResponse.json({ error: "No file provided" }, { status: 400 });
}

const result = await uploadToLighthouseDataDepot(file);

return NextResponse.json({ result }, { status: 200 });
} catch (error) {
console.error(error);
return NextResponse.json({ error: (error as Error).message }, { status: 500 });
}
}
4 changes: 4 additions & 0 deletions packages/nextjs/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use client";

import Link from "next/link";
import UploadForm from "../components/UploadForm";
import type { NextPage } from "next";
import { useAccount } from "wagmi";
import { BugAntIcon, MagnifyingGlassIcon } from "@heroicons/react/24/outline";
Expand All @@ -17,6 +18,9 @@ const Home: NextPage = () => {
<span className="block text-2xl mb-2">Welcome to</span>
<span className="block text-4xl font-bold">FIL-Frame</span>
</h1>
<div>
<UploadForm />
</div>
<div className="flex justify-center items-center space-x-2 flex-col sm:flex-row">
<p className="my-2 font-medium">Connected Address:</p>
<Address address={connectedAddress} />
Expand Down
91 changes: 91 additions & 0 deletions packages/nextjs/components/UploadForm.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// components/UploadForm.tsx
import { useState } from "react";

const UploadForm = () => {
const [file, setFile] = useState<File | null>(null);
const [response, setResponse] = useState<string>("");
const [error, setError] = useState<string>("");
const [isUploading, setIsUploading] = useState<boolean>(false);

const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files[0]) {
setFile(e.target.files[0]);
}
};

const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!file) {
setError("Please select a file.");
return;
}

setIsUploading(true);
setError("");
setResponse("");

const formData = new FormData();
formData.append("file", file);

try {
const res = await fetch("/api/lighthouse", {
method: "POST",
body: formData,
});

const data = await res.json();

if (res.ok) {
setResponse(JSON.stringify(data.result, null, 2));
} else {
setError(data.error || "Upload failed.");
}
} catch (err) {
setError("An error occurred.");
} finally {
setIsUploading(false);
}
};

return (
<div className="max-w-md mx-auto bg-base-100 shadow-lg rounded-lg p-6">
<h2 className="text-2xl font-semibold mb-4 text-center text-primary">Get Deal Params</h2>
<form onSubmit={handleSubmit} className="flex flex-col space-y-4">
<div>
<label htmlFor="file-upload" className="block text-sm font-medium text-secondary mb-1">
Select File
</label>
<input
type="file"
id="file-upload"
onChange={handleFileChange}
className="w-full px-3 py-2 border border-secondary rounded-md focus:outline-none focus:ring-2 focus:ring-primary"
/>
</div>
<button
type="submit"
className={`w-full py-2 px-4 bg-primary text-base-100 rounded-md hover:bg-primary-focus transition ${
isUploading ? "opacity-50 cursor-not-allowed" : ""
}`}
disabled={isUploading}
>
{isUploading ? "Uploading..." : "Upload"}
</button>
</form>
{response && (
<div className="mt-6 bg-success bg-opacity-20 border border-success text-success p-4 rounded-md">
<h3 className="text-lg font-medium">Upload Successful</h3>
<pre className="mt-2 text-sm whitespace-pre-wrap break-words">{response}</pre>
</div>
)}
{error && (
<div className="mt-6 bg-error bg-opacity-20 border border-error text-error p-4 rounded-md">
<h3 className="text-lg font-medium">Error</h3>
<p className="mt-2 text-sm">{error}</p>
</div>
)}
</div>
);
};

export default UploadForm;
1 change: 1 addition & 0 deletions packages/nextjs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
},
"dependencies": {
"@heroicons/react": "^2.1.5",
"@lighthouse-web3/sdk": "0.2.3",
"@rainbow-me/rainbowkit": "2.1.6",
"@tanstack/react-query": "^5.28.6",
"@uniswap/sdk-core": "^4.0.1",
Expand Down
Loading
Loading