Skip to content

Commit

Permalink
Merge pull request #11 from mediolano-app/ipfs
Browse files Browse the repository at this point in the history
Ipfs
  • Loading branch information
PedroRosalba authored Oct 7, 2024
2 parents c033cf0 + c342fba commit 3631b4b
Show file tree
Hide file tree
Showing 11 changed files with 796 additions and 85 deletions.
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@
},
"dependencies": {
"framer-motion": "^11.5.6",
"lucide-react": "^0.446.0",
"lucide-react": "^0.445.0",
"pinata-web3": "^0.5.0",
"postcss": "^8.4.38"
}
}
73 changes: 73 additions & 0 deletions packages/nextjs/app/api/forms-ipfs/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { NextRequest, NextResponse } from 'next/server';
import { IP } from '~~/app/registerIP/page';
import { pinataClient } from '~~/utils/simpleNFT/pinataClient';

// export const config = {
// api: {
// bodyParser: false,
// },
// };

export async function POST(request: NextRequest){
try{
// const mockedData = {
// title: 'mocktitle',
// description: 'mockdescription',
// authors: 'mockauthors',
// ipType: 'mockiptype',
// uploadFile:''
// };

// const data4 = JSON.parse(await request.json());
// console.log(data4);

const data = await request.formData();

const title = data.get('title') as unknown as string;
const description = data.get('description') as unknown as string;
const authors = data.getAll('authors');
const ipType = data.get('ipType') as string;
const uploadFile = data.get('uploadFile') as File | null;

// const data2 = request.body;
// console.log(data2);

// console.log("--------------");
// const data3 = request.text();
// console.log(data3);

//const file: File | null = data.get("file") as unknown as File;

// const uploadMockedData = await pinataClient.upload.json(mockedData);
// const mockedUrl = await pinataClient.gateways.convert(uploadMockedData.IpfsHash);
// console.log(mockedUrl);

// console.log('Received data:', { title, description, authors, ipType, uploadFile: uploadFile?.name });

const userObject = {
title,
description,
authors,
ipType,
uploadFile: uploadFile ? uploadFile.name : null,
};

// console.log('Attempting to upload to Pinata:', userObject);

const uploadData = await pinataClient.upload.json(userObject);
// console.log('Pinata upload successful:', uploadData);
const url = await pinataClient.gateways.convert(uploadData.IpfsHash);
// console.log('Converted IPFS URL:', url);

//aqui eu chamo a função de MINTAR
return NextResponse.json({ ipfsHash: uploadData.IpfsHash, url }, { status: 200 });
// const data = await request.formData();
} catch (e) {
console.log(e);
return NextResponse.json(
{ error: "Internal Server Error" },
{ status: 500 }
);
}
}
97 changes: 62 additions & 35 deletions packages/nextjs/app/api/upload-ipfs/route.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,70 @@
import { NextApiRequest, NextApiResponse } from 'next';
import { ipfsClient } from '~~/utils/simpleNFT/ipfs';
import { NextRequest, NextResponse } from 'next/server';
// import { ipfsClient } from '~~/utils/simpleNFT/ipfs';
import { IP } from '~~/app/registerIP/page';
import { pinataClient } from '~~/utils/simpleNFT/pinataClient';

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === 'POST') {
const { title, description, authors, ipType }: IP = req.body;
export const config = {
api: {
bodyParser: false,
},
};

export async function POST(request: NextRequest){
try{

const data = await request.formData();
const file: File | null = data.get("file") as unknown as File;
const uploadData = await pinataClient.upload.file(file);
const url = await pinataClient.gateways.convert(uploadData.IpfsHash);

console.log(url);
return NextResponse.json(url, { status: 200 });
} catch (e) {
console.log(e);
return NextResponse.json(
{ error: "Internal Server Error" },
{ status: 500 }
);
}
}

// export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// if (req.method === 'POST') {
// const { title, description, authors, ipType }: IP = req.body;

try {
// Upload intellectual property metadata to IPFS
const ipMetadata = {
title,
description,
authors,
ipType,
};
// try {
// // Upload intellectual property metadata to IPFS
// const ipMetadata = {
// title,
// description,
// authors,
// ipType,
// };

const added = await ipfsClient.add(JSON.stringify(ipMetadata));
const ipfsHash = added.path;
// const added = await ipfsClient.add(JSON.stringify(ipMetadata));
// const ipfsHash = added.path;

// Generate NFT metadata
const nftMetadata = {
name: title,
description: description,
authors: authors,
ipfsHash,
image: `https://ipfs.infura.io/ipfs/${ipfsHash}`, // Optional: if file is an image
};
// // Generate NFT metadata
// const nftMetadata = {
// name: title,
// description: description,
// authors: authors,
// ipfsHash,
// image: `https://ipfs.infura.io/ipfs/${ipfsHash}`, // Optional: if file is an image
// };

// Optionally: Upload NFT metadata to IPFS
const metadataAdded = await ipfsClient.add(JSON.stringify(nftMetadata));
const metadataHash = metadataAdded.path;
// // Optionally: Upload NFT metadata to IPFS
// const metadataAdded = await ipfsClient.add(JSON.stringify(nftMetadata));
// const metadataHash = metadataAdded.path;

res.status(200).json({ metadataHash, nftMetadata });
} catch (error) {
console.error('Error uploading to IPFS:', error);
res.status(500).json({ error: 'Failed to upload to IPFS' });
}
} else {
res.setHeader('Allow', ['POST']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
// res.status(200).json({ metadataHash, nftMetadata });
// } catch (error) {
// console.error('Error uploading to IPFS:', error);
// res.status(500).json({ error: 'Failed to upload to IPFS' });
// }
// } else {
// res.setHeader('Allow', ['POST']);
// res.status(405).end(`Method ${req.method} Not Allowed`);
// }
// }
Empty file.
100 changes: 68 additions & 32 deletions packages/nextjs/app/registerIP/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,9 @@ const registerIP = () => {
const { address: connectedAddress, isConnected, isConnecting } = useAccount();
const [status, setStatus] = useState("Mint NFT");
const [ipfsHash, setipfsHash] = useState("");
const [loading, setLoading] = useState(false);

const [file, setFile] = useState<File>();

const { writeAsync: mintItem } = useScaffoldWriteContract({
contractName: "YourCollectible",
Expand Down Expand Up @@ -83,12 +86,17 @@ const registerIP = () => {
ipType: '',
});

const [loading, setLoading] = useState(false);

const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
const { name, value } = e.target;
setIpData((prev) => ({ ...prev, [name]: value }));
console.log(e.target);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>
// | HTMLTextAreaElement>
) => {

// const { name, value } = e.target;
// setIpData((prev) => ({ ...prev, [name]: value }));
// console.log(e.target);

setFile(e.target?.files?.[0]);

};

const getNextSubmissionId = () => {
Expand All @@ -103,24 +111,48 @@ const registerIP = () => {
};


const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
event.preventDefault(); // Prevent form from refreshing the page

const handleSubmit = async (
// event: FormEvent<HTMLFormElement>
) => {
// event.preventDefault(); // Prevent form from refreshing the page
try {
const response = await fetch('/api/upload-ipfs', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(ipData),
if (!file) {
alert("No file selected");
return;
}

setLoading(true);
const data = new FormData();
data.set("file", file);
const uploadRequest = await fetch("/api/forms-ipfs", {
method: "POST",
body: data,
});
const data = await response.json();
setipfsHash(data.metadataHash);

} catch (error) {
console.error('Error uploading to IPFS:', error);
const ipfsUrl = await uploadRequest.json();
setipfsHash(ipfsUrl);
setLoading(false);
} catch (e) {
console.log(e);
setLoading(false);
alert("Trouble uploading file");
}
setLoading(false);
// try {
// const response = await fetch('/api/upload-ipfs', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify(ipData),
// });
// console.log("POST done, waiting for response");
// const data = await response.json();
// setipfsHash(data.metadataHash);

// } catch (error) {
// console.error('Error uploading to IPFS:', error);
// }
// setLoading(false);


// const formData = new FormData(event.currentTarget); // Use FormData to access form fields

Expand All @@ -142,21 +174,23 @@ const registerIP = () => {

};


return (

<>
<div className="flex items-center flex-col pt-10">
<div className="">
<h1 className="text-3xl font-bold mb-6">Register Your Asset</h1>
</div>
</div>


<div className="flex justify-center">
{!isConnected || isConnecting ? (
<CustomConnectButton />
) : (
</div>

// <div className="flex justify-center">
// {!isConnected || isConnecting ? (
// <CustomConnectButton />
// ) : (



<div className="">

<Card className="bg-main border-accent/50 rounded-full" >
Expand Down Expand Up @@ -260,11 +294,13 @@ const registerIP = () => {

)}
</div>




</>
// </>
<main className="w-full min-h-screen m-auto flex flex-col justify-center items-center">
<input type="file" onChange={handleChange} />
<button disabled={loading} onClick={handleSubmit}>
{loading ? "Uploading..." : "Upload"}
</button>
</main>
);
};

Expand Down
Loading

0 comments on commit 3631b4b

Please sign in to comment.