Are you an LLM? Read llms.txt for a summary of the docs, or llms-full.txt for the full context.
Skip to content

将 SDK 与 wagmi 结合使用

createStable 接受一个 viem WalletClient,这正是 wagmi 的 useWalletClient 返回的。您像往常一样通过 wagmi 连接钱包,然后在钱包客户端更改时记忆一个 StableClient

本指南假设使用 wagmi v2 和 @tanstack/react-query

1. 配置 wagmi

将 Stable 添加到 wagmi 配置中。viem 提供了两个网络的链定义。

import { http, createConfig } from "wagmi";
import { stable as stableMainnet, stableTestnet } from "viem/chains";
import { injected } from "wagmi/connectors";
 
export const wagmiConfig = createConfig({
  chains: [stableMainnet, stableTestnet],
  connectors: [injected()],
  transports: {
    [stableMainnet.id]: http(),
    [stableTestnet.id]: http(),
  },
});
WagmiConfig { chains: [988, 2201], connectors: [injected] }

2. 构建一个返回 StableClient 的 Hook

针对当前的 WalletClient 记忆一个 StableClient。当钱包客户端的身份发生变化时重新创建它。

import { useMemo } from "react";
import { useWalletClient } from "wagmi";
import { createStable, Network, type StableClient } from "@stablechain/sdk";
 
export function useStable(network: Network = Network.Mainnet): StableClient | null {
  const { data: walletClient } = useWalletClient();
 
  return useMemo(() => {
    if (!walletClient) return null;
    return createStable({ network, walletClient });
  }, [walletClient, network]);
}

3. 在组件中使用它

import { useAccount, useChainId } from "wagmi";
import { Network } from "@stablechain/sdk";
import { useStable } from "./useStable";
 
export function PayButton() {
  const { address } = useAccount();
  const chainId = useChainId();
  const stable = useStable(Network.Mainnet);
 
  async function onClick() {
    if (!stable || !address) return;
    const { txHash } = await stable.transfer({
      from: address,
      to: "0xRecipient",
      amount: 1,
    });
    console.log("Sent:", txHash);
  }
 
  return (
    <button disabled={!stable} onClick={onClick}>
      支付 1 USDT0 (链 {chainId}
    </button>
  );
}
Sent: 0x8f3a...2d41

4. 从 React 执行桥接和兑换

同一个 stable 实例处理桥接和兑换。在 effect 或 useQuery 中获取报价,然后点击执行。

const stable = useStable(Network.Mainnet);
 
const onSwap = async () => {
  if (!stable) return;
  const quote = await stable.quoteSwap({
    fromToken: "0x8a2B28364102Bea189D99A475C494330Ef2bDD0B",
    toToken: "0x779Ded0c9e1022225f8E0630b35a9b54bE713736",
    amount: 100,
    fromDecimals: 6,
  });
  const { txHash, toAmount } = await stable.swap({
    fromToken: quote.fromToken,
    toToken: "0x779Ded0c9e1022225f8E0630b35a9b54bE713736",
    amount: 100,
    fromDecimals: 6,
    quote,
  });
  console.log({ txHash, toAmount });
};
{ txHash: "0xabcd...", toAmount: 99.81 }

下一步建议