> ## Documentation Index
> Fetch the complete documentation index at: https://daehan-base.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 서브 어카운트

> Base Account로 앱별 지갑 계정 생성 및 관리

export const GithubRepoCard = ({title, githubUrl}) => {
  return <a href={githubUrl} target="_blank" rel="noopener noreferrer" className="mb-4 flex items-center rounded-lg bg-zinc-900 p-4 text-white transition-all hover:bg-zinc-800">
      <div className="flex w-full items-center gap-3">
        <svg height="24" width="24" className="flex-shrink-0 dark:fill-white" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg">
          <path fill="currentColor" fillRule="evenodd" d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z" />
        </svg>

        <div className="flex min-w-0 flex-grow flex-col">
          <span className="truncate text-base font-medium">{title}</span>
          <span className="truncate text-xs text-zinc-400">{githubUrl}</span>
        </div>

        <svg className="h-5 w-5 flex-shrink-0 text-zinc-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
        </svg>
      </div>
    </a>;
};

애플리케이션에 직접 임베드된 앱별 지갑 계정을 제공하는 서브 어카운트를 생성하고 관리하는 방법을 알아보세요.

## 개요

서브 어카운트를 통해 애플리케이션 내에서 사용자를 위한 전용 지갑 계정을 프로비저닝할 수 있습니다.
이 계정들은 사용자의 메인 Base Account에 의해 제어되며, 사용자의 상호작용 시 패스키 프롬프트나 팝업이 없어 향상된 사용자 경험을 제공합니다.

사용자는 [account.base.app](https://account.base.app)에서 모든 서브 어카운트를 관리할 수 있습니다.

<Note>
  서브 어카운트의 라이브 데모를 보려면 [서브 어카운트 데모](https://sub-accounts-fc.vercel.app)를 확인하세요.
</Note>

### 달성할 내용

이 가이드를 마치면 다음을 할 수 있습니다:

* Base Account와 서브 어카운트의 작동 방식 이해
* 사용자를 위한 새 서브 어카운트 생성
* 기존 서브 어카운트 조회 및 관리
* Privy 프로젝트에 서브 어카운트 구현

이 가이드의 코드 스니펫은 다음 예제 프로젝트를 기반으로 합니다:

<GithubRepoCard title="Base Account Privy 템플릿" githubUrl="https://github.com/base/base-account-privy" />

## 설정

[설정](/base-account/framework-integrations/privy/setup) 가이드를 따라 Base Account와 함께 Privy를 설정하세요.

## 구현

### 컴포넌트 설정

<CodeGroup>
  ```tsx 서브 어카운트 컴포넌트 (components/sections/sub-accounts.tsx) expandable theme={null}
  "use client";

  import { useState, useMemo } from "react";
  import { useWallets } from "@privy-io/react-auth";

  const SubAccounts = () => {
    const { wallets } = useWallets();
    const [subAccounts, setSubAccounts] = useState<
      {
        address: string;
        factory: string;
        factoryData: string;
      }[]
    >([]);
    const [isLoading, setIsLoading] = useState(false);

    // Base Account 지갑 찾기
    const baseAccount = useMemo(() => {
      return wallets.find((wallet) => wallet.walletClientType === 'base_account');
    }, [wallets]);

    const handleGetSubAccounts = async () => {
      if (!baseAccount) return;

      setIsLoading(true);
      try {
        // Base Sepolia로 전환 (또는 메인넷의 경우 8453 사용)
        await baseAccount.switchChain(84532);
        const provider = await baseAccount.getEthereumProvider();

        // 기존 서브 어카운트 조회
        const response = await provider.request({
          method: 'wallet_getSubAccounts',
          params: [{
            account: baseAccount.address,
            domain: window.location.origin
          }]
        });

        const { subAccounts: existingSubAccounts } = response;
        setSubAccounts(existingSubAccounts || []);
      } catch (error) {
        console.error("Error getting Sub Accounts:", error);
      } finally {
        setIsLoading(false);
      }
    };

    const handleAddSubAccount = async () => {
      if (!baseAccount) return;

      setIsLoading(true);
      try {
        // Base Sepolia로 전환 (또는 메인넷의 경우 8453 사용)
        await baseAccount.switchChain(84532);
        const provider = await baseAccount.getEthereumProvider();

        // 새 서브 어카운트 생성
        await provider.request({
          method: 'wallet_addSubAccount',
          params: [{
            version: '1',
            account: {
              type: 'create',
              keys: [{
                type: 'address',
                publicKey: baseAccount.address
              }]
            }
          }]
        });

        // 서브 어카운트 목록 새로고침
        await handleGetSubAccounts();
      } catch (error) {
        console.error("Error creating Sub Account:", error);
      } finally {
        setIsLoading(false);
      }
    };

    return (
      <div className="space-y-4">
        <div className="flex gap-4">
          <button 
            onClick={handleGetSubAccounts}
            disabled={!baseAccount || isLoading}
            className="px-4 py-2 bg-blue-600 text-white rounded disabled:opacity-50"
          >
            서브 어카운트 조회
          </button>
          <button 
            onClick={handleAddSubAccount}
            disabled={!baseAccount || isLoading}
            className="px-4 py-2 bg-green-600 text-white rounded disabled:opacity-50"
          >
            서브 어카운트 생성
          </button>
        </div>

        {subAccounts.length > 0 && (
          <div>
            <h4 className="font-medium mb-2">기존 서브 어카운트:</h4>
            <div className="space-y-2">
              {subAccounts.map((subAccount, index) => (
                <div key={index} className="p-3 border rounded-md">
                  <p><strong>주소:</strong> {subAccount.address}</p>
                  <p><strong>팩토리:</strong> {subAccount.factory}</p>
                  <p><strong>팩토리 데이터:</strong> {subAccount.factoryData}</p>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  };
  ```
</CodeGroup>

### 주요 메서드

#### 서브 어카운트 조회

`wallet_getSubAccounts`를 사용하여 도메인의 기존 서브 어카운트를 조회합니다:

```tsx 서브 어카운트 조회 (components/sections/sub-accounts.tsx) theme={null}
const response = await provider.request({
  method: 'wallet_getSubAccounts',
  params: [{
    account: baseAccount.address,
    domain: window.location.origin
  }]
});
```

#### 서브 어카운트 생성

`wallet_addSubAccount`를 사용하여 새 서브 어카운트를 생성합니다:

```tsx 서브 어카운트 생성 (components/sections/sub-accounts.tsx) theme={null}
await provider.request({
  method: 'wallet_addSubAccount',
  params: [{
    version: '1',
    account: {
      type: 'create',
      keys: [{
        type: 'address',
        publicKey: baseAccount.address
      }]
    }
  }]
});
```

### 네트워크 설정

서브 어카운트는 Base 메인넷과 Base Sepolia 모두에서 작동합니다:

* **Base 메인넷**: 체인 ID `8453`
* **Base Sepolia**: 체인 ID `84532`

### 더 알아보기

* [서브 어카운트 가이드](/base-account/improve-ux/sub-accounts)
* [Privy 서브 어카운트 레시피](https://docs.privy.io/recipes/react/external-wallets/base-sub-accounts)
