@coinbase/cdp-wagmi

中文文档
0.0.130发布于 2026/11/10TypeScriptES Module零依赖近 30 天下载 8197

This package provides an embedded wallet connector for Wagmi, which is a commonly used React Hooks library for Ethereum.

原始使用文档
文档目录8 节
  1. Quickstart
  2. Installation
  3. Gather your CDP Project information
  4. Allowlist your local app
  5. Setup Provider
  6. Sign in and connection
  7. Call Wagmi Hooks
  8. Smart Accounts

This package provides an embedded wallet connector for Wagmi, which is a commonly used React Hooks library for Ethereum.

Developers who use Wagmi in their application should be able to use the provided {@link createCDPEmbeddedWalletConnector} out of the box to integrate CDP embedded wallets into their existing environment.

Quickstart

This guide will help you get started with @coinbase/cdp-wagmi. You'll learn how to install the package, set up the provider, and render your first component.

Installation

First, add the package to your project using your preferred package manager.

# 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

Gather your CDP Project information

  1. Sign in or create an account on the CDP Portal
  2. On your dashboard, select a project from the dropdown at the at the top, and copy the Project ID

Allowlist your local app

  1. Navigate to the Embedded Wallet Configuration in CDP Portal, and click Add origin to include your local app
  2. Enter the origin of your locally running app - e.g., http://localhost:3000
  3. Click Add origin again to save your changes

Setup Provider

Next, you must configure your WagmiProvider with the CDPEmbeddedWalletConnector.

CDPEmbeddedWalletConnector provides the necessary context Wagmi to work correctly with the CDP Frontend SDK. The providerConfig must be provided and is responsible for configuring the EIP-1193 provider's transports which are used to broadcast non-Base transactions.

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>,
);

Analytics Opt-Out

By default the SDK will emit usage analytics to help us improve the SDK. If you would like to opt-out, you can do so by setting the disableAnalytics configuration option to true.

const cdpConfig: Config = {
  projectId: "your-project-id", // Copy your Project ID here.
  disableAnalytics: true,
}

Sign in and connection

In order to connect the CDP Embedded Wallet, the end application user must first go through the 2 step sign in flow. As a result, the consumer has 3 options:

  1. Use @coinbase/cdp-core's signInWithEmail + verifyEmailOTP
  2. Use @coinbase/cdp-hooks' useSignInWithEmail + useVerifyEmailOTP
  3. Use @coinbase/cdp-react <SignIn /> component

After using any of these methods, the CDP embedded wallet's connector should automatically connect.

Call Wagmi Hooks

Now, your application should be able to successfully call Wagmi hooks. For example:

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>
  );
}

Smart Accounts

This package has Smart Account support for the Wagmi useSendCalls, useCallsStatus and useCapabilities hooks. It requires a different CDP Config than for EOA wallets:

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
  }
}

After signing in, you can send a User Operation using Wagmi hooks:

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>
  );
}

Transaction Attribution with EIP-8021:

You can add attribution data to Smart Account operations for tracking app usage and revenue sharing using the dataSuffix capability:

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>
  );
}

The dataSuffix capability accepts a hex-encoded string following the EIP-8021 standard. The suffix is automatically appended to the user operation's callData for onchain attribution, enabling usage tracking and revenue sharing mechanisms.

Checking Data Suffix Support:

Use useCapabilities to check if the wallet supports data suffix:

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>
  );
}

版本与发布记录

@coinbase/cdp-wagmi 共发布 129 个版本,首次发布于 2025/07/12;过去 12 个月发布了 71 个版本。

版本发布日期距今
0.0.130latest2026/11/10今天
0.0.1292026/11/055 天前
0.0.1282026/10/2219 天前
0.0.1272026/10/071 个月前
0.0.1262026/09/191 个月前
0.0.1252026/09/191 个月前

其他发布通道:placeholder → 0.0.0。

关于 @coinbase/cdp-wagmi 的常见问题

@coinbase/cdp-wagmi 是什么?

This package provides an embedded wallet connector for Wagmi, which is a commonly used React Hooks library for Ethereum.

如何安装 @coinbase/cdp-wagmi?

在项目目录运行 npm install @coinbase/cdp-wagmi,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:viem(^2.47.0)、react(>=18.2.0)、wagmi(^2.16.0)、@coinbase/cdp-core(^0.0.130)、@tanstack/react-query(^5.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@coinbase/cdp-wagmi 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@coinbase/cdp-wagmi 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@coinbase/cdp-wagmi 可以商用吗?

@coinbase/cdp-wagmi 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@coinbase/cdp-wagmi 的下载量有多少?

根据 npm 官方下载统计,@coinbase/cdp-wagmi 在 2026/10/11 – 2026/11/09 这 30 天内被下载 8,197 次,日均约 273 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@coinbase/cdp-wagmi 还在维护吗?

最新版本 0.0.130 发布于 2026/11/10(今天);至今共发布 129 个版本,其中过去 12 个月发布了 71 个;首次发布于 2025/07/12。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。