@blend-money/fe

中文文档
3.1.1发布于 2026/11/03MITTypeScriptES Module近 30 天下载 3413

Blend SDK for B2B neobank integrations.

原始使用文档
文档目录18 节
  1. Install
  2. Quick Start
  3. Configuration
  4. Paymaster providers
  5. API Reference
  6. Authentication
  7. Session Persistence
  8. Discovery
  9. Amount Helpers
  10. Quoting
  11. Live Quoting
  12. Execution
  13. Account Data
  14. Safe Management
  15. Power-User: Session Lifecycle
  16. Error Handling
  17. Development
  18. License

Blend SDK

npm version npm downloads per week npm downloads per month

TypeScript SDK for the Blend Protocol. Frontend-first, wallet-authenticated via SIWE.

Install

pnpm add @blend-money/fe

Peer dependencies: viem

Quick Start

import { BlendSdk, getPimlicoPaymasterEndpoints } from "@blend-money/fe";

const sdk = new BlendSdk({
  publishableKey: "pk_live_...",
  signMessage: walletClient.signMessage,
  paymaster: getPimlicoPaymasterEndpoints("pim_..."),
});

// 1. Discover what's available
const chains = await sdk.discover.depositChains();
const tokens = await sdk.discover.depositTokens(8453);

// 2. Sign in with SIWE
const session = await sdk.signIn({ address: "0x...", chainId: 8453 });

// 3. Get a quote
const quote = await sdk.quoteDeposit({
  chainId: 8453,
  tokenAddress: "0xA0b86991...",
  amount: "1000000",
});

// 4. Show confirmation UI
console.log(quote.input); // { symbol: "USDC", amount: "1000000", amountUsd: "1" }
console.log(quote.output); // { symbol: "USDC", amount: "1000000", amountUsd: "1" }
console.log(quote.fees); // { totalUsd: "0.01" }

// 5. Execute
const result = await sdk.execute(quote, {
  signerAddress: address,
  deriveSigner: async (chainId) => ({
    signer: getWalletClient({ chainId }),
    publicClient: getPublicClient({ chainId }),
  }),
  onStatusChange: (status) => console.log(status),
});

if (result.status === "settled") {
  console.log("Done!", result.txHashes);
}

Configuration

const sdk = new BlendSdk({
  // Required
  publishableKey: "pk_live_...", // Safe for client-side code
  signMessage: (msg) => wallet.sign(msg), // SIWE signature function

  // Required — validated at construction; sponsors Safe UserOps in execute()
  paymaster: {
    /* per-chain ERC-4337 bundler/paymaster endpoints — see below */
  },

  // Optional
  baseUrl: "https://...", // API base URL override
  fiatCurrency: "EUR", // ISO 4217 code for multi-currency
  timeoutMs: 15000, // Request timeout (default: 15000)
  retries: 3, // Max retries for 429/5xx (default: 3)
});

Paymaster providers

paymaster is a per-chain registry of provider-tagged endpoints — the synchronous source of truth for which ERC-4337 bundler/paymaster serves each chain and the metadata that provider needs.

Single-provider setups are one call — chainIds defaults to every chain the provider serves:

import {
  getAlchemyPaymasterEndpoints,
  getPimlicoPaymasterEndpoints,
} from "@blend-money/fe";

// Pimlico everywhere
paymaster: getPimlicoPaymasterEndpoints("pim_...");

// Alchemy everywhere
paymaster: getAlchemyPaymasterEndpoints("alch_...", {
  policyId: "your-gas-manager-policy-id",
});

Mixed setups spread slices together. Later spreads override earlier ones for the same chain ID, so give the minority provider an explicit chain list:

paymaster: {
  ...getPimlicoPaymasterEndpoints("pim_..."),
  ...getAlchemyPaymasterEndpoints(
    "alch_...",
    { policyId: "your-gas-manager-policy-id" },
    [9745], // Plasma — not served by Pimlico
  ),
},

Pimlico endpoints need only the API key (the URL serves as both bundler transport and paymaster). Alchemy endpoints additionally carry the Gas Manager policy ID, forwarded as ERC-7677 paymaster context (pm_getPaymasterStubData / pm_getPaymasterData). Executing on a chain missing from the registry throws a validation error.

The provider tag also selects the gas price source: UserOperation fees are quoted from the configured bundler at execution time, each provider following its vendor's documented recipe — Pimlico endpoints via pimlico_getUserOperationGasPrice (fast tier), Alchemy endpoints via the rundler_maxPriorityFeePerGas quote buffered +25% plus the buffered latest base fee. No extra configuration is needed, and the Blend API plays no role in gas pricing.

API Reference

Authentication

