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 与 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 或自定义签名器)时,可以直接传递它。它会优先于 accounttransport

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)。

接下来推荐