如何在 Berachain 测试网上使用 Particle Network 构建社交登录 dApp | 开发者必备
本指南详细介绍了如何在 Berachain Artio 测试网上使用 Particle Auth Core 和 AA SDK 构建启用了社交登录和智能账户的 dApp。通过配置 Ethers、自定义交易及销毁 $BERA 和 $HONEY,开发者可以轻松实现 Web3 项目集成。完整步骤包括项目设置、关键库安装和测试部署,适合新手及经验丰富的区块链开发者。
BM 开发者熊熊们!🐻
Berachain 的 Artio 测试网启动后,在社区中引起了广泛关注。Artio在 用户中的热度无人能及,其强大的流动性证明共识机制(Proof-of-Liquidity)进一步激发了开发者和团队在测试网上部署的热情!
在 Berachain 的 Artio 测试网启动后不久,Particle Network 推出了智能钱包即服务(Smart Wallet-as-a-Service)支持,允许在 Berachain 上开发的开发者立即开始原型设计原生利用社交登录功能的应用程序,以创建和管理 EOA(外部拥有账户)以及相关的智能账户(目前是 SimpleAccount 实现)。
本文是与 Particle Network 开发者关系团队的 Tabasco 共同完成的,感谢在从零开始设计 dApp 模板过程中提供的帮助!🤝 🐻
- Node.js 版本需大于 20 和最新的 npm。如果需要,请参考此指南:https://docs.npmjs.com/downloading-and-installing-node-js-and-npm
- 开发工具如 VScode、Replit 等。
- $BERA:Berachain 的原生 gas 代币,创建新钱包并用于演示时将需要此代币。(https://artio.faucet.berachain.com)
- $HONEY:Berachain 的原生稳定币,可以通过官方的 Berachain Dex/Bex 获取。(https://artio.bex.berachain.com)
- 访问 Particle Network 的开发者控制台。(https://dashboard.particle.network/)
通过 Particle Auth Core 实现社交登录
🤔 为什么选择社交登录?
基于社交的登录方式被证明是实现“更简单的 Web3 入门”这一目标的重要一步,尤其对于主要使用 Web2 应用的用户而言。
通过社交登录,用户可以使用他们喜欢的社交媒体账户轻松完成身份验证,从而简化了入门流程。众所周知,要与 Web3 dApp 互动,我们需要一个钱包。Particle Networks 正在弥合这一差距,用户在成功验证身份后,可以通过该平台获得一个与其账户关联的 Web3 钱包地址。
🛠️ 我们正在构建什么?
本教程将重点介绍如何通过 Particle Auth Core 和 Particle 的 AA SDK,在 Berachain Artio 测试网上构建一个启用了智能钱包即服务(WaaS)的应用程序。该应用程序将复制上方嵌入 dApp 中的功能。
本指南不会专注于前端,但会分享前端代码。总体上,我们将完成以下内容:
- 启动社交登录(在本例中,通过 Google 或 X,以及通用身份验证模式)。
- 为通过社交登录生成的 EOA(外部拥有账户)分配一个 SimpleAccount。
- 执行一笔无 gas 费用的销毁交易(0.001 $BERA)。
- 执行销毁 1 $HONEY(Berachain 的原生稳定币)。
完成本教程后,你应该能够了解如何在 Berachain 项目中集成 Particle Auth Core,或者简单地在 Berachain 测试网上获得一个社交登录模板,利用展示的结构和流程。
为你的应用构建基础
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 的过程,你需要安装一些关键库来进行配置。具体来说,你需要安装:
- @particle-network/auth-core-modal:这是用于实现 Particle Auth Core 的核心 SDK,之前名为 @particle-network/auth。
- @particle-network/aa:用于分配一个 SimpleAccount,并生成一个启用了 AA(Account Abstraction)的自定义 EIP-1193 提供程序对象,以通过 Ethers 控制智能账户。
- @particle-network/chains:用于配置 Particle Auth Core,其中包含 Berachain 特定信息的对象(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 控制台获取密钥
在构建 AuthCoreContextProvider 之前,你需要三个值来初始化 Particle Auth Core。无论是在配置 Particle Auth Core、Particle Connect 还是 Particle 的 AA SDK 时,都需要从 Particle 控制台获取项目 ID、客户端密钥和应用 ID。
这些值将你的应用与 Particle 控制台上的项目链接起来,从而验证 API 请求、跟踪用户、允许无代码模式自定义等。
1.前往 particlenetwork.com,然后点击右上角的“Dashboard”。
Particle Network 首页
2. 点击“Add New Project”(添加新项目),输入你选择的项目名称,然后点击“Save”(保存)。
Dashboard 主页
3. 现在你将能够获取到“Project ID”(项目ID)和“Client Key”(客户端密钥)。
应用程序界面
4. 要获取“App ID”,点击“Your Apps”选项卡下的“Web”,然后点击“Ok”。
应用程序中的 Web 应用部分突出显示
5. 在“App Name”中输入你选择的名称。对于域名,你可以填写“google.com”或填写你应用程序托管的域名(如果已经托管)。
获取应用 ID
6.“App ID” 现在应在 “Your Apps” 部分中可见。
获取应用 ID
6. “App ID” 现在应在 “Your Apps” 部分中可见。
“Your Apps” 下的 App ID
一旦这些库安装完毕,你就可以开始进行配置了。
通过 Particle Auth Core 实现社交登录:
Particle Auth Core 通过 AuthCoreContextProvider(从 @particle-network/auth-core-modal 导入)来管理配置,这是一个用于包裹主应用组件(或其等效组件)的对象,放置在你的 index 文件中。它包含用于验证 Particle Auth 实例的关键值,并启用社交登录或嵌入钱包模式的核心自定义功能。
通过 Particle 控制台设置好项目和应用后,你就可以配置 AuthCoreContextProvider 了。
文件路径: ./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>
);
注意:由于特定的环境限制,我们直接将密钥作为字符串传递,而不是通过 .env 文件。
配置智能账户
现在,AuthCoreContextProvider 已经配置好,并且 Particle Auth Core 已初始化,你可以继续实现你的主要应用组件(在上面的例子中,这就是 App)。
在执行交易之前,你需要先配置你的智能账户。
在此设置中,Particle Auth Core 用于启动社交登录并生成一个 EOA(外部拥有账户)。在此之后,Particle 的 AA SDK(@particle-network/aa)负责分配并促进与智能账户的交互。
下面是该过程的一个示例。
文件路径: ./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 中使用,以构建一个支持 AA(账户抽象)的提供者对象,该对象可用于一个新的 ethers.providers.Web3Provider 实例(如果你使用的是 v6,则是 ethers.BrowserProvider)。同样的结构也可以应用于 Web3.js 或 viem。
我们将在 AAWrapProvider 中使用 SendTransactionMode.Gasless,确保通过该提供者对象发送的交易将符合 Paymaster 中设定的条件并受到资助(尽管在这个例子中没有设置条件,因此所有交易将无差别地得到资助)。
你自定义的 Ethers 提供者应如下所示:
文件路径: ./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 hook 导出的两个函数:connect 和 disconnect 来实现。当调用 connect 时,社交登录将立即启动,用户将经历指定社交登录方式的登录过程。同样,当调用 disconnect 时,用户将从其账户中注销。
此外,我们还需要导入从 @particle-network/auth-core 导入的特定类型 SocialAuthType。(这将在导入部分中体现)。
文件路径: ./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 的销毁交易
在此演示中,我们将执行两笔交易,并进行另一笔销毁 1 $HONEY 的交易。
对于第一笔交易,我们将执行 0.001 $BERA 的无 gas 销毁,实际上是将 $BERA 发送到一个死地址,通常是 0x000000000000000000000000000000000000dEaD。
这笔交易在编程上相当简单,遵循类似于以下的结构:
文件路径: ./src/App.tsx
4o
// 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 的销毁交易
注意:如果你没有 $HONEY 但想测试这个功能,Berachain 有一个原生 DEX,可以支持将 $BERA 兑换成 $HONEY。
对于第二笔交易,即销毁 1 $HONEY(Berachain 的原生稳定币),我们可以采用类似的方法,不过这次我们不会直接调用 signer 上的方法,而是需要为 $HONEY 创建一个合约对象,并在该对象上调用 transfer 方法。
这可以通过简单地初始化 ethers.Contract 来完成,传入 0x7EeCA4205fF31f947EdBd49195a7A88E6A91161B(Berachain Artio 上的 $HONEY 合约地址)以及 ABI。(ABI 链接)
文件路径: ./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>
),
});
};
设置 $HONEY 的销毁交易
注意:如果你没有 $HONEY 但想测试这个功能,Berachain 有一个原生 DEX,可以支持将 $BERA 兑换成 $HONEY。
对于第二笔交易,即销毁 1 $HONEY(Berachain 的原生稳定币),我们可以采用类似的方法,不过这次我们不会直接调用 signer 上的方法,而是需要为 $HONEY 创建一个合约对象,并在该对象上调用 transfer 方法。
这可以通过简单地初始化 ethers.Contract 来完成,传入 0x7EeCA4205fF31f947EdBd49195a7A88E6A91161B(Berachain Artio 上的 $HONEY 合约地址)以及 ABI。(ABI 链接)
文件路径: ./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 中将 visible 设置为 true 显示),许多 ERC-20 和 ERC-721 代币(包括 $HONEY)不会被自动识别。如果这些代币没有自动显示在模态框中,你需要通过余额列表旁边的加号图标手动添加代币。
完整的 App.tsx 代码,请参考“回顾”下方的“完整代码”部分。
dApp CSS
如前所述,我们主要专注于后端并使 dApp 运行。点击以下链接,将 CSS 代码添加到你现有的 ../src/App.css
文件中。
../src/App.css
前往 https://github.com/berachain/guides/tree/main/apps/particle-auth-core-vite,并使用模板中的现有代码!
✅ 部署 dApp4o
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/。
本地服务器:— 部署后
回顾
以下是本指南中执行的步骤的简要总结:
- 设置开发环境并安装所需库。
- 从 Particle 控制台获取密钥。
- 配置智能账户。
- 设置 Ethers。
- 设置社交登录。
- 设置 $BERA 和 $HONEY 的销毁交易。
- 部署并测试 dApp!
本指南为新 dApp 提供了一站式解决方案,帮助它们集成支持社交登录和 AA 功能的钱包!类似的结构和流程可以直接应用于现有和新应用程序。
完整代码../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,建议尝试官方指南仓库中提供的各种示例代码库 —
https://github.com/berachain/guides/tree/main/apps/particle-auth-core-vite
Berachain 的开发者文档中还提供了多个入门指南,包含 Hardhat、Foundry 等常用工具!请访问以下链接中的开发者部分了解更多信息。
https://docs.berachain.com/developers
如何获得开发者支持?
⚠️ 仍然遇到问题或有疑问?请前往官方 Berachain Discord,提交工单!
我们的开发者关系团队将很乐意为您提供帮助!🤝
再见,开发者胖熊们!🐻
❤️ 别忘了为这篇文章点赞 👏🏼
原创文章,作者:Rama Ai,如若转载,请注明出处:https://www.dappchaser.com/social-login-dapp-with-particle-network-on-berachain-testnet/