// Sign in — wallet prompted to sign a SIWE message
const session = await sdk.signIn({ address: "0x...", chainId: 8453 });
// session: { address, accountId, safeAddress, chainsDeployed, expiresAt }

// Sign out
await sdk.signOut();

// Check state
sdk.isSignedIn; // boolean
sdk.session; // AuthSession (throws if not signed in)

Session Persistence

Sessions are in-memory by default and lost on page reload. Use exportSession() and restoreSession() to persist across reloads. Expired tokens are automatically refreshed on the next API call. Use sessionStorage (cleared when the tab closes) unless you need cross-tab persistence — localStorage extends XSS exposure to the token's full lifetime.

// After sign-in, save the session
await sdk.signIn({ address: "0x...", chainId: 8453 });
sessionStorage.setItem("blend-session", JSON.stringify(sdk.exportSession()));

// On page load, restore the session
const stored = sessionStorage.getItem("blend-session");
if (stored) {
  try {
    sdk.restoreSession(JSON.parse(stored));
    // sdk.isSignedIn === true — no wallet prompt needed
  } catch {
    // Corrupt data — fall back to signIn
    sessionStorage.removeItem("blend-session");
  }
}

Discovery

No authentication required. When signed in, depositTokens automatically filters to tokens the wallet holds.

const chains = await sdk.discover.depositChains();
// [{ chainId, name, displayName, iconUrl }]

const tokens = await sdk.discover.depositTokens(8453);
// [{ chainId, address, symbol, name, decimals, logoURI, price, balance?, amount? }]

const destinations = await sdk.discover.withdrawDestinations();
// [{ chainId, name, loanTokenAddress }]

const yieldData = await sdk.discover.yield();
// { accountTypeId, yieldBreakdown: [{ chainId, vaultAddress, breakdown, summary }] }

Amount Helpers

The SDK requires amounts in the token's smallest unit (e.g. "1000000" for 1 USDC). Use parseAmount and formatAmount to convert between human-readable and smallest-unit strings without floating-point precision loss.

import { parseAmount, formatAmount } from "@blend-money/fe";

// Human-readable → smallest unit
const smallest = parseAmount("100.50", 6); // "100500000" (USDC has 6 decimals)

// Smallest unit → human-readable
const human = formatAmount("100500000", 6); // "100.5"

// Use with discovered tokens
const tokens = await sdk.discover.depositTokens(8453);
const usdc = tokens.find((t) => t.symbol === "USDC")!;
const amount = parseAmount(userInput, usdc.decimals);
const quote = await sdk.quoteDeposit({
  chainId: 8453,
  tokenAddress: usdc.address,
  amount,
});

Quoting

Requires authentication. Creates or reuses a session, then quotes it. Returns a clean object for your confirmation UI.

// Deposit quote
const quote = await sdk.quoteDeposit({
  chainId: 8453,
  tokenAddress: "0xA0b86991...",
  amount: "1000000",
  externalRef: "order-123", // optional — for reconciliation
  forceReset: false, // optional — cancel existing session first (default: false)
});
// DepositQuote: { type, intentId, originChainId, destinationChainId,
//   input, output, fees, estimatedSeconds, expiresAt }

// Withdrawal quote
const quote = await sdk.quoteWithdraw({
  destinationChainId: 8453,
  amount: "1000000",
  isMaxWithdraw: false, // optional — redeem all shares (default: false)
  forceReset: false, // optional
});
// WithdrawQuote: { type, intentId, destinationChainId, totalAmount,
//   totalFeesUsd, estimatedSeconds, sourceChainCount, expiresAt }

Live Quoting

Calling quoteDeposit or quoteWithdraw multiple times re-quotes the same open session with the new parameters. No need for forceReset just to change the amount or token.

// User types $1
const quote1 = await sdk.quoteDeposit({
  chainId: 8453,
  tokenAddress: "0xA0b86991...",
  amount: parseAmount("1", 6),
});

// User changes to $5 — same session, fresh quote
const quote2 = await sdk.quoteDeposit({
  chainId: 8453,
  tokenAddress: "0xA0b86991...",
  amount: parseAmount("5", 6),
});
// quote2 reflects the updated amount — same intentId, fresh prices

// Switching from withdraw to deposit also works on open sessions
const depositQuote = await sdk.quoteDeposit({ ... });

Execution

Pass a quote, a signer address, and a deriveSigner callback that returns viem clients for a given chain. The SDK handles session locking, on-chain submission (Safe UserOps via the paymaster), hash submission, and settlement polling internally. For multi-chain withdrawals, deriveSigner is called once per source chain.

