Skip to main content

Documentation Index

Fetch the complete documentation index at: https://daehan-base.mintlify.app/llms.txt

Use this file to discover all available pages before exploring further.

비밀번호 대신 지갑 서명을 사용하는 이유

  1. 새로운 비밀번호 불필요 – 사용자가 이미 보유한 키로 인증이 이루어집니다.
  2. 탈취하거나 재사용할 것이 없음 – 각 로그인은 사용자 디바이스를 벗어나지 않는 일회성 도메인 바인딩 서명입니다.
  3. 지갑 무관 – 모든 EIP-1193 지갑(브라우저 확장, 모바일 딥링크, 임베디드 프로바이더)에서 동작하며 개방형 “Sign in with Ethereum” (SIWE) EIP-4361 표준을 따릅니다.
Base Account는 이 표준을 기반으로 구축되어 있어 기존 SIWE 도구를 재사용하면서도 패스키, 세션 키, 스마트 지갑 보안의 이점을 누릴 수 있습니다.
브랜드 가이드라인을 준수해 주세요SignInWithBaseButton을 사용하려면 애플리케이션 전반의 일관성을 위해 Base 브랜드 가이드라인을 준수해 주세요.
영상 콘텐츠를 선호하시나요?이 페이지 마지막 섹션에서 구현 내용을 자세히 다루는 영상 가이드를 확인하세요.

전체 흐름

미배포 스마트 지갑?Base Account 서명에는 ERC-6492 래퍼가 포함되어 있어 지갑 컨트랙트가 배포되기 전에도 검증이 가능합니다. Viem의 verifyMessageverifyTypedData가 이를 자동으로 처리합니다.

구현

의존성 설치

의존성을 설치합니다:
npm install @base-org/account @base-org/account-ui

코드 스니펫

import { createBaseAccountSDK } from "@base-org/account";

// Initialize the SDK
const provider = createBaseAccountSDK({
  appName: "My App",
}).getProvider();

// 1 — get a fresh nonce (generate locally or prefetch from backend)
const nonce = window.crypto.randomUUID().replace(/-/g, "");
// OR prefetch from server
// const nonce = await fetch("/auth/nonce").then((response) => response.text());

// 2 — switch to Base Chain
const switchChainResponse = await provider.request({
  method: "wallet_switchEthereumChain",
  params: [{ chainId: "0x2105" }],
});

console.log("Switch chain response:", switchChainResponse);

// 3 — connect and authenticate
try {
  const { accounts } = await provider.request({
    method: "wallet_connect",
    params: [
      {
        version: "1",
        capabilities: {
          signInWithEthereum: {
            nonce,
            chainId: "0x2105", // Base Mainnet - 8453
          },
        },
      },
    ],
  });

  const { address } = accounts[0];
  const { message, signature } =
    accounts[0].capabilities.signInWithEthereum;

  await fetch("/auth/verify", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ address, message, signature }),
  });
} catch (error) {
  console.error("Failed to authenticate with Base Account:", error);
}

위 코드를 Base Account 외에도 사용하는 경우, 모든 지갑이 새로운 wallet_connect 메서드를 아직 지원하지 않는다는 점에 유의하세요. 호출이 [method_not_supported]를 발생시키면 eth_requestAccountspersonal_sign을 사용하도록 폴백하세요.
팝업 차단을 피하려면 사용자가 “Base로 로그인” 버튼을 누르기 전에 (예: 페이지 로드 시) 논스를 가져오거나 생성하세요. 보안을 위해, 백엔드가 모든 논스를 추적하고 재사용된 논스를 거부하기만 하면 됩니다. 논스의 출처는 관계없습니다.

Express 서버 예시

server/auth.ts
import crypto from "crypto";
import express from "express";
import { createPublicClient, http } from "viem";
import { base } from "viem/chains";

const app = express();
app.use(express.json());

// Simple in-memory nonce store (swap for Redis or DB in production)
const nonces = new Set<string>();

app.get("/auth/nonce", (_, res) => {
  const nonce = crypto.randomBytes(16).toString("hex");
  nonces.add(nonce);
  res.send(nonce);
});

const client = createPublicClient({ chain: base, transport: http() });

app.post("/auth/verify", async (req, res) => {
  const { address, message, signature } = req.body;

  // 1. Check nonce hasn\'t been reused
  const nonce = message.match(/at (\w{32})$/)?.[1];
  if (!nonce || !nonces.delete(nonce)) {
    return res.status(400).json({ error: "Invalid or reused nonce" });
  }

  // 2. Verify signature
  const valid = await client.verifyMessage({ address, message, signature });
  if (!valid) return res.status(401).json({ error: "Invalid signature" });

  // 3. Create session / JWT here
  res.json({ ok: true });
});

app.listen(3001, () => console.log("Auth server listening on :3001"));

Base Sign In With Base 버튼 추가

네이티브 룩앤필을 위해 사전 제작된 컴포넌트를 사용하세요:
App.tsx
import { SignInWithBaseButton } from "@base-org/account-ui/react";

export function App() {
  return (
    <SignInWithBaseButton
      colorScheme="light"
      onClick={() => signInWithBase()}
    />
  );
}
전체 props 및 테마 옵션은 SignInWithBaseButton 컴포넌트 타입과 이 페이지의 예시를 참고하세요.
브랜드 가이드라인을 준수해 주세요SignInWithBaseButton을 사용하려면 애플리케이션 전반의 일관성을 위해 Base 브랜드 가이드라인을 준수해 주세요.

영상 가이드