メインコンテンツへスキップ

インポート

import { useExplicitSessions } from '@0xsequence/connect'

使い方

import { createContractPermission, useExplicitSessions, type ExplicitSessionParams, type ExplicitSession } from '@0xsequence/connect'
import { useEffect, useState } from 'react'
import { parseUnits } from 'viem'

function App() {
  const {
    isLoading,
    error,
    addExplicitSession,
    modifyExplicitSession,
    getExplicitSessions
  } = useExplicitSessions()

  const [sessions, setSessions] = useState<ExplicitSession[]>([])

  // Load existing sessions
  useEffect(() => {
    const loadSessions = async () => {
      try {
        const existingSessions = await getExplicitSessions()
        setSessions(existingSessions)
      } catch (err) {
        console.error('Failed to load sessions:', err)
      }
    }

    loadSessions()
  }, [getExplicitSessions])

  // Function to handle modifying an existing explicit session
  const handleModifySession = () => {
    const newPermission = createContractPermission({
      address: '0x...',
      functionSignature: 'function testContract() public'
    })
    const currentSession = sessions[0]
    const modifiedSession = { ...currentSession, permissions: [...currentSession.permissions!, newPermission] }
    modifyExplicitSession(modifiedSession)
  }

  // Handle creating a new explicit session
  const handleCreateSession = async () => {
    try {
      const tokenSpendingSession: ExplicitSessionParams = {
        chainId: 42161,
        nativeTokenSpending: {
          valueLimit: 0n,
        },
        expiresIn: {
          days: 3
        },
        permissions: [
          createContractPermission({
            address: '0x...',
            functionSignature: 'function transfer(address to, uint256 amount)',
              rules: [
                {
                  param: 'amount',
                  type: 'uint256',
                  condition: 'LESS_THAN_OR_EQUAL',
                  value: parseUnits('100', 6), // Max cumulative amount of 100 USDC
                  cumulative: true
                }
              ]
          })
        ]
      }

      await addExplicitSession(tokenSpendingSession)

      // Refresh sessions after creating a new one
      const updatedSessions = await getExplicitSessions()
      setSessions(updatedSessions)
    } catch (err) {
      console.error('Failed to create session:', err)
    }
  }

  if (isLoading) {
    return <div>Creating session...</div>
  }

  if (error) {
    return <div>Error: {error.message}</div>
  }

  return (
    <div>
      <h2>Explicit Sessions</h2>
      <button onClick={handleCreateSession}>
        Create New Session
      </button>

      <button onClick={handleModifySession}>
        Modify Session
      </button>

      <div>
        <h3>Existing Sessions ({sessions.length})</h3>
        {sessions.map((session, index) => (
          <div key={index}>
            <p>Session Address: {session.sessionAddress}</p>
            <p>Chain ID: {session.chainId}</p>
            <p>Permissions: {session.permissions?.map(permission => permission.target).join(', ')}</p>
          </div>
        ))}
      </div>
    </div>
  )
}

返り値の型

このフックは以下のプロパティを持つオブジェクトを返します。
type UseExplicitSessionsReturnType = {
  isLoading: boolean
  error: Error | null
  addExplicitSession: (params: ExplicitSessionParams, includeFeeOptionPermissions?: boolean) => Promise<void>
  modifyExplicitSession: (explicitSession: ExplicitSession) => Promise<void>
  getExplicitSessions: () => Promise<ExplicitSession[]>
}

プロパティ

isLoading

boolean セッションリクエスト操作が進行中かどうかを示すブール値です。

エラー

Error | null 直近の操作が失敗した場合はエラーオブジェクト、それ以外はnullです。

addExplicitSession

(params: ExplicitSessionParams, includeFeeOptionPermissions?: boolean) => Promise<void>
type ExplicitSession = {
  sessionAddress: Address.Address
  valueLimit: bigint
  deadline: bigint
  permissions: Permission.Permission[]
  chainId: number
  type: 'explicit'
}
新しい明示的セッションを作成する関数です。

modifyExplicitSession

(explicitSession: ExplicitSession) => Promise<void>
type ExplicitSession = {
  sessionAddress: Address.Address
  valueLimit: bigint
  deadline: bigint
  permissions: Permission.Permission[]
  chainId: number
  type: 'explicit'
}
既存の明示的セッションを変更するための関数です。

getExplicitSessions

() => Promise<ExplicitSession[]> 接続されているウォレットのすべての明示的セッションを取得する関数です。

補足

このフックは、Sequence V3ウォレット接続の明示的セッション管理機能を提供します。 主な特徴:
  • カスタム権限や利用上限を設定した新規明示的セッションを作成できます
  • 接続中ウォレットの既存の明示的セッションをすべて取得できます
  • 既存の明示的セッションを変更する
  • 一般的な接続エラーに対する組み込みエラーハンドリング
  • ユーザー体験向上のためのローディング状態管理
  • 明示的セッションのみを表示する自動セッションフィルタリング