
Next.js와 Helius의 DAS API로 Solana 포트폴리오 뷰어를 구축하는 방법
목표
이 튜토리얼에서는 Helius의 DAS API를 사용하여 Solana 지갑의 콘텐츠를 표시하는 프런트엔드 애플리케이션을 구축합니다. 메타데이터, 컬렉션 정보, 대체 가능 토큰 가격을 포함해 다양한 토큰 유형과 상세 정보를 보여줍니다.
필요한 단계를 하나씩 살펴보며 Galleria와 유사한 서비스를 구축하는 방법을 안내합니다.
사전 요구 사항
- Helius API 키
- React에 대한 이해
- Next.js 사용 경험
사용 기술 개요
- Next.js: 서버 사이드 렌더링 애플리케이션을 구축하기 위한 React 프레임워크입니다.
- Helius의 DAS API: Solana 토큰 데이터에 접근하기 위한 종합 API입니다.
- Vercel: Next.js 애플리케이션을 호스팅하는 플랫폼입니다.
- Tailwind CSS: 스타일링을 위한 유틸리티 우선 CSS 프레임워크입니다.
프로젝트 설정
DAS API
DAS API는 Helius가 제공하는 오픈 소스 사양이자 시스템입니다. Solana 블록체인의 디지털 자산과 상호작용할 수 있는 간단한 인터페이스를 제공합니다. 대체 가능 토큰, 일반 NFT, 압축 NFT 등 다양한 토큰 유형을 지원하며 오프체인 메타데이터 인덱싱 같은 기능도 제공합니다.
API 키 설정
Helius API 키를 발급받으려면 Helius 개발자 포털을 방문하세요. 시작 방법은 다음과 같습니다.
- Solana 지갑, Google 계정 또는 GitHub 계정으로 계정을 만듭니다.
- 로그인하면 API 키를 생성하라는 안내가 표시됩니다.
- 이 키는 API 호출에 사용되므로 안전하게 보관하세요.
Next.js 애플리케이션 구축
1단계: Next.js 프로젝트 설정
Tailwind를 사용하는 새 Next.js 앱 만들기
npx create-next-app@latest helius-portfolio --typescript --eslint다음 구성을 사용하세요.
이렇게 하면 스타일링에 Tailwind CSS를 사용하고 새로운 App router도 활용할 수 있습니다.
cd helius-portfolio2단계: 컴포넌트 만들기
구조를 체계적으로 관리하려면 app 디렉터리에 components 폴더를 만드세요.
SearchBar 컴포넌트(components/SearchBar.js):
이 컴포넌트는 지갑 주소에 대한 사용자 입력을 처리합니다. 주소 상태를 관리하는 useState 훅과 폼 제출 후 이동을 처리하는 **useRouter**을 사용합니다. Tailwind CSS 클래스로 폼을 세련되게 스타일링합니다.
TokenCard 컴포넌트(components/TokenCard.js):
이 컴포넌트는 토큰 정보를 표시하도록 설계되었습니다. 대체 가능 토큰과 대체 불가능 토큰에 서로 다른 레이아웃을 조건부로 렌더링하며, **../types/Token**의 Token 및 Attribute 타입을 사용합니다.
SearchBar 컴포넌트:
components/searchBar.ts
import { useRouter } from "next/navigation";
import React, { useState } from "react";
export default function SearchBar() {
const router = useRouter();
const [address, setAddress] = useState("");
function handleSubmit(event: React.FormEvent) {
event.preventDefault();
router.push(`/${address}`);
}
return (
setAddress(e.target.value)}
className="border-2 border-gray-300 rounded-md w-full text-center px-4 py-2 mb-4 flex-grow text-black"
/>
Search
);
}TokenCard 컴포넌트:
이 컴포넌트는 API에서 받은 토큰 데이터를 파싱하고 각 토큰 카드에 관련 정보를 표시합니다.
아래 예시에서는 각 대체 가능 토큰의 이미지, 심볼, 수량, 가치와 같은 기본 정보를 보여줍니다. 대체 불가능 토큰에는 이미지, 이름, 설명, 속성을 표시합니다. API가 제공하는 모든 정보를 추출하여 카드에 표시할 수 있습니다.
예를 들어 cNFT에는 압축 관련 정보를, 인스크립션된 자산에는 인스크립션 정보를 표시할 수 있습니다. 활용할 수 있는 구체적인 정보는 DAS 문서에서 자세히 확인하세요.
"use client";
import React from "react";
import { Token, Attribute } from "../types/Token";
interface TokenCardProps {
token: Token;
tokenType: string;
}
const TokenCard = ({ token, tokenType }: TokenCardProps) => {
return (
{/* Other token information */}
{tokenType === "fungible" ? (
{token.content.metadata.symbol}
{/* {token.content.metadata.description} */}
Amount:{token.token_info.balance}
{token.token_info.price_info?.total_price ? (
Value: ${token.token_info.price_info.total_price}
) : null}
) : (
{token.content.metadata.name}
{token.content.metadata.description}
{token.content.metadata?.attributes?.map(
(attribute: Attribute, index: number) => (
{attribute.trait_type}: {attribute.value}
)
)}
)}
);
}
export default TokenCard;3단계: DAS에서 데이터 가져오기
DAS API의 searchAssets 메서드를 사용하여 토큰 데이터를 가져옵니다. 이 메서드는 유연하므로 지갑 주소와 토큰 유형 같은 조건을 지정할 수 있습니다.
lib 폴더 만들기:
- API 호출을 위해 app 디렉터리에
lib폴더를 만듭니다. - 그 안에
searchAssets.ts파일을 만듭니다.
API 호출 함수 (lib/searchAssets.ts):
- 이 함수는 지갑 주소를 기준으로 토큰을 가져옵니다.
- 잠재적인 오류를 처리하고 디버깅을 위해 응답을 기록합니다.
interface Tokens {
items: any[];
}
const fetchTokens = async (walletAddress: string): Promise => {
const url = `https://mainnet.helius-rpc.com/?api-key=`;
console.log(
`Starting search for tokens for wallet address: ${walletAddress}`
);
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
jsonrpc: "2.0",
id: "my-id",
method: "searchAssets",
params: {
ownerAddress: walletAddress,
tokenType: "all",
displayOptions: {
showCollectionMetadata: true,
},
},
}),
});
const data = await response.json();
console.log(
`Data returned for wallet address ${walletAddress}:`,
data.result
);
return { items: data.result };
} catch (error) {
console.error("Error fetching tokens:", error);
return { items: [] };
}
};
export default fetchTokens;토큰 타입 설정
- DAS API 응답에 사용할 타입을 설정해야 합니다. TypeScript로 작업할 때 권장되는 방식입니다. types라는 폴더를 만들고
token.ts파일을 생성하세요.
export interface ApiResponse {
total: number;
limit: number;
cursor?: string;
items: Token[];
}
export interface Token {
interface: string;
id: string;
content: Content;
authorities: Authority[];
compression: Compression;
grouping: Grouping[]; // or any[]
royalty: Royalty;
creators: Creator[]; // or any[]
ownership: Ownership;
supply: Supply | null | number;
mutable: boolean;
burnt: boolean;
token_info: TokenInfo;
mint_extensions: MintExtensions;
inscription: Inscription;
spl20?: Spl20;
}
export interface Content {
$schema: string;
json_uri: string;
files: any[];
metadata: Record;
links: Record;
}
export interface Authority {
address: string;
scopes: string[];
}
export interface Compression {
eligible: boolean;
compressed: boolean;
data_hash: string;
creator_hash: string;
asset_hash: string;
tree: string;
seq: number;
leaf_id: number;
}
export interface Grouping {
group_key: string;
group_value: string;
collection_metadata: CollectionMetadata;
}
export interface Royalty {
royalty_model: string;
target: string | null;
percent: number;
basis_points: number;
primary_sale_happened: boolean;
locked: boolean;
}
export interface Creator {
address: string;
share: number;
verified: boolean;
}
export interface Ownership {
frozen: boolean;
delegated: boolean;
delegate: null | string;
ownership_model: string;
owner: string;
}
export interface Supply {
print_max_supply: number;
print_current_supply: number;
edition_nonce: number;
}
export interface TokenInfo {
symbol: string;
balance: number;
supply: number;
decimals: number;
token_program: string;
associated_token_address: string;
price_info: PriceInfo;
}
export interface Inscription {
order: number;
size: number;
contentType: string;
encoding: string;
validationHash: string;
inscriptionDataAccount: string;
}
export interface Spl20 {
p: string;
op: string;
tick: string;
amt: string;
}
export interface File {
uri: string;
cdn_uri: string;
mime: string;
}
export interface Metadata {
attributes: Attribute[];
description: string;
name: string;
symbol: string;
}
export interface Attribute {
value: string;
trait_type: string;
}
export interface CollectionMetadata {
name: string;
symbol: string;
image: string;
description: string;
external_url: string;
}
export interface PriceInfo {
price_per_token: number;
total_price: number;
currency: string;
}
export interface MintExtensions {}4단계: 토큰 정보 표시
API 응답을 대체 가능 토큰과 대체 불가능 토큰으로 분류합니다. Token Card 컴포넌트를 사용해 이 토큰들을 표시합니다. 사용자는 토글 버튼으로 두 토큰 유형을 전환할 수 있습니다.
검색 페이지에 컴포넌트 통합
- 검색 페이지(pages/index.ts)
- 랜딩 페이지에는 사용자가 지갑 주소를 입력할 수 있는 검색창이 있습니다.
- Tailwind CSS로 깔끔하고 반응형인 디자인을 구현합니다.
"use client";
import React from "react";
import SearchBar from "./components/searchBar";
export default function Home() {
return (
Solana Portfolio Viewer
{"Built with Helius's DAS API"}
);
}토큰 페이지 설정
개별 지갑 주소에 Next.js 동적 라우트를 사용합니다. 간편한 페이지 이동과 URL 공유를 지원하여 사용자 경험을 개선합니다.
[wallet] 디렉터리를 설정하세요. 대괄호를 사용하면 동적 라우팅이 활성화됩니다. 그런 다음 동적으로 로드되는 모든 페이지의 비즈니스 로직을 담을 page.tsx 파일을 만드세요.
토큰 페이지 설정(pages/[wallet]/page.tsx):
이 페이지는 URL의 지갑 주소와 연결된 토큰을 표시합니다. API를 호출해 토큰 데이터를 가져오고 Token Card 컴포넌트로 표시합니다.
"use client";
import React, { useState, useEffect } from "react";
import fetchTokens from "../lib/searchAssets";
import TokenCard from "../components/tokenCard";
import { Token, Attribute } from "../types/Token";
interface Tokens {
items: Token[];
}
interface PageProps {
params: {
wallet: string;
};
}
export default function Page({ params }: PageProps) {
const [tokens, setTokens] = useState(null);
const [tokenType, setTokenType] = useState("fungible");
useEffect(() => {
fetchTokens(params.wallet).then(setTokens).catch(console.error);
}, [params.wallet]);
console.log("tokens", tokens);
const fungibleTokens = tokens
? tokens.items.filter(
(token) =>
token.interface === "FungibleToken" ||
token.interface === "FungibleAsset"
)
: [];
const nonFungibleTokens = tokens
? tokens.items.filter(
(token) =>
token.interface !== "FungibleToken" &&
token.interface !== "FungibleAsset"
)
: [];
const displayedTokens =
tokenType === "fungible" ? fungibleTokens : nonFungibleTokens;
return (
Portfolio Viewer
{params.wallet}
setTokenType("fungible")}
>
Fungible Tokens
setTokenType("nonFungible")}
>
Non-Fungible Tokens
{displayedTokens.length > 0 ? (
{displayedTokens.map((token) => (
))}
) : (
Loading...
)}
);
}모든 설정을 마치면 프로젝트 디렉터리는 다음과 같은 구조가 됩니다.
5단계: 애플리케이션 스타일링
스타일링 프레임워크로 Tailwind CSS를 사용합니다. 유틸리티 우선 방식이므로 일관된 반응형 디자인을 유지하면서 컴포넌트를 빠르게 스타일링할 수 있습니다. Tailwind를 사용해 원하는 방식으로 애플리케이션을 맞춤 설정하세요.
6단계: 애플리케이션 테스트
로컬에서 테스트하려면 Next.js 앱을 실행하세요.
npm run dev여러 지갑 주소를 입력하여 테스트하고 올바른 데이터가 표시되는지 확인하세요.
배포
Vercel을 사용해 애플리케이션을 배포합니다. Vercel은 무료 호스팅과 유용한 분석 및 인사이트를 제공하므로 Next.js 애플리케이션 호스팅에 적합합니다. https://vercel.com/에서 설정할 수 있습니다.
마무리
튜토리얼을 완료하신 것을 축하합니다! 유익한 내용이었기를 바랍니다.
DAS API는 온체인에서 토큰 데이터를 가져올 수 있는 매우 강력하고 빠른 도구입니다.
이 포트폴리오 뷰어는 API로 무엇을 구현할 수 있는지 잘 보여주는 예시입니다.
이번에 만든 기본 사이트를 바탕으로 멋진 서비스를 완성해 보세요. 궁금한 점이 있다면 언제든 Discord에 참여해 직접 질문하세요!
전체 코드는 여기에서 확인할 수 있습니다: https://github.com/helius-labs/galleria
추가 학습 자료
Next.js, Solana 블록체인, API 통합을 더 깊이 이해하려면 다음 자료를 살펴보세요.
이 가이드는 Next.js로 블록체인 기반 애플리케이션을 구축하고 DAS API를 사용해 Solana 블록체인과 상호작용하는 데 필요한 탄탄한 기초를 제공합니다.
관련 아티클
Helius 구독하기
최신 Solana 개발 소식을 확인하고 새 게시물 알림을 받아보세요


