-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipfs-uploader.js
68 lines (60 loc) · 2.08 KB
/
ipfs-uploader.js
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
63
64
65
66
67
68
/*
Uploads the metadata of an asset to IPFS, using Pinata
The image of the asset is uploaded first, so that its IPFS
address can be used in the asset image metadata field
*/
require('dotenv').config();
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
// Pinata API headers
const headers = {
pinata_api_key: process.env.PINATA_API_KEY,
pinata_secret_api_key: process.env.PINATA_API_SECRET,
};
async function uploadToIPFS(filePath) {
try {
const data = new FormData();
data.append('file', fs.createReadStream(filePath));
const response = await axios.post('https://api.pinata.cloud/pinning/pinFileToIPFS', data, { headers: { ...headers, ...data.getHeaders() } });
return response.data.IpfsHash;
} catch (error) {
console.error('Error uploading file to IPFS:', error);
return null;
}
}
async function main() {
// Example usage for uploading an image
const imagePath = 'imgs/weapon.jpg'; // Path to the image file
const imageHash = await uploadToIPFS(imagePath); // Upload image
if (imageHash) {
console.log('\n-------------');
console.log(`Image uploaded to IPFS: ipfs://${imageHash}`);
// Prepare metadata
const metadata = {
name: 'Your NFT Name',
description: 'Description of your NFT',
image: `ipfs://${imageHash}`, // Link image hash in metadata
attributes: [
{ trait_type: 'Attr 1', value: 'Value 1' },
{ trait_type: 'Attr 2', value: 'Value 2' },
],
};
// Save metadata to a file
const metadataPath = 'metadata.json';
fs.writeFileSync(metadataPath, JSON.stringify(metadata));
// Upload metadata
const metadataHash = await uploadToIPFS(metadataPath);
if (metadataHash) {
console.log('-------------');
console.log('Metadata uploaded to IPFS');
console.log(`IPFS address (to pass to single-mint.js): ipfs://${metadataHash}`);
console.log('-------------\n');
} else {
console.log('Failed to upload metadata to IPFS');
}
} else {
console.log('Failed to upload image to IPFS');
}
}
main();