Skip to content

Instantly share code, notes, and snippets.

@stevedylandev
Created April 10, 2024 17:36
Show Gist options
  • Save stevedylandev/65e09c479326622c3f3b3a37b5396c9e to your computer and use it in GitHub Desktop.
Save stevedylandev/65e09c479326622c3f3b3a37b5396c9e to your computer and use it in GitHub Desktop.
Predetermine a CID before uploading to Pinata
import { CID } from 'multiformats/cid'
import * as raw from 'multiformats/codecs/raw'
import { sha256 } from 'multiformats/hashes/sha2'
const JWT = "YOUR_PINATA_JWT"
async function main(){
try {
const text = "Hello World!";
const blob = new Blob([text], { type: "text/plain" });
const unit8array = new Uint8Array(await blob.arrayBuffer());
const bytes = raw.encode(unit8array)
const hash = await sha256.digest(bytes)
const cid = CID.create(1, raw.code, hash)
console.log(cid.toString())
} catch(error) {
console.log(error)
}
}
async function pinFileToIPFS() {
try {
const text = "Hello World!";
const blob = new Blob([text], { type: "text/plain" });
const data = new FormData();
data.append("file", blob);
const options = JSON.stringify({
cidVersion: 1
})
data.append("pinataOptions", options)
const res = await fetch("https://api.pinata.cloud/pinning/pinFileToIPFS", {
method: "POST",
headers: {
Authorization: `Bearer ${JWT}`,
},
body: data
});
const resData = await res.json();
console.log(resData.IpfsHash);
} catch (error) {
console.log(error);
}
};
main()
pinFileToIPFS()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment