进阶 docs.web3js.org 2026-10-19 02:32:30 · 12 阅读

第20章 Wagmi 集成 web3.js 适配器实践指南

Wagmi Web3.js 适配器参考实现 如果你在用 Wagmi,同时想引入 web3.js,可以在项目中使用下面的代码。这段代码能把 Viem client 转换成 web3.js 实例,用于签署交易和与区块链交互: import { Web3 } from 'web3';
import { useMemo } from 'react';
import type { Chain, Client, Transport } from 'viem';
import { type Config, useClient, useConnectorClient } from 'wagmi';

export function clientToWeb3js(client?: Client) {
if (!client) {
return new Web3();
}

const { transport } = client;

if (transport.type === 'fallback') {
return new Web3(transport.transports[0].value.url);
}
return new Web3(transport);
}

/ Action to convert a viem Client to a web3.js Instance. */
export function useWeb3js({ chainId }: { chainId?: number } = {}) {
const client = useClient({ chainId });
return useMemo(() => clientToWeb3js(client), [client]);
}

/
Action to convert a viem ConnectorClient to a web3.js Instance. */
export function useWeb3jsSigner({ chainId }: { chainId?: number } = {}) {
const { data: client } = useConnectorClient({ chainId });
return useMemo(() => clientToWeb3js(client), [client]);
}
使用示例 获取区块数据的例子: import { useWeb3js } from '../web3/useWeb3js';
import { mainnet } from 'wagmi/chains';
import { useEffect, useState } from 'react';

type Block = {
hash: string;
extraData: string;
miner: string;
};

function Block() {
const web3js = useWeb3js({ chainId: mainnet.id });
const [block, setBlock] = useState();

useEffect(() => {
web3js.eth
.getBlock(19235006)
.then(b => {
setBlock(b as Block);
})
.catch(console.error);
}, [setBlock]);

if (!block) return
Loading...
;

return (
<>
{block.hash}

{block.extraData}

{block.miner}


);
}

export default Block;
发送交易的例子: import { mainnet } from 'wagmi/chains';
import { useAccount, useConnect } from 'wagmi';
import { useWeb3jsSigner } from '../web3/useWeb3js';
import { useEffect } from 'react';

function SendTransaction() {
const account = useAccount();
const { connectors, connect } = useConnect();
该仓库包含一个 Wagmi 示例应用,展示如何使用 web3.js 库与以太坊区块链进行交互

评论 (0)