本文へスキップ
このページは英語からの機械翻訳を使用しており、誤りや不明瞭な表現が含まれている可能性があります。最も正確な情報については、オリジナルの英語版をご覧ください。頻繁な更新のため、一部のコンテンツはオリジナルの英語になっている可能性があります。Crowdinでの取り組みに参加して、このページの翻訳改善にご協力ください。 (Crowdin translation page, Contributing guide)

Particle NetworkをdAppに統合する

はじめに

Particle Networkは、ユーザーオンボーディングを簡素化するために、ウォレット抽象化サービスを提供します。

Particle Connect SDKは、Kaiaとそのテストネットを含むEVM互換チェーンをサポートしています。 social and Web3 login optionsを使って、2クリックオンボーディングを可能にします。

Particle Networkを使えば、Kaiaの開発者はKaiaメインネットとテストネット用のソーシャルログインを埋め込むことができ、ユーザーはGoogle、Eメール、Xなどを使ってアプリケーション内でウォレットを生成し、使用することができます。

このページでは、KaiaベースのアプリケーションにParticle Connectを実装するための概要とチュートリアルをご紹介します。

前提条件

インストール

Particle Network、特にParticle ConnectをdApp内で活用するには、まず必要なライブラリをインストールする必要があります。 Particle Connect SDKは、ウォレットの作成、ユーザーログイン、ブロックチェーンとのやり取りを1つのインターフェースで効率化します。 ソーシャルログインとWeb3ログインの両方をサポートし、簡単にアクセスできる。 Particle Connect SDKは、ウォレットの作成、ユーザーログイン、ブロックチェーンとのやり取りを1つのインターフェースで効率化します。 ソーシャルログインとWeb3ログインの両方をサポートし、簡単にアクセスできる。

SDKとViem(コネクトのバックエンド)、ethers(EIP-1193プロバイダーのデモ)をインストールするには、以下を実行する:


yarn add @particle-network/connectkit viem@^2エーテル

Particle Connectの初期化

まずはじめに、Particleの代表的な認証SDKであるParticle Connectを設定します。 プロジェクトのルート・ディレクトリに ConnectKit.tsx という新しいファイルを作成します。 まずはじめに、Particleの代表的な認証SDKであるParticle Connectを設定します。 プロジェクトのルート・ディレクトリに ConnectKit.tsx という新しいファイルを作成します。 このファイルには ParticleConnectKit コンポーネントが格納されます。このコンポーネントは、設定された ConnectKitProvider インスタンスのラッパーであり、Particle Connect を設定するための主要なインターフェイスとして機能します(これがプログラムでどのように見えるかについては、後で説明します)。

次に、Particle dashboardにアクセスして新しいWebアプリケーションプロジェクトを作成し、以下の必須APIキーを取得します:

  • projectId - プロジェクトの一意な識別子。
  • clientKey - クライアント固有のキー。
  • appId - アプリケーションのID。

これらのAPIキーを.envファイルに以下のように格納する:


next_public_project_id='project_id'
next_public_client_key='client_key'
next_public_app_id='app_id'

次のコードを ConnectKit.tsx ファイルに追加してください:


"use client";
import React from "react";
import { ConnectKitProvider, createConfig } from "@particle-network/connectkit";
import { authWalletConnectors } from "@particle-network/connectkit/auth";
import { defineChain } from "@particle-network/connectkit/chains";
import { wallet, EntryPosition } from "@particle-network/connectkit/wallet";
const kaiaMainnet = defineChain({
id: 8217,
name: "Kaia",
nativeCurrency: {
decimals: 18,
name: "KAIA",
symbol: "KAIA",
},
rpcUrls: {
default: {
http: ["https://public-en.node.kaia.io"],
},
},
blockExplorers: {
default: { name: "Explorer", url: "https://kaiascope.com/" },
},
testnet: false,
});
const kaiaTestnet = defineChain({
id: 1001,
name: "Kaia Testnet",
nativeCurrency: {
decimals: 18,
name: "KAIA",
symbol: "KAIA",
},
rpcUrls: {
default: {
http: ["https://public-en-kairos.node.kaia.io"],
},
},
blockExplorers: {
default: { name: "Explorer", url: "https://kairos.kaiascope.com/" },
},
testnet: true,
});
const config = createConfig({
projectId: process.env.NEXT_PUBLIC_PROJECT_ID!,
clientKey: process.env.NEXT_PUBLIC_CLIENT_KEY!,
appId: process.env.NEXT_PUBLIC_APP_ID!,
walletConnectors: [authWalletConnectors({})],
plugins: [
wallet({
entryPosition: EntryPosition.BR, // Positions the modal button at the bottom right on login
visible: true, // Determines if the wallet modal is displayed
}),
],
chains: [kaiaMainnet, kaiaTestnet],
});
export const ParticleConnectkit = ({ children }: React.PropsWithChildren) => {
return <ConnectKitProvider config={config}>{children}</ConnectKitProvider>;
};

このコンポーネントは、サポートするさまざまなログインタイプからモーダルの視覚的な外観まで、ほぼすべてのプロパティを設定できます。これらのさまざまなオプションを調べるには、Particleのドキュメントにアクセスしてください。

Particle Connectをアプリに統合

設定が完了したら、アプリケーションを ParticleConnectKit コンポーネントでラップし、Particle Connect SDK へのグローバルアクセスを有効にします。 そのためには、srcディレクトリにあるlayout.tsxファイルを以下のように修正します: そのためには、srcディレクトリにあるlayout.tsxファイルを以下のように修正します:


import { ParticleConnectkit } from '@/connectkit';
import type { Metadata } from 'next';
import { Inter } from 'next/font/google';
import './globals.css';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = {
title: 'Particle Connectkit App',
description: 'Generated by create next app',
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>
<ParticleConnectkit>{children}</ParticleConnectkit>
</body>
</html>
);
}

