bankr-x402-sdk---client-patterns by bankrbot/claude-plugins
npx skills add https://github.com/bankrbot/claude-plugins --skill 'Bankr x402 SDK - Client Patterns'适用于 Bankr SDK 项目的可复用客户端代码和通用文件。
所有 Bankr SDK 项目的核心 SDK 客户端模块:
import "dotenv/config";
import { BankrClient } from "@bankr/sdk";
// ============================================
// 验证
// ============================================
if (!process.env.BANKR_PRIVATE_KEY) {
throw new Error(
"BANKR_PRIVATE_KEY 环境变量是必需的。 " +
"该钱包为每次请求支付 0.01 USDC(需要在 Base 链上有 USDC)。"
);
}
// ============================================
// 客户端设置
// ============================================
/**
* Bankr SDK 客户端
*
* 提供支持 AI 的 Web3 操作和 x402 微支付。
* 每个 API 请求花费 0.01 USDC(从 Base 链上的支付钱包支付)。
*
* @example
* ```typescript
* import { bankrClient } from "./bankr-client";
*
* // 代币兑换
* const swap = await bankrClient.promptAndWait({
* prompt: "在 Base 链上将 0.1 ETH 兑换为 USDC",
* });
*
* // 查询余额
* const balances = await bankrClient.promptAndWait({
* prompt: "我的代币余额是多少?",
* });
* ```
*
* @see https://www.npmjs.com/package/@bankr/sdk
*/
export const bankrClient = new BankrClient({
// 必需:支付钱包私钥
// 该钱包为每个 API 请求支付 0.01 USDC(必须在 Base 链上有 USDC)
privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`,
// 可选:覆盖接收钱包地址
// 如果未设置,代币将发送到支付钱包地址
walletAddress: process.env.BANKR_WALLET_ADDRESS,
// 可选:API 端点(默认为生产环境)
...(process.env.BANKR_API_URL && { baseUrl: process.env.BANKR_API_URL }),
});
// 导出钱包地址以供参考
export const walletAddress = bankrClient.getWalletAddress();
// ============================================
// 类型(从 SDK 重新导出)
// ============================================
export type { JobStatusResponse, Transaction } from "@bankr/sdk";
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
使用 viem 的交易执行助手:
import { createWalletClient, http, type WalletClient } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base, mainnet, polygon } from "viem/chains";
import type { Transaction } from "@bankr/sdk";
// 链配置
const chains = {
8453: base,
1: mainnet,
137: polygon,
} as const;
// 创建用于交易执行的钱包客户端
const account = privateKeyToAccount(
process.env.BANKR_PRIVATE_KEY as `0x${string}`
);
function getWalletClient(chainId: number): WalletClient {
const chain = chains[chainId as keyof typeof chains];
if (!chain) {
throw new Error(`不支持的链 ID: ${chainId}`);
}
return createWalletClient({
account,
chain,
transport: http(),
});
}
/**
* 执行 Bankr SDK 返回的交易
*
* @example
* ```typescript
* const result = await bankrClient.promptAndWait({
* prompt: "将 0.1 ETH 兑换为 USDC",
* });
*
* if (result.transactions?.length) {
* const hash = await executeTransaction(result.transactions[0]);
* console.log("交易:", hash);
* }
* ```
*/
export async function executeTransaction(tx: Transaction): Promise<string> {
const txData = tx.metadata.transaction;
const client = getWalletClient(txData.chainId);
console.log(`在链 ${txData.chainId} 上执行 ${tx.type}...`);
const hash = await client.sendTransaction({
to: txData.to as `0x${string}`,
data: txData.data as `0x${string}`,
value: BigInt(txData.value || "0"),
gas: BigInt(txData.gas),
});
console.log(`交易已提交: ${hash}`);
return hash;
}
/**
* 执行 Bankr 结果中的所有交易
*/
export async function executeAllTransactions(
transactions: Transaction[]
): Promise<string[]> {
const hashes: string[] = [];
for (const tx of transactions) {
const hash = await executeTransaction(tx);
hashes.push(hash);
}
return hashes;
}
所有 Bankr SDK 项目的基础 package.json:
{
"name": "{project-name}",
"version": "0.1.0",
"description": "{description}",
"type": "module",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "tsx src/index.ts"
},
"dependencies": {
"@bankr/sdk": "^1.0.0",
"dotenv": "^16.3.1",
"viem": "^2.0.0"
},
"devDependencies": {
"@types/node": "^20.10.0",
"tsx": "^4.7.0",
"typescript": "^5.3.0"
}
}
根据项目模板添加:
Web 服务(Express):
"dependencies": {
"express": "^4.18.0"
},
"devDependencies": {
"@types/express": "^4.17.21"
}
CLI:
"dependencies": {
"commander": "^12.0.0"
}
TypeScript 配置:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
环境变量模板:
# Bankr SDK 配置
# 参见:https://docs.bankr.bot
# 必需:支付钱包私钥
# 该钱包为每个 API 请求支付 0.01 USDC(必须在 Base 链上有 USDC)
# 格式:64 个十六进制字符,带 0x 前缀
BANKR_PRIVATE_KEY=0x
# 可选:接收钱包地址
# 兑换/购买的代币发送到此地址。如果未设置,则默认为支付钱包。
# BANKR_WALLET_ADDRESS=0x
# 可选:API 端点覆盖(默认为 https://api.bankr.bot)
# BANKR_API_URL=https://api.bankr.bot
标准忽略模式:
# 依赖项
node_modules/
# 构建输出
dist/
# 环境
.env
.env.local
.env.*.local
# 日志
*.log
npm-debug.log*
# IDE
.idea/
.vscode/
*.swp
*.swo
# 操作系统
.DS_Store
Thumbs.db
# 测试
coverage/
import { bankrClient } from "./bankr-client";
const result = await bankrClient.promptAndWait({
prompt: "ETH 的价格是多少?",
onStatusUpdate: (msg) => console.log("进度:", msg),
});
console.log(result.response);
import { bankrClient } from "./bankr-client";
import { executeTransaction } from "./executor";
const result = await bankrClient.promptAndWait({
prompt: "在 Base 链上将 0.1 ETH 兑换为 USDC",
});
if (result.status === "completed" && result.transactions?.length) {
// 执行前审查
console.log("交易准备就绪:", result.transactions[0].type);
console.log("详情:", result.transactions[0].metadata.__ORIGINAL_TX_DATA__);
// 执行
const hash = await executeTransaction(result.transactions[0]);
console.log("已执行:", hash);
}
import { bankrClient } from "./bankr-client";
import { executeAllTransactions } from "./executor";
async function performSwap(prompt: string) {
try {
const result = await bankrClient.promptAndWait({
prompt,
onStatusUpdate: console.log,
});
if (result.status === "completed") {
console.log("成功:", result.response);
if (result.transactions?.length) {
const hashes = await executeAllTransactions(result.transactions);
console.log("交易:", hashes);
}
} else if (result.status === "failed") {
console.error("失败:", result.error);
}
} catch (error) {
console.error("错误:", error.message);
}
}
import { bankrClient } from "./bankr-client";
// 余额查询不返回交易
const balances = await bankrClient.promptAndWait({
prompt: "我在 Base 链上的余额是多少?",
});
console.log(balances.response);
// 价格查询
const price = await bankrClient.promptAndWait({
prompt: "DEGEN 的价格",
});
console.log(price.response);
请查阅 sdk-capabilities 技能以获取:
请查阅 sdk-token-swaps 技能以获取:
每周安装量
0
代码仓库
GitHub 星标数
70
首次出现
1970年1月1日
Reusable client code and common files for Bankr SDK projects.
The core SDK client module for all Bankr SDK projects:
import "dotenv/config";
import { BankrClient } from "@bankr/sdk";
// ============================================
// Validation
// ============================================
if (!process.env.BANKR_PRIVATE_KEY) {
throw new Error(
"BANKR_PRIVATE_KEY environment variable is required. " +
"This wallet pays $0.01 USDC per request (needs USDC on Base)."
);
}
// ============================================
// Client Setup
// ============================================
/**
* Bankr SDK Client
*
* Provides AI-powered Web3 operations with x402 micropayments.
* Each API request costs $0.01 USDC (paid from payment wallet on Base).
*
* @example
* ```typescript
* import { bankrClient } from "./bankr-client";
*
* // Token swap
* const swap = await bankrClient.promptAndWait({
* prompt: "Swap 0.1 ETH to USDC on Base",
* });
*
* // Check balances
* const balances = await bankrClient.promptAndWait({
* prompt: "What are my token balances?",
* });
* ```
*
* @see https://www.npmjs.com/package/@bankr/sdk
*/
export const bankrClient = new BankrClient({
// Required: Payment wallet private key
// This wallet pays $0.01 USDC per API request (must have USDC on Base)
privateKey: process.env.BANKR_PRIVATE_KEY as `0x${string}`,
// Optional: Override receiving wallet address
// If not set, tokens are sent to the payment wallet address
walletAddress: process.env.BANKR_WALLET_ADDRESS,
// Optional: API endpoint (defaults to production)
...(process.env.BANKR_API_URL && { baseUrl: process.env.BANKR_API_URL }),
});
// Export the wallet address for reference
export const walletAddress = bankrClient.getWalletAddress();
// ============================================
// Types (re-exported from SDK)
// ============================================
export type { JobStatusResponse, Transaction } from "@bankr/sdk";
Transaction execution helper using viem:
import { createWalletClient, http, type WalletClient } from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { base, mainnet, polygon } from "viem/chains";
import type { Transaction } from "@bankr/sdk";
// Chain configuration
const chains = {
8453: base,
1: mainnet,
137: polygon,
} as const;
// Create wallet client for transaction execution
const account = privateKeyToAccount(
process.env.BANKR_PRIVATE_KEY as `0x${string}`
);
function getWalletClient(chainId: number): WalletClient {
const chain = chains[chainId as keyof typeof chains];
if (!chain) {
throw new Error(`Unsupported chain ID: ${chainId}`);
}
return createWalletClient({
account,
chain,
transport: http(),
});
}
/**
* Execute a transaction returned by the Bankr SDK
*
* @example
* ```typescript
* const result = await bankrClient.promptAndWait({
* prompt: "Swap 0.1 ETH to USDC",
* });
*
* if (result.transactions?.length) {
* const hash = await executeTransaction(result.transactions[0]);
* console.log("Transaction:", hash);
* }
* ```
*/
export async function executeTransaction(tx: Transaction): Promise<string> {
const txData = tx.metadata.transaction;
const client = getWalletClient(txData.chainId);
console.log(`Executing ${tx.type} on chain ${txData.chainId}...`);
const hash = await client.sendTransaction({
to: txData.to as `0x${string}`,
data: txData.data as `0x${string}`,
value: BigInt(txData.value || "0"),
gas: BigInt(txData.gas),
});
console.log(`Transaction submitted: ${hash}`);
return hash;
}
/**
* Execute all transactions from a Bankr result
*/
export async function executeAllTransactions(
transactions: Transaction[]
): Promise<string[]> {
const hashes: string[] = [];
for (const tx of transactions) {
const hash = await executeTransaction(tx);
hashes.push(hash);
}
return hashes;
}
Base package.json for all Bankr SDK projects:
{
"name": "{project-name}",
"version": "0.1.0",
"description": "{description}",
"type": "module",
"main": "dist/index.js",
"scripts": {
"build": "tsc",
"start": "node dist/index.js",
"dev": "tsx src/index.ts"
},
"dependencies": {
"@bankr/sdk": "^1.0.0",
"dotenv": "^16.3.1",
"viem": "^2.0.0"
},
"devDependencies": {
"@types/node": "^20.10.0",
"tsx": "^4.7.0",
"typescript": "^5.3.0"
}
}
Add based on project template:
Web Service (Express):
"dependencies": {
"express": "^4.18.0"
},
"devDependencies": {
"@types/express": "^4.17.21"
}
CLI:
"dependencies": {
"commander": "^12.0.0"
}
TypeScript configuration:
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
Environment variables template:
# Bankr SDK Configuration
# See: https://docs.bankr.bot
# Required: Payment wallet private key
# This wallet pays $0.01 USDC per API request (must have USDC on Base)
# Format: 64 hex characters with 0x prefix
BANKR_PRIVATE_KEY=0x
# Optional: Receiving wallet address
# Tokens from swaps/purchases go here. Defaults to payment wallet if not set.
# BANKR_WALLET_ADDRESS=0x
# Optional: API endpoint override (defaults to https://api.bankr.bot)
# BANKR_API_URL=https://api.bankr.bot
Standard ignore patterns:
# Dependencies
node_modules/
# Build output
dist/
# Environment
.env
.env.local
.env.*.local
# Logs
*.log
npm-debug.log*
# IDE
.idea/
.vscode/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# Testing
coverage/
import { bankrClient } from "./bankr-client";
const result = await bankrClient.promptAndWait({
prompt: "What is the price of ETH?",
onStatusUpdate: (msg) => console.log("Progress:", msg),
});
console.log(result.response);
import { bankrClient } from "./bankr-client";
import { executeTransaction } from "./executor";
const result = await bankrClient.promptAndWait({
prompt: "Swap 0.1 ETH to USDC on Base",
});
if (result.status === "completed" && result.transactions?.length) {
// Review before executing
console.log("Transaction ready:", result.transactions[0].type);
console.log("Details:", result.transactions[0].metadata.__ORIGINAL_TX_DATA__);
// Execute
const hash = await executeTransaction(result.transactions[0]);
console.log("Executed:", hash);
}
import { bankrClient } from "./bankr-client";
import { executeAllTransactions } from "./executor";
async function performSwap(prompt: string) {
try {
const result = await bankrClient.promptAndWait({
prompt,
onStatusUpdate: console.log,
});
if (result.status === "completed") {
console.log("Success:", result.response);
if (result.transactions?.length) {
const hashes = await executeAllTransactions(result.transactions);
console.log("Transactions:", hashes);
}
} else if (result.status === "failed") {
console.error("Failed:", result.error);
}
} catch (error) {
console.error("Error:", error.message);
}
}
import { bankrClient } from "./bankr-client";
// Balance queries don't return transactions
const balances = await bankrClient.promptAndWait({
prompt: "What are my balances on Base?",
});
console.log(balances.response);
// Price queries
const price = await bankrClient.promptAndWait({
prompt: "Price of DEGEN",
});
console.log(price.response);
Consult the sdk-capabilities skill for:
Consult the sdk-token-swaps skill for:
Weekly Installs
0
Repository
GitHub Stars
70
First Seen
Jan 1, 1970
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
106,200 周安装