将 SDK 与 viem 结合使用
@stablechain/sdk 基于 viem 构建。createStable 接受三种签名模式,您可以根据代码运行环境进行选择:在服务器端使用私钥,在浏览器端使用用户钱包,或者使用您已经构建的 WalletClient(例如,在 wagmi 应用程序中)。
本指南将演示每种模式的端到端实现。
服务器端:私钥 Account
使用 viem 中的 privateKeyToAccount 函数,通过后端持有的私钥进行签名。
import "dotenv/config";
import { createStable, Network } from "@stablechain/sdk";
import { privateKeyToAccount } from "viem/accounts";
const account = privateKeyToAccount(process.env.PRIVATE_KEY as `0x${string}`);
const stable = createStable({
network: Network.Mainnet,
account,
});
const { txHash } = await stable.transfer({
from: account.address,
to: "0xRecipient",
amount: 5,
});
console.log(txHash);0x8f3a...2d41浏览器端:来自钱包的 Transport
将 custom(window.ethereum)(或任何 EIP-1193 provider)作为 transport 传递。SDK 会构建 WalletClient 并从 provider 读取签名者地址。
import { createStable, Network } from "@stablechain/sdk";
import { custom } from "viem";
const stable = createStable({
network: Network.Mainnet,
transport: custom(window.ethereum),
});
const [from] = await window.ethereum.request({ method: "eth_requestAccounts" });
const { txHash } = await stable.transfer({
from,
to: "0xRecipient",
amount: 5,
});0x8f3a...2d41引入您自己的 WalletClient
当您已经拥有一个 WalletClient(例如,来自 wagmi 或自定义签名器)时,可以直接传递它。它会优先于 account 和 transport。
import { createStable, Network } from "@stablechain/sdk";
import { createWalletClient, custom } from "viem";
import { stable as stableChain } from "viem/chains";
const walletClient = createWalletClient({
chain: stableChain,
transport: custom(window.ethereum),
});
const [from] = await walletClient.requestAddresses();
const stable = createStable({
network: Network.Mainnet,
walletClient,
});
const { txHash } = await stable.transfer({ from, to: "0xRecipient", amount: 5 });0x8f3a...2d41选择一种模式
| 模式 | 何时使用 |
|---|---|
account | 后端服务、脚本、代理,任何您持有私钥的地方。 |
transport | 浏览器应用程序,用户通过 MetaMask 或无 wagmi 的自定义流程进行签名。 |
walletClient | 您已经有一个配置好的 WalletClient (wagmi、RainbowKit、ConnectKit)。 |
接下来推荐
- 与 wagmi 结合使用:通过 wagmi 钩子将 SDK 集成到 React 应用程序中。
- SDK 参考:所有配置字段、方法、枚举和错误类。
- SDK 快速入门:在测试网上运行您的第一个转账、桥接和兑换。