コネクティング・ウォレット

layout.tsxファイルのセットアップが完了したら、中央のConnect Walletボタンを使ってユーザーを接続します。 これを行うには @particle-network/connectkit から ConnectButton をインポートします。 ユーザーがログインすると、ConnectButtonは埋め込みウィジェットに変わります。


import { ConnectButton, useAccount } from '@particle-network/connectkit';
export const App = () => {
const { address, isConnected, chainId } = useAccount();
// Standard ConnectButton utilization
return (
<div>
<ConnectButton />
{isConnected && (
<>
<h2>Address: {address}</h2>
<h2>Chain ID: {chainId}</h2>
</>
)}
</div>
);
};

アカウントと残高の取得

ConnectButtonコンポーネントを通してウォレット(またはソーシャルログイン)が接続されると、ユーザーの関連するKaiaアドレスを取得することができます。 さらに、(KAIAの)現在の残高をpublicClientを通して取得することができます。これは、Particle Connectによってすでに設定されているViemプロバイダを利用します。


"use client";
import { useState, useEffect } from "react";
import {
ConnectButton,
useAccount,
usePublicClient,
} from "@particle-network/connectkit";
import { formatEther } from "viem";
export default function Home() {
// Account-related states
const { isConnected, address, chain } = useAccount();
const publicClient = usePublicClient();
// State variable for balance
const [balance, setBalance] = useState<string>("");
// Fetch and display user balance when connected
useEffect(() => {
const fetchBalance = async () => {
if (address) {
try {
const balanceResponse = await publicClient.getBalance({ address });
const balanceInEther = formatEther(balanceResponse);
setBalance(balanceInEther);
} catch (error) {
console.error("Error fetching balance:", error);
}
}
};
if (isConnected) {
fetchBalance();
}
}, [isConnected, address, publicClient]);
return (
<div className="min-h-screen flex flex-col items-center justify-center p-8 bg-black text-white">
<ConnectButton label="Connect Wallet" />
{isConnected && (
<div className="w-full max-w-md mt-6">
<h2 className="text-xl font-bold text-white mb-4">Account Details</h2>
<p className="text-lg text-white">
Address: {address || "Loading..."}
</p>
<p className="text-lg text-white">
Balance: {balance || "Loading..."} {chain?.nativeCurrency.symbol}
</p>
</div>
)}
</div>
);
}

ウォレットの切断

一度ログインしたユーザは、プログラムによって useDisconnect から派生した disconnect によって強制的にログアウトさせることができる。 これは現在アクティブなセッションをdAppから切断し、ユーザーを初期状態に戻します。


import { useDisconnect } from "@particle-network/connectkit";
const { disconnect } = useDisconnect();
// Inside your component's JSX
<button
className="mt-4 w-full bg-red-600 hover:bg-red-700 text-white font-bold py-2 px-4 rounded"
onClick={disconnect}
>
Disconnect
</button>

ユーザー情報の取得

ユーザーがソーシャルアカウント経由で接続すると、フック useParticleAuth() を使って userinfo にアクセスすることができます。この情報には、接続方法、アカウント作成日、名前、メールアドレス、その他の Particle Auth の関連情報 に関する詳細が含まれます。


import { useAccount, useParticleAuth, useWallets } from '@particle-network/connectkit';
import { useState, useEffect } from 'react';
export const App = () => {
const { getUserInfo } = useParticleAuth();
const { isConnected } = useAccount();
// Retrieve the primary wallet from the Particle Wallets
const [primaryWallet] = useWallets();
// Store userInfo in a useState to use it in your app
const [userInfo, setUserInfo] = useState<any>(null);
useEffect(() => {
const fetchUserInfo = async () => {
// Use walletConnectorType as a condition to avoid account not initialized errors
if (primaryWallet?.connector?.walletConnectorType === 'particleAuth') {
const userInfo = await getUserInfo();
setUserInfo(userInfo);
}
};
fetchUserInfo();
}, [isConnected, getUserInfo]);
return <h2 className="text-style">Name: {userInfo.name || 'N/A'}</h2>;
};

ネイティブ・トランザクションの送信

Particle Connectでは、すでに存在するEIP-1193プロバイダを活用できます。この例では、ethersでプロバイダインスタンスを作成し、転送トランザクションを送信します。


import { useWallets } from "@particle-network/connectkit";
import { ethers, type Eip1193Provider } from "ethers";
const [primaryWallet] = useWallets();
const executeTransaction = async () => {
// Get the provider from the primary wallet's connector
const EOAprovider = await primaryWallet.connector.getProvider();
// Initialize a custom provider using ethers.js with the obtained EIP-1193 provider
const customProvider = new ethers.BrowserProvider(EOAprovider as Eip1193Provider, "any");
// Get the signer (an abstraction of the account that can sign transactions)
const signer = await customProvider.getSigner();
// Send a transaction with specified recipient address, amount (0.01 ETH), and empty data
await signer.sendTransaction({
to: recipientAddress,
value: parseEther("0.01"),
data: "0x",
});
};

次のステップ

利用可能なフックの完全なリストは、Particle Connect docsにあります。

Particle Network(Particle Connect、Particle Auth、およびその他のSDK)に関するその他のガイドについては、Particle Network docsおよびParticle Network GitHubアカウントを参照してください。 さらに、Particle Networkのサービス、今後のリリース、技術スタックに関する追加情報については、Particle Networkブログをご覧ください。 さらに、Particle Networkのサービス、今後のリリース、技術スタックに関する追加情報については、Particle Networkブログをご覧ください。

ページを改善してください。