일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 스마트컨트렉트 예약어 함수이름 중복
- 체인의정석
- 티스토리챌린지
- Vue.js
- 컨트렉트 동일한 함수이름 호출
- chainlink 설명
- SBT표준
- 스마트컨트렉트테스트
- multicall
- 머신러닝기초
- git rebase
- 계정추상화
- erc4337 contract
- 컨트렉트 배포 자동화
- 오블완
- ethers
- ethers v6
- ethers websocket
- erc4337
- ambiguous function description
- Vue
- 러스트기초
- 스마트 컨트렉트 함수이름 중복
- rust 기초
- 러스트 기초 학습
- ethers type
- 스마트컨트렉트 함수이름 중복 호출
- 러스트 기초
- ethers typescript
- vue기초
- Today
- Total
체인의정석
IPFS에 데이터 올리는 방법 본문
목표 : Filecoin을 통해 저장되는 형태로 IPFS에 NFT메타데이터 올리기
1. NFT.storage
https://nft.storage/docs/#using-the-javascript-api
NFT storage는 javascript 예제가 있었으나 mjs 파일로 되어 있었다.
mjs 파일을 처음들어서 살펴보니 ECMAS를 사용하는 경우 명시하는 파일 같았다.
NFT storage 모듈 자체에서 mjs를 가져와서 사용하도록 되어 있기 때문에 node.js와 mjs만 써서 실행을 했을 때는 성공을 했지만 express를 써서 했을 때는 실패를하였다.
https://ui.toast.com/weekly-pick/ko_20190805
Node.js로 ECMAScript 모듈을 사용하는 방법
Kevin Dangoor가 CommonJS 프로젝트를 시작한 후 2009년부터 어떻게 하면 자바스크립트가 웹 브라우저에서 실행되는 것 뿐만 아니라, 범위가 확대되어 백엔드 영역을 포함한 애플리케이션 개발에도 적
ui.toast.com
// Import the NFTStorage class and File constructor from the 'nft.storage' package
import { NFTStorage, File } from 'nft.storage'
// The 'mime' npm package helps us set the correct file type on our File objects
import mime from 'mime'
// The 'fs' builtin module on Node.js provides access to the file system
import fs from 'fs'
// The 'path' module provides helpers for manipulating filesystem paths
import path from 'path'
// Paste your NFT.Storage API key into the quotes:
const NFT_STORAGE_KEY = process.env.NFTSTORE_APIKEY;
/**
* Reads an image file from `imagePath` and stores an NFT with the given name and description.
* @param {string} imagePath the path to an image file
* @param {string} name a name for the NFT
* @param {string} description a text description for the NFT
*/
export async function storeNFT(imageName, name, description) {
//imagedirectoryName
const __dirname = path.dirname(new URL(import.meta.url).pathname);
console.log("__dirname >>", __dirname);
// load the file from disk
const image = await fileFromPath(`${__dirname}/../../../../data/articles/${imageName}`)
// create a new NFTStorage client using our API key
const nftstorage = new NFTStorage.NFTStorage({ token: NFT_STORAGE_KEY })
const response = await nftstorage.store({
image,
name,
description,
})
console.log("response is >>", response);
// call client.store, passing in the image & metadata
return response
}
/**
* A helper to read a file from a location on disk and return a File object.
* Note that this reads the entire file into memory and should not be used for
* very large files.
* @param {string} filePath the path to a file to store
* @returns {File} a File object containing the file content
*/
async function fileFromPath(filePath) {
const content = await fs.promises.readFile(filePath)
const type = mime.getType(filePath)
return new nftstorage.File([content], path.basename(filePath), { type })
}
해당 경우 예제를 거의 똑같이 사용한 것인데 다음과 같이 작성하면 된다. 해당 예제의 경우 아마 프론트에서 사용하면 잘 될것 같다.
2. Web3.strorage
https://web3.storage/
js 파일이 지원되는 예제를 찾다가 2번째 방안을 찾았다.
사이트에 예제가 나와있어서 바로 시도하기 좋았다. 근데 여기도 mjs를 써서 node.js에 쓰려면 express 대신 아래처럼 직접 커스터마이징 해서 써야 한다.
https://github.com/mondyfy/ipfsupload/tree/main
GitHub - mondyfy/ipfsupload: IPFS upload in NodeJs
IPFS upload in NodeJs. Contribute to mondyfy/ipfsupload development by creating an account on GitHub.
github.com
3. 직접 구현하기
결국 다른 api가 나와있는 현 상황에서 exrpess를 써서 하는 방식은 직접 구현하는 방법 뿐이다.
예제도 한번 찾아봤다.
https://github.com/gatij10/ipfs-server-setup/blob/master/app.js
접근은 infrua의 엔드 포인트를 써서 한다.
Ethereum API | IPFS API & Gateway | ETH Nodes as a Service | Infura
Infura's development suite provides instant, scalable API access to the Ethereum and IPFS networks. Connect your app to Ethereum and IPFS now, for free!
app.infura.io
이건 신용카드 정보를 등록해야 한다. 5GB까지는 무료라고 한다.
보아하니 ipfs-api 라는 모듈이 있는것 같다.
IPFS 사용법 (nodejs, Ubuntu)
목록 IPFS-#1.IPFS 사용법(CLI,Ubuntu) IPFS-#2.IPFS 사용법(nodejs,Ubuntu) IPFS 사용법 IPFS를 javascript로 nodejs에서 실행해본다. ipfs-api 모듈 설치 sudo npm install -save ipfs-api ipfs 연결 const ipfsAPI = require('ipfs-api'); const
lbm93.tistory.com
이건 근데 deprecated 되었다고 하고
https://www.npmjs.com/package/ipfs-http-client
ipfs-http-client
A client library for the IPFS HTTP API. Latest version: 60.0.1, last published: 5 months ago. Start using ipfs-http-client in your project by running `npm i ipfs-http-client`. There are 543 other projects in the npm registry using ipfs-http-client.
www.npmjs.com
ipfs-http-client가 최신이라고한다.
https://github.com/ysheokorea/IPFS-Node.js
GitHub - ysheokorea/IPFS-Node.js
Contribute to ysheokorea/IPFS-Node.js development by creating an account on GitHub.
github.com
해당 모듈을 사용한 예제도 발견하였다.
import { path } from '../../app';
const ipfsClient = require('ipfs-http-client');
const projectId = process.env.INFURA_ID;
const projectSecret = process.env.INFURA_SECRET_KEY;
const auth =
'Basic' + Buffer.from(projectId + ':' + projectSecret).toString('base64');
const client = ipfsClient.create({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
});
const __dirname = path.dirname(new URL(import.meta.url).pathname);
const file = await ipfs.add(urlSource(__dirname))
client.add('testing').then((res) => {
console.log(res);
});
이런식으로 사용을 하면 파일을 올릴 수 있다.
다만 해당 모듈도 ECMAS 환경이 있다보니 예전 버전으로 쓰는것이 좋다고 한다.
기타
해당링크에 여러 지원되는 서비스들을 볼 수 있다.
https://ecosystem-wg.notion.site/Getting-Started-With-IPFS-Filecoin-c00526cf97ba4087ba5c3ad5f5337a58
Getting Started With IPFS & Filecoin
Email | Website | Twitter | Discord
ecosystem-wg.notion.site
Estuary
Use any browser and our API to store public data on IPFS and Filecoin.
estuary.tech
const https = require("https");
const fs = require("fs");
const FormData = require("form-data");
const fetch = require("node-fetch");
const key = `YOUR_API_KEY`;
var form = new FormData();
const path = `${__dirname}/YOUR_FILE_ON_YOUR_COMPUTER.mp4`;
form.append("data", fs.createReadStream(path));
const headers = form.getHeaders();
console.log(headers);
fetch("https://upload.estuary.tech/content/add", {
method: "POST",
body: form,
headers: {
Authorization: `Bearer ${key}`,
...headers,
},
})
.then(function(res) {
return res.json();
})
.then(function(json) {
console.log(json);
});
'블록체인 > NFT & BRIDGE' 카테고리의 다른 글
ENS Namehash 만들고 Namehash로 컨트렉트에서 실제 지갑주소 뽑아보기 (0) | 2023.11.27 |
---|---|
ENS 살펴보기 - 공식문서 살펴보기 (0) | 2023.11.23 |
Chainlink functions 사용해보기 (0) | 2023.10.13 |
SBT와 관련된 표준 ERC 정리) ERC-6239: Semantic Soulbound Tokens (0) | 2023.09.16 |
SBT와 관련된 표준 ERC 정리) 소각 권한을 상황에 맞게 분리시켜주는 ERC-5484 (0) | 2023.09.14 |