将 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,并以您传递给 transfer 的 from 地址进行签名。
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 | 仅使用显式 from 调用 transfer 的浏览器应用程序。 |
walletClient | 您已经有一个配置好的 WalletClient (wagmi, RainbowKit, ConnectKit)。 |
接下来推荐
- 与 wagmi 结合使用:通过 wagmi 钩子将 SDK 集成到 React 应用程序中。
- SDK 参考:每个配置字段、方法、枚举和错误类。
- SDK 快速入门:在测试网上运行您的第一个转账、桥接和兑换。

