インポート

import { useSwapModal } from '@0xsequence/checkout'

使い方

import { useSwapModal } from '@0xsequence/checkout'
import { encodeFunctionData, parseAbi } from 'viem'

function App() {
  const { openSwapModal } = useSwapModal()
  
  const handleSwap = () => {
    // Target token information
    const chainId = 137 // Polygon
    const toTokenAddress = '0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359' // USDC on Polygon
    const toTokenAmount = '20000' // 0.02 USDC (in smallest units)
    
    // Optional: Transaction to execute after swap is completed
    const data = encodeFunctionData({ 
      abi: parseAbi(['function demo()']), 
      functionName: 'demo', 
      args: [] 
    })
    
    // Open the swap modal
    openSwapModal({
      onSuccess: () => {
        console.log('swap successful!')
      },
      chainId,
      toTokenAddress,
      toTokenAmount,
      postSwapTransactions: [
        {
          to: '0x37470dac8a0255141745906c972e414b1409b470',
          data
        }
      ],
      title: 'Swap and Pay',
      description: 'Select a token in your wallet to swap to 0.2 USDC.'
    })
  }
  
  return (
    <button onClick={handleSwap}>
      Swap with Sequence Pay
    </button>
  )
}

返り値の型:UseSwapModalReturnType

このフックは以下のプロパティを持つオブジェクトを返します。

type UseSwapModalReturnType = {
  openSwapModal: (settings: SwapModalSettings) => void
  closeSwapModal: () => void
  swapModalSettings: SwapModalSettings | undefined
}

プロパティ

openSwapModal

(settings: SwapModalSettings) => void

指定した設定でスワップモーダルを開く関数です。

パラメータ:

settingsオブジェクトには以下のプロパティを含めることができます:

パラメータ説明
chainIdnumberスワップを行うブロックチェーンネットワークID
toTokenAddressstring対象トークンコントラクトのアドレス
toTokenAmountstring対象トークンの最小単位での数量
postSwapTransactionsArray<{to: string, data: string}>(オプション)スワップ完了後に実行するトランザクションの配列
disableMainCurrencyboolean(オプション)trueの場合、チェーンのメイン通貨でのスワップを無効化します
titlestring(オプション)スワップモーダルのカスタムタイトル
descriptionstring(オプション)スワップモーダルのカスタム説明文
onSuccess() => void(オプション)スワップが成功した際のコールバック
onError(error: Error) => void(オプション)エラー発生時のコールバック
onClose() => void(オプション)モーダルが閉じられたときのコールバック
blockConfirmationsnumber(オプション)スワップ完了までに待機するブロック承認数

closeSwapModal

() => void

スワップモーダルを閉じる関数です。

swapModalSettings

SwapModalSettings | undefined

現在のスワップモーダルの設定内容です。

export interface SwapModalSettings {
  chainId: number
  toTokenAddress: string
  toTokenAmount: string
  title?: string
  description?: string
  disableMainCurrency?: boolean
  postSwapTransactions?: Transaction[]
  blockConfirmations?: number
  onSuccess?: (txHash: string) => void
}

補足

このフックは、ウォレット内のトークンを指定した通貨にスワップするためのスワップモーダルを操作するメソッドを提供します。ユーザーはウォレット内のトークンを選択して指定したトークンにスワップでき、スワップ完了後に追加のトランザクションを実行することも可能です。