此软件包提供了一个嵌入式钱包连接器 瓦格米语Name,哪个 是Ethereum常用的 React Hooks 库.
在应用程序中使用Wagmi的开发者应当能够使用所提供的 将 CDP 嵌入式钱包集成到框中 进入他们现有的环境.
快速启动
这个向导会帮助您开始 @coinbase/cdp-wagmi。你会学会如何安装软件包, 设置提供者, 并制作您的第一个组件.
安装
首先,使用您首选的软件包管理器将软件包添加到您的项目中 .
# With pnpm
pnpm add @coinbase/cdp-wagmi @coinbase/cdp-core @tanstack/react-query viem wagmi
# With yarn
yarn add @coinbase/cdp-wagmi @coinbase/cdp-core @tanstack/react-query viem wagmi
# With npm
npm install @coinbase/cdp-wagmi @coinbase/cdp-core @tanstack/react-query viem wagmi
收集您的 CDP 项目信息
- 在此处签名或创建账户 CDP 门户
- 在您的仪表板上,从最上方的下拉位置选择一个项目,并复制项目ID
允许列出本地应用程序
- 导航到 嵌入式钱包配置 在 CDP 门户网站中,单击添加来源以包含本地应用程序
- 输入本地运行的应用程序的出处 - 例如 ,
http://localhost:3000 - 点击 重新添加来源以保存您的更改
设置提供者
下一位,您必须配置您的 Wagmi 提供程序 CDPEmbeddedWalletConnector。 。 。 .
CDPEmbeddedWalletConnector 提供Wagmi正确工作的必要背景
(原始内容存档于2018-03-21). the CDP Frontend SDK. 这个 providerConfig 必须提供并负责:
配置 EIP-1193 供应商用于广播非Base 的运输工具
交易.
import React from 'react';
import ReactDOM from 'react-dom/client';
import { App } from './App'; // Your main App component
import { Config }from '@coinbase/cdp-core';
import { createCDPEmbeddedWalletConector } from '@coinbase/cdp-wagmi';
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { http }from "viem";
import { baseSepolia, base } from 'viem/chains';
import { WagmiProvider, createConfig, http } from 'wagmi';
// Your CDP config
const cdpConfig: Config = {
projectId: "your-project-id", // Copy your Project ID here.
}
const connector = createCDPEmbeddedWalletConnector({
cdpConfig: cdpConfig,
providerConfig:{
chains: [base, baseSepolia],
transports: {
[base.id]: http(),
[baseSepolia.id]: http()
}
}
});
const wagmiConfig = createConfig({
connectors: [connector],
chains: [base, baseSepolia],
transports: {
[base.id]: http(),
[baseSepolia.id]: http(),
},
});
const queryClient = new QueryClient(); // For use with react-query
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<WagmiProvider config={wagmiConfig} >
<QueryClientProvider client={ queryClient }>
<App />
</QueryClientProvider>
</WagmiProvider>
</React.StrictMode>,
);
分析
默认SDK会释放出使用分析器来帮助我们改进SDK. 如果您想选择退出,您可以通过设置 disableAnalytics 配置选项到 true。 。 。 .
const cdpConfig: Config = {
projectId: "your-project-id", // Copy your Project ID here.
disableAnalytics: true,
}
签名和连接
为了连接到CDP嵌入式钱包,终端应用程序用户必须先从流中走出2步的标志. 因此,消费者有三种选择:
- 使用 @ coinbase/ cdp- core's 的标签
signInWithEmail+ 键verifyEmailOTP - 使用@ coinbase/ cdp- hooks'
useSignInWithEmail+ 键useVerifyEmailOTP - 使用@ coinbase/ cdp- react
<SignIn />组件
在使用任何这些方法后,CDP嵌入式钱包的连接器应该自动连接.
给瓦格米虎克打电话
现在,你的应用应该能够 成功地调用Wagmi钩。 例如:
import { useState } from "react";
import { parseEther } from "viem";
import { useAccount, useSendTransaction, useWaitForTransactionReceipt } from "wagmi";
/**
* The burn address (0x0000000000000000000000000000000000000000)
*/
const BURN_ADDRESS = "0x0000000000000000000000000000000000000000" as const;
/**
* The amount to send in ETH (0.00001 ETH)
*/
const AMOUNT_TO_SEND = "0.00001";
/**
* A component that demonstrates wagmi's useSendTransaction hook
* by sending 0.00001 ETH to the burn address.
*
* @returns A component that allows the user to send a transaction using wagmi.
*/
export default function WagmiTransaction() {
const { address } = useAccount();
const [isLoading, setIsLoading] = useState(false);
const { data: hash, sendTransaction, isPending, error } = useSendTransaction();
const { isLoading: isConfirming, isSuccess } = useWaitForTransactionReceipt({
hash,
});
const handleSendTransaction = async () => {
if (!address) return;
setIsLoading(true);
try {
sendTransaction({
to: BURN_ADDRESS,
value: parseEther(AMOUNT_TO_SEND),
});
} catch (error) {
console.error("Failed to send transaction:", error);
} finally {
setIsLoading(false);
}
};
const handleReset = () => {
// Reset by refreshing the page or clearing state
window.location.reload();
};
return (
<div>
<div>
<p>
⚠️ Warning: This will send {AMOUNT_TO_SEND} ETH to the burn address (0x0000...0000).
This transaction cannot be reversed and the ETH will be permanently lost.
</p>
</div>
<div>
<div>
<div>Amount: {AMOUNT_TO_SEND} ETH</div>
<div>To (Burn Address): {BURN_ADDRESS.slice(0, 6)}...{BURN_ADDRESS.slice(-4)}</div>
<div>From: {address?.slice(0, 6)}...{address?.slice(-4)}</div>
</div>
</div>
{error && (
<div>
<strong>Error:</strong> {error.message}
</div>
)}
{!hash && !isPending && !isLoading && (
<button disabled={!address} onClick={handleSendTransaction}>
Send {AMOUNT_TO_SEND} ETH to Burn Address
</button>
)}
{(isPending || isConfirming) && (
<div>
<div>Sending transaction...</div>
{hash && (
<div>
Hash: {hash.slice(0, 10)}...{hash.slice(-8)}
</div>
)}
</div>
)}
{isSuccess && hash && (
<div>
<div>
<div>✅</div>
</div>
<div>
<div>Transaction Confirmed!</div>
<div>Your transaction has been successfully sent to the burn address</div>
</div>
<div>
<div>Amount: {AMOUNT_TO_SEND} ETH</div>
<div>To: {BURN_ADDRESS.slice(0, 6)}...{BURN_ADDRESS.slice(-4)}</div>
<div>
Block Explorer:{" "}
<a
href={`https://sepolia.basescan.org/tx/${hash}`}
target="_blank"
rel="noopener noreferrer"
>
{hash.slice(0, 10)}...{hash.slice(-8)}
</a>
</div>
</div>
<button onClick={handleReset}>
Send Another Transaction →
</button>
</div>
)}
</div>
);
}
智能账户
此软件包对 Wagmi 有智能账户支持 useSendCalls, (中文(简体) ), useCallsStatus 财务报告和审定财务报表 useCapabilities 钩子. 它需要一个不同的 CDP 配置 而非 EOA 钱包 :
const cdpConfig: Config = {
projectId: "your-project-id", // Copy your Project ID here.
ethereum: {
createOnLogin: "smart" // Create a smart account by default when a user logs in and does not yet have one
}
}
注册后, 您可以使用 Wagmi 钩子发送用户操作 :
import { useState } from "react";
import { parseEther } from "viem";
import { useAccount, useSendCalls, useSendCalls, useCallsStatus, useCapabilities } from "wagmi";
/**
* The burn address (0x0000000000000000000000000000000000000000)
*/
const BURN_ADDRESS = "0x0000000000000000000000000000000000000000" as const;
/**
* The amount to send in ETH (0.00001 ETH)
*/
const AMOUNT_TO_SEND = "0.00001";
/**
* SendCalls component that allows users with Smart Accounts to send ETH to the burn address
*
* @returns JSX element with transaction sending functionality
*/
export function WagmiSendCalls() {
const { address, isConnected } = useAccount();
const { data: userOpHash, sendCalls, isPending, error } = useSendCalls();
// Check the status of a sent user operation
const { isLoading: isConfirming, isSuccess } = useCallsStatus({
id: userOpHash as Hex,
query: {
enabled: !!userOpHash,
},
});
const chainId = useChainId();
const { data: walletCapabilities } = useCapabilities({
chainId,
});
// Check the capabilities of the wallet to determine if you can use user operations
const isSendCallsSupported = useMemo(() => {
return walletCapabilities?.atomic?.status === "supported";
}, [walletCapabilities]);
const handleSendCalls = async () => {
if (!isConnected || !address) return;
try {
sendCalls(
{
calls: [
{
to: BURN_ADDRESS,
value: parseEther(AMOUNT_TO_SEND),
},
],
}
);
} catch (err) {
console.log("Failed to send user operation: ", err)
}
};
if (!isSendCallsSupported) {
return (
<div>
<p>
This wallet does not support sending calls on chain {chainId}. Ensure your wallet has a
smart account, and is on a supported chain.
</p>
</div>
);
}
return (
<div>
<div>
<p>
⚠️ Warning: This will send {AMOUNT_TO_SEND} ETH to the burn address (0x0000...0000).
This operation cannot be reversed and the ETH will be permanently lost.
</p>
</div>
<div>
<div>
<div>Amount: {AMOUNT_TO_SEND} ETH</div>
<div>To (Burn Address): {BURN_ADDRESS.slice(0, 6)}...{BURN_ADDRESS.slice(-4)}</div>
<div>From: {address?.slice(0, 6)}...{address?.slice(-4)}</div>
</div>
</div>
{error && (
<div>
<strong>Error:</strong> {error.message}
</div>
)}
{!userOpHash && !isPending && (
<button disabled={!address} onClick={handleSendCalls}>
Send {AMOUNT_TO_SEND} ETH to Burn Address
</button>
)}
{(isPending || isConfirming) && (
<div>
<div>Sending transaction...</div>
{hash && (
<div>
Hash: {hash.slice(0, 10)}...{hash.slice(-8)}
</div>
)}
</div>
)}
{isSuccess && userOpHash && (
<div>
<div>
<div>✅</div>
</div>
<div>
<div>Operation Sent!</div>
<div>Your operation has been successfully sent to the burn address</div>
</div>
<div>
<div>Amount: {AMOUNT_TO_SEND} ETH</div>
<div>To: {BURN_ADDRESS.slice(0, 6)}...{BURN_ADDRESS.slice(-4)}</div>
<div>
Block Explorer:{" "}
<a
href={`https://sepolia.basescan.org/tx/${userOpHash}`}
target="_blank"
rel="noopener noreferrer"
>
{hash.slice(0, 10)}...{hash.slice(-8)}
</a>
</div>
</div>
<button onClick={handleReset}>
Send Another Operation →
</button>
</div>
)}
</div>
);
}
与EIP-8021的交易归属:
您可以在智能账户操作中添加归属数据, 用于跟踪应用程序的使用和收入共享 dataSuffix 能力:
import { useSendCalls, useChainId } from "wagmi;
import { parseEther, type Hex } from "viem";
function SendCallsWithAttribution() {
const { sendCalls, isPending } = useSendCalls();
const chainId = useChainId();
const handleSendWithAttribution = async () => {
// EIP-8021 data suffix for "baseapp" attribution (Schema ID 0)
const dataSuffix = "0xdddddddd62617365617070070080218021802180218021802180218021" as Hex;
await sendCalls({
calls: [
{
to: "0xTargetContract",
value: parseEther("0.001"),
}
],
capabilities: {
dataSuffix: {
value: dataSuffix // Attribution data appended to callData
}
}
});
};
return (
<button onClick={handleSendWithAttribution} disabled={isPending}>
Send with Attribution
</button>
);
}
这个 dataSuffix 能力接受后面的十六进制字符串 EIP-8021标准后缀自动附加到用户操作的 callData (c) 建立供应链归属、便于跟踪使用和收入分享机制.
正在检查数据后缀支持 :
使用 useCapabilities 检查钱包是否支持数据后缀:
import { useCapabilities, useChainId } from "wagmi/experimental";
function CheckDataSuffixSupport() {
const { data: capabilities } = useCapabilities();
const chainId = useChainId();
const supportsDataSuffix = capabilities?.[chainId.toString()]?.dataSuffix?.supported;
return (
<div>
Data Suffix Support: {supportsDataSuffix ? "✅ Supported" : "❌ Not Supported"}
</div>
);
}