web3-nextjs

HAaYAT0 的头像作者 HAaYAT0

Next.js + Web3開発の知識。「ウォレット接続」「ethers」「wagmi」で使用。

📖 中文导读:Next.js + Web3開発の知識。「ウォレット接続」「ethers」「wagmi」で使用。 以下正文为该技能的原始 SKILL.md 内容(英文),上方安装命令可直接使用。

name: web3-nextjs description: Next.js + Web3開発の知識。「ウォレット接続」「ethers」「wagmi」で使用。 allowed-tools: Read, Bash

Web3 + Next.js 開発スキル

基本構成

# 依存パッケージ
pnpm add ethers@^6.9.0 wagmi@^2.0.0 @tanstack/react-query@^5.0.0 viem@^2.0.0

ウォレット接続パターン

// ethers.js v6 直接使用
async function connectWallet() {
  if (!window.ethereum) throw new Error("MetaMask not installed");

  const provider = new ethers.BrowserProvider(window.ethereum);
  const accounts = await provider.send("eth_requestAccounts", []);
  const signer = await provider.getSigner();

  return { address: accounts[0], signer };
}

ネットワーク切り替え

async function switchToSepolia() {
  await window.ethereum.request({
    method: "wallet_switchEthereumChain",
    params: [{ chainId: "0xaa36a7" }], // 11155111
  });
}

トランザクション実行

async function sendTransaction(signer, contract, method, args, value?) {
  try {
    const tx = await contract[method](...args, value ? { value } : {});
    const receipt = await tx.wait();
    return { success: true, hash: tx.hash, receipt };
  } catch (error) {
    return { success: false, error: error.message };
  }
}

Next.js 14 注意点

  • App Router 使用
  • 'use client' ディレクティブ必須(ウォレット操作)
  • window.ethereum アクセスは useEffect 内で
  • SSR での window 参照エラーに注意