4
0

Particle Networkを使ったBerachain TestnetのソーシャルログインdApp [Berachian翻訳]

Posted at

本記事は下記の翻訳となります。
『Social Login dApp with Particle Network on Berachain Testnet』

image.png

Bm dev の皆さん!🐻

Berachain の Artio Testnet のローンチは、コミュニティ内で大きな反響を呼んでいます。Artio はユーザーの間での注目度が非常に高く、Proof-of-Liquidity のコンセンサスメカニズムを強力に実装していることが、テストネット上での展開に対する開発者やチームの興奮をさらに高めています!

Berachain の Artio Testnet のローンチ直後、Particle Network はSmart Wallet-as-a-Serviceのサポートを開始しました。これにより、Berachain 上で開発を行う開発者は、ソーシャルログインをネイティブに活用した EOA と関連するスマートアカウント(現在はSimpleAccount の実装)の作成と管理にすぐに取り組むことができます。

この記事は、Particle Network の DevRel チームの Tabasco との共同作業です。ゼロから dApp のテンプレートを作成する際の助けは大いに感謝しています!🤝 🐻


Bm dev の皆さん!🐻

Berachain の Artio Testnet のローンチは、コミュニティ内で大きな反響を呼んでいます。Artio はユーザーの間での注目度が非常に高く、Proof-of-Liquidity のコンセンサスメカニズムを強力に実装していることが、テストネット上での展開に対する開発者やチームの興奮をさらに高めています!

Berachain の Artio Testnet のローンチ直後、Particle Network はSmart Wallet-as-a-Serviceのサポートを開始しました。これにより、Berachain 上で開発を行う開発者は、ソーシャルログインをネイティブに活用した EOA と関連するスマートアカウント(現在はSimpleAccount の実装)の作成と管理にすぐに取り組むことができます。

この記事は、Particle Network の DevRel チームの Tabasco との共同作業です。ゼロから dApp のテンプレートを作成する際の助けは大いに感謝しています!🤝 🐻