const result = await sdk.execute(quote, {
  signerAddress: address, // EOA address (Hex)
  deriveSigner: async (chainId) => ({
    // returns viem clients for the chain
    signer: getWalletClient({ chainId }),
    publicClient: getPublicClient({ chainId }),
  }),
  isContractSigner: false, // optional — for smart contract wallets (e.g. Coinbase)
  onStatusChange: (status) => {
    // optional — "executing" | "confirming" | "settled" | "failed"
    updateUI(status);
  },
  pollIntervalMs: 3000, // optional (default: 3000)
  pollTimeoutMs: 300000, // optional (default: 300000)
});
// ExecuteResult: { status, txHashes, settledAt, error }

Account Data

Requires authentication.

const balance = await sdk.account.balance();
// { accountId, safeAddress, perChain, total }

const history = await sdk.account.balanceHistory({ startDate: "2025-01-01" });
// [{ id, createdAt, totalValue, totalYield, breakdown }]

const positions = await sdk.account.positions();
// { accountId, safeAddress, events }

const returns = await sdk.account.returns();
// { current, totalDeposited, totalWithdrawn, netDeposited, returns, returnsPct }

Safe Management

// Resolve Safe deployment on a chain (requires auth)
const resolution = await sdk.account.safe.resolve(8453);
// { status: "validated", accountId, userAddress, safeAddress, chainId }

// Request Safe deployment (requires auth)
await sdk.account.safe.request(8453);

// Look up account by EOA (no auth required)
const account = await sdk.account.safe.lookup("0x...");
// { accountId, safeAddress, chainsDeployed }

Power-User: Session Lifecycle

For advanced use cases, the full intent session lifecycle is available via sdk.sessions:

const session = await sdk.sessions.createSession({ forceReset: true });
const quoted = await sdk.sessions.quoteDeposit(session.intentId, { ... });
const locked = await sdk.sessions.lock(session.intentId, { signerAddress: "0x..." });
const submitted = await sdk.sessions.submit(session.intentId, { txHashes: [...] });
const result = await sdk.sessions.execute(session.intentId, { ... });
const sessions = await sdk.sessions.list();
await sdk.sessions.cancel(session.intentId);

Error Handling

import { SdkError, SESSION_ERROR_CODES } from "@blend-money/fe";

try {
  await sdk.quoteDeposit({ ... });
} catch (err) {
  if (err instanceof SdkError) {
    console.log(err.code);            // e.g. "AUTH_NOT_SIGNED_IN"
    console.log(err.status);          // HTTP status
    console.log(err.getUserMessage()); // human-readable message
    console.log(err.isRetryable());   // true for 429, 5xx, network errors
  }
}

Error codes: AUTH_NOT_SIGNED_IN, AUTH_CHALLENGE_FAILED, AUTH_VERIFICATION_FAILED, AUTH_TOKEN_EXPIRED, AUTH_INVALID_SESSION, INTENT_NOT_FOUND, INTENT_EXPIRED, INTENT_WRONG_STATUS, INTENT_CONCURRENT_TRANSITION, SESSION_NOT_QUOTED, SESSION_LOCKED_BY_OTHER, SETTLEMENT_TIMEOUT, FLOWPLAN_CONFLICT.

Development

From the monorepo root:

pnpm install                              # Install all dependencies
pnpm --filter @blend-money/fe build      # Build this package
pnpm --filter @blend-money/fe dev        # Watch mode
pnpm --filter @blend-money/fe test       # Run tests (interactive)
pnpm --filter @blend-money/fe test:run   # Run tests (CI)
pnpm --filter @blend-money/fe check-types # Type check

Or run pnpm build, pnpm test:run, etc. from the monorepo root to run across all packages.

License

MIT

版本与发布记录

@blend-money/fe 共发布 15 个版本,首次发布于 2026/05/07;过去 12 个月发布了 15 个版本。

版本发布日期距今
3.1.1latest2026/11/035 天前
3.1.02026/10/051 个月前
3.0.12026/07/243 个月前
3.0.02026/07/233 个月前
2.0.02026/07/143 个月前
1.2.12026/07/044 个月前

关于 @blend-money/fe 的常见问题

@blend-money/fe 是什么?

Blend SDK for B2B neobank integrations.

如何安装 @blend-money/fe?

在项目目录运行 npm install @blend-money/fe,或使用 pnpm add / yarn add / bun add。

@blend-money/fe 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@blend-money/fe 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@blend-money/fe 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js ^22.23.4 || ^24.22.1 || ^26.12.1。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@blend-money/fe 可以商用吗?

@blend-money/fe 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@blend-money/fe 的下载量有多少?

根据 npm 官方下载统计,@blend-money/fe 在 2026/10/09 – 2026/11/07 这 30 天内被下载 3,413 次,日均约 114 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@blend-money/fe 还在维护吗?

最新版本 3.1.1 发布于 2026/11/03(5 天前);至今共发布 15 个版本,其中过去 12 个月发布了 15 个;首次发布于 2026/05/07。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。