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,并以您传递给 transferfrom 地址进行签名。

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仅使用显式 from 调用 transfer 的浏览器应用程序。
walletClient您已经有一个配置好的 WalletClient (wagmi, RainbowKit, ConnectKit)。

接下来推荐