메인 콘텐츠로 건너뛰기
SessionWalletProvider는 앱 컴포넌트를 감싸 애플리케이션 전체에 sessionWallet context를 제공하는 고차 컴포넌트입니다. 다음은 SessionWalletProvider 사용 예시입니다.
  1. components/SessionProvider.tsx라는 새 파일을 만듭니다
// components/SessionProvider.tsx
// The SessionProvider component initializes the SessionKeyManager and provides it to its children via context.
// Wrap any component that needs access to the SessionKeyManager with this provider.

import {
  SessionWalletProvider,
  useSessionKeyManager,
} from "@magicblock-labs/gum-react-sdk";
import {
  AnchorWallet,
  useAnchorWallet,
  useConnection,
} from "@solana/wallet-adapter-react";

interface SessionProviderProps {
  children: React.ReactNode;
}

const SessionProvider: React.FC<SessionProviderProps> = ({ children }) => {
  const { connection } = useConnection();
  const anchorWallet = useAnchorWallet() as AnchorWallet;
  const cluster = "devnet"; // or "mainnet-beta", "testnet", "localnet"
  //here the useSessionKeyManager takes in 3 properties
  const sessionWallet = useSessionKeyManager(anchorWallet, connection, cluster);

  return (
    <SessionWalletProvider sessionWallet={sessionWallet}>
      {children}
    </SessionWalletProvider>
  );
};

export default SessionProvider;
  1. In your _app.tsx file, wrap the SessionProvider around the entire app to ensure it’s accessible within every component:
// pages/_app.tsx
import SessionProvider from "@/components/SessionProvider";
import { WalletContextProvider } from "@/contexts/WalletContextProvider";
import "@/styles/globals.css";
import { WalletAdapterNetwork } from "@solana/wallet-adapter-base";
import {
  PhantomWalletAdapter,
  SolflareWalletAdapter,
} from "@solana/wallet-adapter-wallets";
import { clusterApiUrl } from "@solana/web3.js";
import type { AppProps } from "next/app";
import React, { useMemo } from "react";
import dotenv from "dotenv";

// Use require instead of import since order matters
require("@solana/wallet-adapter-react-ui/styles.css");

dotenv.config();

export default function App({ Component, pageProps }: AppProps) {
  const network = WalletAdapterNetwork.Devnet;
  const endpoint =
    process.env.NEXT_PUBLIC_SOLANA_ENDPOINT || clusterApiUrl(network);
  const wallets = useMemo(
    () => [
      new PhantomWalletAdapter({ network }),
      new SolflareWalletAdapter({ network }),
    ],
    [network]
  );

  return (
    <WalletContextProvider
      endpoint={endpoint}
      network={network}
      wallets={wallets}
    >
      <SessionProvider>
        <Component {...pageProps} />
      </SessionProvider>
    </WalletContextProvider>
  );
}
참고: 모든 Solana wallet adapter context가 SessionProvider의 부모에 오도록 구성해야 합니다.
  1. SessionWalletProvider 설정이 끝나면 컴포넌트에서 useSessionWallet hook을 사용할 수 있습니다.

컴포넌트에서 useSessionWallet 사용하기

useSessionWallet는 session wallet context 값에 접근할 수 있게 해주는 커스텀 hook입니다. SessionWalletProvider로 감싼 어떤 컴포넌트에서든 사용할 수 있습니다. useSessionWallet hook이 무엇을 제공하는지 제대로 이해하려면 SessionWalletInterface를 살펴봐야 합니다. 이것은 useSessionKeyManager가 반환하는 값이며, session keys 활용과 트랜잭션 서명 및 전송에 필요한 메서드를 제공합니다.
interface SessionWalletInterface {
  publicKey: PublicKey | null; // Public key associated with the session wallet
  ownerPublicKey: PublicKey | null; // The Publickey of the session token authority(The creator of the session token)
  isLoading: boolean; // Indicates whether the session wallet is loading
  error: string | null; // An error message, if any
  sessionToken: string | null; // Session token for the current session
  signTransaction:
    | (<T extends Transaction>(
        transaction: T,
        connection?: Connection,
        sendOptions?: SendTransactionOptions
      ) => Promise<T>)
    | undefined; // Sign a single transaction
  signAllTransactions:
    | (<T extends Transaction>(
        transactions: T[],
        connection?: Connection,
        sendOptions?: SendTransactionOptions
      ) => Promise<T[]>)
    | undefined; // Sign multiple transactions
  signMessage: ((message: Uint8Array) => Promise<Uint8Array>) | undefined; // Sign a message
  sendTransaction:
    | (<T extends Transaction>(
        transaction: T,
        connection?: Connection,
        options?: SendTransactionOptions
      ) => Promise<string>)
    | undefined; // Send a signed transaction
  signAndSendTransaction:
    | (<T extends Transaction>(
        transactions: T | T[],
        connection?: Connection,
        options?: SendTransactionOptions
      ) => Promise<string[]>)
    | undefined; // Sign and send transactions
  createSession: (
    targetProgram: PublicKey, // Target Solana program
    topUpLamports?: number, // Top up session wallet with lamports or not
    validUntil?: number, // Duration of session token before expiration
    sessionCreatedCallback?: (sessionInfo: {
      sessionToken: string;
      publicKey: string;
    }) => void
  ) => Promise<SessionWalletInterface | undefined>; // Create a new session
  revokeSession: () => Promise<void>; // Revoke the current session
  getSessionToken: () => Promise<string | null>; // Retrieve the current session token
}
이를 통해 코드에서 sessionWallet을 사용해 session token을 만들고, 더 이상 필요 없을 때 철회하는 방법을 이해할 수 있습니다.
import { useSessionWallet } from "@magicblock-labs/gum-react-sdk";

function YourComponent() {
  const sessionWallet = useSessionWallet();

  //create session token
  const session = await sessionWallet.createSession(
  // pass needed params here
  );

  //Revoke Session Wallet
   const result = await sessionWallet.revokeSession();

   //Access the session signer Publickey
   sessionWallet.publicKey,

   //To access the session token
   sessionWallet.sessionToken

  return (
    // Your component JSX
  );
}