前提条件

  1. Node js > 20 および最新の npm。必要に応じて、このガイドに従ってください: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm
  2. VScode、Replit などの IDE。
  3. $BERA:Berachain のネイティブガストークン。デモで使用する新しく作成されたウォレットで必要になります。(https://artio.faucet.berachain.com)
  4. $HONEY:Berachain のネイティブステーブルコイン。公式の Berachain Dex/ Bex を通じて入手できます。(https://artio.bex.berachain.com)
  5. Particle Network の開発者ダッシュボードへのアクセス。(https://dashboard.particle.network/)

Particle Auth Core を使用したソーシャルログイン

ソーシャルベースのログインは、「より簡単な Web3 へのオンボーディング」という物語に一歩近づくことが証明されており、特に主に Web2 アプリを経験したユーザーにとって有効です。

ソーシャルログインを活用することで、ユーザーは好みのソーシャルメディアアカウントを使用して簡単に認証でき、オンボーディングプロセスが簡素化されます。Web3 の dApp とやり取りするためにはウォレットが必要です。Particle Networks は、ユーザーが正常に認証された後、ユーザーのアカウントに関連付けられた Web3 ウォレットアドレスを取得できるようにすることで、このギャップを埋める役割を果たしています。

🛠️ 何を構築するのでしょう?

このチュートリアルでは、Particle Auth Core と Particle の AA SDK を使用して、Berachain Artio Testnet 上でスマート WaaS 対応のアプリケーションを構築することに焦点を当てます。このアプリケーションは、上記の埋め込み dApp で見つかる機能を再現します。

このガイドではフロントエンドには焦点を当てませんが、ガイドではフロントエンドのコードを共有しています。全体として、次のことを行います。

  • ソーシャルログインの開始(この例では Google または X を使用し、一般的な認証モーダルと一緒に行います)。
  • ソーシャルログインを介して生成された結果の EOA に SimpleAccount を割り当てます。
  • ガスレスのバーントランザクション(0.001 $BERA)を実行します。
  • Berachain のネイティブステーブルコインである$HONEY のバーンを実行します。

これにより、Berachain 上のプロジェクトに Particle Auth Core を実装する方法や、Berachain Testnet 上でソーシャルログインのテンプレートを取得する方法について、ここで示された構造と利用フローを活用できるようになるでしょう。

アプリケーションの基盤を構築する

  1. プロジェクトを初期化する: Vite を使用して新しい React-typescript アプリケーションを作成します。
npm create vite@latest berachain-particleTest -- --react-ts;

# Expected Output
# Need to install the following packages:
# create-vite@5.2.1
# Ok to proceed? (y) y
# ✔ Package name: … berachain-particletest
# ✔ Select a framework: › React
# ✔ Select a variant: › TypeScript

# Scaffolding project in /Users/dethebera/BeraWork/berachain-particle-testterminal/berachain-particleTest...

# Done. Now run:

#   cd berachain-particleTest
#   npm install
#   npm run dev
cd berachain-particleTest;
npm intall;


# Expected Output
# added 219 packages, and audited 220 packages in 8s

# 41 packages are looking for funding
#   run `npm fund` for details

# found 0 vulnerabilities

2. プロジェクトの依存関係をインストールする

npm install @types/events antd buffer react-dom

# Expected Output
# added 71 packages, and audited 291 packages in 5s

# 45 packages are looking for funding
#   run `npm fund` for details

# found 0 vulnerabilities
npm i ethers@5.7.2

# Expected Output
# added 44 packages, and audited 335 packages in 4s

# 76 packages are looking for funding
#   run `npm fund` for details

# found 0 vulnerabilities

3. Particle ライブラリのインストール: このデモを構築し、Particle Auth Core を実装するプロセスを探索するために、いくつかの重要なライブラリをインストールする必要があります。具体的には、以下のライブラリをインストールする必要があります:

  1. @particle-network/auth-core-modal:Particle Auth Core を実装するための中央 SDK で、以前は@particle-network/authとして知られていました。
  2. @particle-network/aa:SimpleAccount を割り当て、Ethers を使用してスマートアカウントを制御するためのカスタム AA 対応の EIP-1193 プロバイダーオブジェクトを生成するために使用します。
  3. @particle-network/chains:Berachain 固有の情報を含むオブジェクトで Particle Auth Core を設定するために使用します(BerachainArtio)。

次に、以下のいずれかのコマンドをコピーしてプロジェクトのルートで実行し、Yarn または npm を使用して両方の SDK をインストールします(pnpm などの代替パッケージマネージャーも同様の構文に従います):

yarn add @particle-network/auth-core-modal @particle-network/chains @particle-network/aa;

# OR (Remember to use either and not both)

npm install @particle-network/auth-core-modal @particle-network/chains @particle-network/aa;


# Expected Output
# added 368 packages, and audited 703 packages in 41s

# 109 packages are looking for funding
#   run `npm fund` for details

# 8 moderate severity vulnerabilities

# To address issues that do not require attention, run:
#   npm audit fix

# Some issues need review, and may require choosing
# a different dependency.

# Run `npm audit` for details.

Particle Dashboard からキーを取得する

AuthCoreContextProvider を構築する前に、Particle Auth Core を初期化するために 3 つの値が必要です。Particle Network のいずれかの SDK(Particle Auth Core, Particle Connect, または Particle's AA SDK)を設定する際には、Particle ダッシュボードからプロジェクト ID、クライアントキー、アプリ ID を取得する必要があります。

これらの値は、アプリケーションを Particle ダッシュボード上のプロジェクトにリンクさせ、API リクエストの認証、ユーザーの追跡、ノーコードのモーダルのカスタマイズなどを可能にします。

  1. particlenetwork.com にアクセスし、右上隅の「Dashboard」をクリックします。


Particle Network’s Homepage

  1. 「プロジェクトの追加」をクリックし、任意のプロジェクト名を入力して「保存」をクリックします。


Dashboard Homepage

  1. これで「プロジェクト ID」と「クライアントキー」にアクセスできるようになります。


Application Screen

  1. 「App ID」を取得するには、「Your Apps」タブの下にある「Web」をクリックし、「Ok」をクリックします。


Web App section highlighted in Application

  1. 「App Name」に任意の名前を入力します。ドメインには「goggle.com」を指定するか、既にホストされている場所のドメインを指定することができます。


Fetching App ID

  1. 「App ID」は「Your Apps」セクションの下に表示されるはずです。


App ID under Your Apps

これらのライブラリがインストールされたら、設定のプロセスを進める準備が整いました。

Particle Auth Core を介したソーシャルログインの実装:

Particle Auth Core は、AuthCoreContextProvider@particle-network/auth-core-modalからインポートされる)を介して設定を管理します。これは、主要なAppコンポーネント(またはそれに相当するもの)をラップするために、indexファイル内で使用されるオブジェクトです。これには、Particle Auth のインスタンスの認証に使用されるキー値と、ソーシャルログインまたは埋め込みウォレットモーダルのコアカスタマイズを有効にする値が含まれています。

Particle ダッシュボードを介してプロジェクトとアプリケーションを設定したら、AuthCoreContextProviderを構成する準備ができます。

File: ./src/index.tsx

// Imports
// ========================================================
import React from "react";
import ReactDOM from "react-dom/client";
import { BerachainArtio } from "@particle-network/chains";
import { AuthCoreContextProvider } from "@particle-network/auth-core-modal";
import App from "./App";

import("buffer").then(({ Buffer }) => {
  window.Buffer = Buffer;
});

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <AuthCoreContextProvider
      options={{
        projectId:  process.env.REACT_APP_PROJECT_ID, // Replace YOUR_PROJECT_ID_HERE with the actual project ID
        clientKey: process.env.REACT_APP_CLIENT_KEY, // Replace YOUR_CLIENT_KEY_HERE with the actual client key
        appId:  process.env.REACT_APP_CLIENT_KEY, // Replace YOUR_APP_ID_HERE with the actual app ID
        erc4337: {
          name: "SIMPLE",                  //name of the smart account you'd like to be displayed on the modal
          version: "1.0.0",
        },
        wallet: {
          visible: true,                   //boolean dictating whether or not the Particle Wallet modal is shown after login
          customStyle: {
            supportChains: [BerachainArtio], //an array of chains for the Particle Wallet modal (if visible is true) will be locked to.
          },
        },
      }}
    >
      <App />
    </AuthCoreContextProvider>
  </React.StrictMode>
);

Note: 特定の環境制約により、キーを.env ファイルではなく文字列として直接渡しています。

スマートアカウントの設定

AuthCoreContextProviderが設定され、Particle Auth Core が初期化されたので、主要なアプリケーションコンポーネント(上記の例ではApp)の実装に移る準備が整いました。

トランザクションを実行する前に、まずスマートアカウントを設定する必要があります。

このセットアップでは、Particle Auth Core を使用してソーシャルログインを開始し、EOA を生成します。その後、Particle の AA SDK(@particle-network/aa)がスマートアカウントの割り当てと相互作用を担当します。

上記でカバーされたプロセスの例を以下に示します。

File: ./src/App.tsx

// Imports
// ========================================================
import { BerachainArtio } from "@particle-network/chains";
import {
  AAWrapProvider,
  SendTransactionMode,
  SmartAccount,
} from "@particle-network/aa";
import {
  useEthereum
} from "@particle-network/auth-core-modal";


 // Import App
// ========================================================
import "./App.css";



const App = () => {
  const { provider } = useEthereum();
  const { connect, disconnect } = useConnect();
  const { userInfo } = useAuthCore();

  const [balance, setBalance] = useState(null);

// Smart Account Config
// ========================================================
  const smartAccount = new SmartAccount(provider, {
    projectId: "YOUR_PROJECT_ID_HERE", // Replace YOUR_PROJECT_ID_HERE with the actual project ID
        clientKey: "YOUR_CLIENT_KEY_HERE", // Replace YOUR_CLIENT_KEY_HERE with the actual client key
        appId: "YOUR_APP_ID_HERE", // Replace YOUR_APP_ID_HERE with the actual app ID
    aaOptions: {
      accountContracts: {
        SIMPLE: [{ chainIds: [BerachainArtio.id], version: '1.0.0' }],
      }
    }
  });

Ethers の設定

上記の例でのSmartAccountのインスタンスは、AAWrapProvider内で直接使用することができます。これにより、ethers.providers.Web3Providerの新しいインスタンス(または v6 を使用している場合はethers.BrowserProvider)内で使用するための AA 対応のプロバイダーオブジェクトが構築されます。この同じ構造は、Web3.js や viem にも適用することができます。

AAWrapProvider内でSendTransactionMode.Gaslessを使用し、このプロバイダーオブジェクトを介して送信されるトランザクションが、Paymaster 内で設定した条件を満たす場合にスポンサーシップの対象となるようにします(ただし、この例では条件がないため、トランザクションは無差別にスポンサーされます)。

カスタムの Ethers プロバイダーは、次のようになります:

File: ./src/App.tsx

// Imports
// ========================================================
import { BerachainArtio } from "@particle-network/chains";
import {
  AAWrapProvider,
  SendTransactionMode,
  SmartAccount,
} from "@particle-network/aa";
import {
  useEthereum
} from "@particle-network/auth-core-modal";


 // Import App
// ========================================================
import "./App.css";

const App = () => {
  const { provider } = useEthereum();
  const { connect, disconnect } = useConnect();
  const { userInfo } = useAuthCore();

  const [balance, setBalance] = useState(null);

// Smart Account Config
// ========================================================
  const smartAccount = new SmartAccount(provider, {
    projectId: "YOUR_PROJECT_ID_HERE", // Replace YOUR_PROJECT_ID_HERE with the actual project ID
        clientKey: "YOUR_CLIENT_KEY_HERE", // Replace YOUR_CLIENT_KEY_HERE with the actual client key
        appId: "YOUR_APP_ID_HERE", // Replace YOUR_APP_ID_HERE with the actual app ID
    aaOptions: {
      accountContracts: {
        SIMPLE: [{ chainIds: [BerachainArtio.id], version: '1.0.0' }],
      }
    }
  });


// Ethers Provider Setup
const customProvider = new ethers.providers.Web3Provider(new AAWrapProvider(smartAccount, SendTransactionMode.Gasless), "any");

このように初期化されたオブジェクト(この場合はcustomProvider)を使用すると、Particle を介してトランザクションの実行、残高の取得、メッセージの署名などが可能になります。ただし、これらのいずれかを実行する前に、まずソーシャルログインを実現する必要があります。次に、それについて説明します。

Particle Auth Core を使用したソーシャルログインは、useConnectフックから派生した 2 つの関数、connectdisconnectによって簡単に行うことができます。connectを呼び出すと、ソーシャルログインがすぐに開始され、指定されたソーシャルログインメカニズムのログインプロセスがユーザーによって実行されます。同様に、disconnectも呼び出されると、ユーザーはアカウントから削除されます。

また、@particle-network/auth-core からインポートされたSocialAuthTypeという特定のタイプもインポートする必要があります(これはインポートの中にあります)。

File: ./src/App.tsx

// Imports
// ========================================================
import { BerachainArtio } from "@particle-network/chains";
import {
  AAWrapProvider,
  SendTransactionMode,
  SmartAccount,
} from "@particle-network/aa";
import {
  useEthereum
} from "@particle-network/auth-core-modal";


// New addition of Imports- SocialAuthType
// ========================================================
import { SocialAuthType } from "@particle-network/auth-core";


 // Import App
// ========================================================
import "./App.css";

const App = () => {
  const { provider } = useEthereum();
  const { connect, disconnect } = useConnect();
  const { userInfo } = useAuthCore();

  const [balance, setBalance] = useState(null);

// Smart Account Config
// ========================================================
  const smartAccount = new SmartAccount(provider, {
    projectId: "YOUR_PROJECT_ID_HERE", // Replace YOUR_PROJECT_ID_HERE with the actual project ID
        clientKey: "YOUR_CLIENT_KEY_HERE", // Replace YOUR_CLIENT_KEY_HERE with the actual client key
        appId: "YOUR_APP_ID_HERE", // Replace YOUR_APP_ID_HERE with the actual app ID
    aaOptions: {
      accountContracts: {
        SIMPLE: [{ chainIds: [BerachainArtio.id], version: '1.0.0' }],
      }
    }
  });

// Ethers Provider Setup
const customProvider = new ethers.providers.Web3Provider(new AAWrapProvider(smartAccount, SendTransactionMode.Gasless), "any");

// Login Setup
// ========================================================
const handleLogin = async (authType: SocialAuthType) => {  //can be mapped to "Sign in with Google," "Sign in with X," and a miscellaneous button on the frontend by purely changing the string passed into socialType on connect
    if (!userInfo) {
      await connect({
        socialType: authType,           //a string dictating the specific authentication type to be used (such as 'google', 'twitter', etc.)
        chain: BerachainArtio,         //the specific chain you'd like to connect to. This should be BerachainArtio
      });
    }
  };

カスタム Ethers オブジェクトが構築され、ユーザーがログインした後(connectを介して)、トランザクションリクエストは埋め込まれたウォレットを介して直接 Particle に行われます。前述の Ethers オブジェクト(ここではcustomProvider)のメソッドを使用して直接行われるため、Particle との連携に特別な設定は必要ありません。

BERA のためのバーントランザクションの設定

このデモでは、2 つのトランザクションを実行し、さらに 1 つの$HONEY を燃やすためのトランザクションを行います。

最初のトランザクションでは、0.001 $BERAをガスレスで燃やすことを行います。これは、$BERA を通常0x000000000000000000000000000000000000dEaDという無効なアドレスに送信することを意味します。

このトランザクションは、次のような構造に従ったプログラム的にシンプルなものです:

File: ./src/App.tsx

// Imports
// ========================================================
import { BerachainArtio } from "@particle-network/chains";
import {
  AAWrapProvider,
  SendTransactionMode,
  SmartAccount,
} from "@particle-network/aa";
import {
  useEthereum
} from "@particle-network/auth-core-modal";

// New addition of Imports- SocialAuthType
// ========================================================
import { SocialAuthType } from "@particle-network/auth-core";

 // Import App
// ========================================================
import "./App.css";

const App = () => {
  const { provider } = useEthereum();
  const { connect, disconnect } = useConnect();
  const { userInfo } = useAuthCore();

  const [balance, setBalance] = useState(null);

// Smart Account Config
// ========================================================
  const smartAccount = new SmartAccount(provider, {
    projectId: "YOUR_PROJECT_ID_HERE", // Replace YOUR_PROJECT_ID_HERE with the actual project ID
        clientKey: "YOUR_CLIENT_KEY_HERE", // Replace YOUR_CLIENT_KEY_HERE with the actual client key
        appId: "YOUR_APP_ID_HERE", // Replace YOUR_APP_ID_HERE with the actual app ID
    aaOptions: {
      accountContracts: {
        SIMPLE: [{ chainIds: [BerachainArtio.id], version: '1.0.0' }],
      }
    }
  });

// Ethers Provider Setup
const customProvider = new ethers.providers.Web3Provider(new AAWrapProvider(smartAccount, SendTransactionMode.Gasless), "any");

// Login Setup
// ========================================================
const handleLogin = async (authType: SocialAuthType) => {  //can be mapped to "Sign in with Google," "Sign in with X," and a miscellaneous button on the frontend by purely changing the string passed into socialType on connect
    if (!userInfo) {
      await connect({
        socialType: authType,           //a string dictating the specific authentication type to be used (such as 'google', 'twitter', etc.)
        chain: BerachainArtio,         //the specific chain you'd like to connect to. This should be BerachainArtio
      });
    }
  };‎

// Burn 0.001 $BERA
// ========================================================
const executeUserOp = async () => {
    const signer = customProvider.getSigner();

    const tx = {
      to: "0x000000000000000000000000000000000000dEaD",
      value: ethers.utils.parseEther("0.001"),              //value of the $BERA that will be coverted to which needs to be converted to wei through
    };

    const txResponse = await signer.sendTransaction(tx);  //sendTransaction method
    const txReceipt = await txResponse.wait();

    notification.success({
      message: "Transaction Successful",
      description: (
        <div>
          Transaction Hash:{" "}
          <a
            href={`https://artio.beratrail.io/tx/${txReceipt.transactionHash}`}
            target="_blank"
            rel="noopener noreferrer"
          >
            {txReceipt.transactionHash}
          </a>
        </div>
      ),
    });
  };

$HONEY のためのバーントランザクションの設定

Note: $HONEYを持っていない場合でも、この機能をテストするためにいくつかの$HONEY が必要な場合は、Berachain には$BERAを$HONEY と交換するためのネイティブ DEXがあります。

2 番目のトランザクションである 1 $HONEYのバーンについては、同様のアプローチを取ることができますが、signerに直接メソッドを呼び出す代わりに、$HONEY のためのコントラクトオブジェクトを作成する必要があります。このオブジェクトに対してトランスファーメソッドを呼び出すことができます。

これは、ethers.Contractを初期化し、ABI とともに Berachain Artio 上の$HONEY コントラクトアドレスである0x7EeCA4205fF31f947EdBd49195a7A88E6A91161Bを渡すことで行うことができます。 (https://artio.beratrail.io/token/0x7EeCA4205fF31f947EdBd49195a7A88E6A91161B)

File: ./src/App.tsx

// Imports
// ========================================================
import { BerachainArtio } from "@particle-network/chains";
import {
  AAWrapProvider,
  SendTransactionMode,
  SmartAccount,
} from "@particle-network/aa";
import {
  useEthereum
} from "@particle-network/auth-core-modal";

// New addition of Imports- SocialAuthType
// ========================================================
import { SocialAuthType } from "@particle-network/auth-core";

 // Import App
// ========================================================
import "./App.css";

const App = () => {
  const { provider } = useEthereum();
  const { connect, disconnect } = useConnect();
  const { userInfo } = useAuthCore();

  const [balance, setBalance] = useState(null);

// Smart Account Config
// ========================================================
  const smartAccount = new SmartAccount(provider, {
    projectId: "YOUR_PROJECT_ID_HERE", // Replace YOUR_PROJECT_ID_HERE with the actual project ID
        clientKey: "YOUR_CLIENT_KEY_HERE", // Replace YOUR_CLIENT_KEY_HERE with the actual client key
        appId: "YOUR_APP_ID_HERE", // Replace YOUR_APP_ID_HERE with the actual app ID
    aaOptions: {
      accountContracts: {
        SIMPLE: [{ chainIds: [BerachainArtio.id], version: '1.0.0' }],
      }
    }
  });

// Ethers Provider Setup
const customProvider = new ethers.providers.Web3Provider(new AAWrapProvider(smartAccount, SendTransactionMode.Gasless), "any");

// Login Setup
// ========================================================
const handleLogin = async (authType: SocialAuthType) => {  //can be mapped to "Sign in with Google," "Sign in with X," and a miscellaneous button on the frontend by purely changing the string passed into socialType on connect
    if (!userInfo) {
      await connect({
        socialType: authType,           //a string dictating the specific authentication type to be used (such as 'google', 'twitter', etc.)
        chain: BerachainArtio,         //the specific chain you'd like to connect to. This should be BerachainArtio
      });
    }
  };

// Burn 0.001 $BERA
// ========================================================
const executeUserOp = async () => {
    const signer = customProvider.getSigner();

    const tx = {
      to: "0x000000000000000000000000000000000000dEaD",
      value: ethers.utils.parseEther("0.001"),              //value of the $BERA that will be coverted to which needs to be converted to wei through
    };

    const txResponse = await signer.sendTransaction(tx);  //sendTransaction method
    const txReceipt = await txResponse.wait();

    notification.success({
      message: "Transaction Successful",
      description: (
        <div>
          Transaction Hash:{" "}
          <a
            href={`https://artio.beratrail.io/tx/${txReceipt.transactionHash}`}
            target="_blank"
            rel="noopener noreferrer"
          >
            {txReceipt.transactionHash}
          </a>
        </div>
      ),
    });
  };


// Burn 1 $HONEY
// ========================================================
const executeUserOpHONEY = async () => {
    const signer = customProvider.getSigner();

    const tokenContract = new ethers.Contract(
      "0x7EeCA4205fF31f947EdBd49195a7A88E6A91161B",                      //official  $HONEY contract address
      ["function transfer(address to, uint256 amount)"],
      signer                                                             //retrieved through {your ethers object}.getSigner
    );

    const txResponse = await tokenContract.transfer(
      "0x000000000000000000000000000000000000dEaD",
      ethers.utils.parseEther("1")                                      // value of the $HONEY
    );
    const txReceipt = await txResponse.wait();

    notification.success({
      message: "Transaction Successful",
      description: (
        <div>
          Transaction Hash:{" "}
          <a
            href={`https://artio.beratrail.io/tx/${txReceipt.transactionHash}`}
            target="_blank"
            rel="noopener noreferrer"
          >
            {txReceipt.transactionHash}
          </a>
        </div>
      ),
    });
  };

ビルトインの Particle Wallet インターフェースを利用している場合(AuthCoreContextProvider内のvisibletrueに設定することで表示されます)、多くの ERC-20 および ERC-721 トークン($HONEY を含む)は自動的に認識されません。これらがモーダル内で自動的に反映されない場合は、残高リストの近くのプラスアイコンをクリックしてトークンを手動で追加する必要があります。

完全な App.tsx コードについては、「Recap」のすぐ下にある「Complete Code」セクションを参照してください。

dApp CSS

前述のように、主にバックエンドに焦点を当てて dApp を実行します。以下のリンクに移動し、既存の ../src/App.css に CSS コードを追加してください。

../src/App.css

https://github.com/berachain/guides/tree/main/apps/particle-auth-core-vite に移動し、テンプレートから既存のコードを使用してください!

✅ dApp のデプロイ

npm run dev;

#Expected Output:
> vite-project@0.0.0 dev
> vite


  VITE v5.1.3  ready in 117 ms

  ➜  Local:   http://localhost:5173/
  ➜  Network: use --host to expose
  ➜  press h + enter to show help

dApp は http://localhost:5173/ に正常にデプロイされます。

Localhost :— After Deployment

振り返り

このガイドで行われた手順を簡単に説明します!

  1. 開発環境の設定と必要なライブラリのインストール
  2. Particle ダッシュボードからキーを取得
  3. スマートアカウントの設定
  4. Ethers の設定
  5. ソーシャルログインの設定
  6. $BERAと$HONEY のためのバーントランザクションの設定
  7. dApp のデプロイとテスト!

このガイドは、ソーシャルベースのログインを容易にするウォレットを統合したい新しい dApp にとってのワンストップソリューションとして機能します!上記の構造とフローは、既存のアプリケーションや新しいアプリケーションに直接適用することができます。

Complete Code

../src/index.tsx

import React from "react";
import ReactDOM from "react-dom/client";
import { BerachainArtio } from "@particle-network/chains";
import { AuthCoreContextProvider } from "@particle-network/auth-core-modal";
import App from "./App";

import("buffer").then(({ Buffer }) => {
  window.Buffer = Buffer;
});

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
  <React.StrictMode>
    <AuthCoreContextProvider
      options={{
        projectId: "YOUR_PROJECT_ID_HERE", // Replace YOUR_PROJECT_ID_HERE with the actual project ID
        clientKey: "YOUR_CLIENT_KEY_HERE", // Replace YOUR_CLIENT_KEY_HERE with the actual client key
        appId: "YOUR_APP_ID_HERE", // Replace YOUR_APP_ID_HERE with the actual app ID
        erc4337: {
          name: "SIMPLE",
          version: "1.0.0",
        },
        wallet: {
          visible: true,
          customStyle: {
            supportChains: [BerachainArtio],
          },
        },
      }}
    >
      <App />
    </AuthCoreContextProvider>
  </React.StrictMode>
);

../src/App.tsx

import React, { useState, useEffect } from "react";
import { BerachainArtio } from "@particle-network/chains";
import {
  AAWrapProvider,
  SendTransactionMode,
  SmartAccount,
} from "@particle-network/aa";
import {
  useEthereum,
  useConnect,
  useAuthCore,
} from "@particle-network/auth-core-modal";
import { ethers } from "ethers";
import { Modal, notification } from "antd";

import "./App.css";

import { SocialAuthType } from "@particle-network/auth-core";

const App = () => {
  const { provider } = useEthereum();
  const { connect, disconnect } = useConnect();
  const { userInfo } = useAuthCore();

  const smartAccount = new SmartAccount(provider, {
    projectId: "YOUR_PROJECT_ID_HERE", // Replace YOUR_PROJECT_ID_HERE with the actual project ID
    clientKey: "YOUR_CLIENT_KEY_HERE", // Replace YOUR_CLIENT_KEY_HERE with the actual client key
    appId: "YOUR_APP_ID_HERE", // Replace YOUR_APP_ID_HERE with the actual app ID
    aaOptions: {
      accountContracts: {
        SIMPLE: [{ chainIds: [BerachainArtio.id], version: "1.0.0" }],
      },
    },
  });

  const customProvider = new ethers.providers.Web3Provider(
    new AAWrapProvider(smartAccount, SendTransactionMode.Gasless),
    "any"
  );

  useEffect(() => {
    if (userInfo) {
      fetchBalance();
    }
  }, [userInfo]);

  const [balance, setBalance] = useState<string | null>(null);

  const fetchBalance = async () => {
    const address = await smartAccount.getAddress();
    const balanceResponse = await customProvider.getBalance(address);
    setBalance(ethers.utils.formatEther(balanceResponse));
  };

  const handleLogin = async (authType: SocialAuthType) => {
    if (!userInfo) {
      await connect({
        socialType: authType,
        chain: BerachainArtio,
      });
    }
  };

  const executeUserOp = async () => {
    const signer = customProvider.getSigner();

    const tx = {
      to: "0x000000000000000000000000000000000000dEaD",
      value: ethers.utils.parseEther("0.001"),
    };

    const txResponse = await signer.sendTransaction(tx);
    const txReceipt = await txResponse.wait();

    notification.success({
      message: "Transaction Successful",
      description: (
        <div>
          Transaction Hash:{" "}
          <a
            href={`https://artio.beratrail.io/tx/${txReceipt.transactionHash}`}
            target="_blank"
            rel="noopener noreferrer"
          >
            {txReceipt.transactionHash}
          </a>
        </div>
      ),
    });
  };

  const executeUserOpHONEY = async () => {
    const signer = customProvider.getSigner();

    const tokenContract = new ethers.Contract(
      "0x7EeCA4205fF31f947EdBd49195a7A88E6A91161B",
      ["function transfer(address to, uint256 amount)"],
      signer
    );

    const txResponse = await tokenContract.transfer(
      "0x000000000000000000000000000000000000dEaD",
      ethers.utils.parseEther("1")
    );
    const txReceipt = await txResponse.wait();

    notification.success({
      message: "Transaction Successful",
      description: (
        <div>
          Transaction Hash:{" "}
          <a
            href={`https://artio.beratrail.io/tx/${txReceipt.transactionHash}`}
            target="_blank"
            rel="noopener noreferrer"
          >
            {txReceipt.transactionHash}
          </a>
        </div>
      ),
    });
  };

  return (
    <div className="App">
      <div className="logo-section">
        <img
          src="https://i.imgur.com/EerK7MS.png"
          alt="Logo 1"
          className="logo logo-big"
        />
        <img
          src="https://i.imgur.com/OdR3YLW.png"
          alt="Logo 2"
          className="logo"
        />
      </div>
      {!userInfo ? (
        <div className="login-section">
          <button
            className="sign-button google-button"
            onClick={() => handleLogin("google")}
          >
            <img
              src="https://i.imgur.com/nIN9P4A.png"
              alt="Google"
              className="icon"
            />
            Sign in with Google
          </button>
          <button
            className="sign-button twitter-button"
            onClick={() => handleLogin("twitter")}
          >
            <img
              src="https://i.imgur.com/afIaQJC.png"
              alt="Twitter"
              className="icon"
            />
            Sign in with X
          </button>
        </div>
      ) : (
        <div className="profile-card">
          <h2>{userInfo.name}</h2>
          <div className="balance-section">
            <small>{balance} BERA</small>
            <button className="sign-message-button" onClick={executeUserOp}>
              Burn 0.001 $BERA
            </button>
            <button
              className="sign-message-button honey"
              onClick={executeUserOpHONEY}
            >
              Burn 1 $HONEY
            </button>
            <button className="disconnect-button" onClick={() => disconnect()}>
              Logout
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default App;

../src/App.css
https://github.com/berachain/guides/tree/main/apps/particle-auth-core-viteにアクセスし、テンプレートから既存のコードを使用してください!

さらなる dApps とサポートの入手方法

Berachain について理解し、開発することに興味がある場合は、公式ガイドのリポジトリに提供されているさまざまな例のリポジトリを試してみてください。

Berachain の開発者向けドキュメントには、Hardhat や Foundry などのツールを使った複数のスターターガイドもあります!以下のリンクから、ドキュメントの開発者セクションにアクセスしてください。

開発者サポートの入手方法

⚠️ まだ問題が発生している場合や疑問がある場合は、公式 Berachain Discordに移動し、以下の GIF に示すようにチケットを作成してください!

DevRel チームが喜んでお手伝いいたします! 🤝

さようなら、開発者のみなさん! 🐻



【Sunrise とは】
Sunrise は Proof of Liquidity(PoL)と Fee Abstraction(手数料抽象化)を備えたデータ可用性レイヤーです。 私たちは DA の体験を再構築し、多様なエコシステムからのモジュラー型流動性を活用してロールアップを立ち上げています。

【Social Links】

【お問合せ】
Sunrise へのお問い合わせはこちらから 👉 Google Form

1080x360.jpeg

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0