@circle-fin/swap-kit

中文文档
1.9.1发布于 2026/11/06TypeScriptESM + CJS近 30 天下载 3万

A Circle SDK for single-chain token swaps with minimal code

原始使用文档
文档目录27 节
  1. Table of Contents
  2. Overview
  3. Developer Documentation
  4. Installation
  5. Quick Start
  6. Class-Based Usage
  7. Functional Usage (Tree-Shakeable)
  8. Configuration
  9. Custom Fees
  10. 1. Percentage-Based Fees
  11. 2. Callback-Based Fees
  12. Custom Providers (typed)
  13. Authentication
  14. Swap Configuration Options
  15. Supported Tokens
  16. Type Definitions
  17. SwapParams
  18. SwapEstimate
  19. SwapResult
  20. Resolving Chain Name to ChainDefinition
  21. CustomFeePolicy
  22. Validation
  23. Usage Patterns: Class vs Functional
  24. Use Class-Based (SwapKit) When:
  25. Use Functional (createSwapKitContext + operations) When:
  26. License
  27. Support

Swap Kit

npm version TypeScript License Discord

A Circle SDK for single-chain token swaps with minimal code, backed by strong type safety and comprehensive validation.

Making swapping as simple as a single function call

Table of Contents

Overview

SwapKit provides a foundation for building tree-shakeable swap operations with:

  • 🔒 Type Safety: Full TypeScript support with strict type checking
  • ✅ Runtime Validation: Comprehensive Zod schemas for parameter validation
  • 📝 Rich Documentation: Complete JSDoc with runnable examples
  • 🎯 Developer Experience: IntelliSense support and clear error messages
  • 🔧 Flexible Configuration: Customizable fee policies and swap strategies

Developer Documentation

Installation

npm install @circle-fin/swap-kit
# or
yarn add @circle-fin/swap-kit

Quick Start

SwapKit offers two usage patterns - choose the one that fits your project best:

  • Chain selection is constrained to swap-supported networks. Supported chains include mainnet networks with CCTP v2 and at least one supported token (USDC, USDT, EURC, or other registered tokens). Current examples: Ethereum, Base, Polygon, Arbitrum, Optimism, Avalanche, Monad, Solana, and others. Use getSupportedChains() to get the complete, up-to-date list.

Class-Based Usage

import { SwapKit } from '@circle-fin/swap-kit'
import { createViemAdapterFromPrivateKey } from '@circle-fin/adapter-viem-v2'

// Create a SwapKit instance
const kit = new SwapKit()

// Create an adapter
const adapter = createViemAdapterFromPrivateKey({
  privateKey: process.env.PRIVATE_KEY,
})

// Define swap parameters
const params = {
  from: { adapter, chain: 'Ethereum' },
  tokenIn: 'USDC',
  tokenOut: 'USDT',
  amountIn: '100.50',
  config: {
    apiKey: process.env.CIRCLE_API_KEY,
    slippageBps: 300, // 3% slippage tolerance
    allowanceStrategy: 'permit',
  },
}

// Get an estimate
const estimate = await kit.estimate(params)
console.log(
  `Estimated output: ${estimate.estimatedOutput?.amount} ${estimate.estimatedOutput?.token}`,
)

// Execute the swap
const result = await kit.swap(params)

Functional Usage (Tree-Shakeable)

import { createSwapKitContext, estimate, swap } from '@circle-fin/swap-kit'
import { createViemAdapterFromPrivateKey } from '@circle-fin/adapter-viem-v2'

// Create a swap context
const context = createSwapKitContext()

// Create an adapter
const adapter = createViemAdapterFromPrivateKey({
  privateKey: process.env.PRIVATE_KEY,
})

// Define swap parameters
const params = {
  from: { adapter, chain: 'Ethereum' },
  tokenIn: 'USDC',
  tokenOut: 'USDT',
  amountIn: '100.50',
  config: {
    apiKey: process.env.CIRCLE_API_KEY,
    slippageBps: 300,
    allowanceStrategy: 'permit',
  },
}

// Get an estimate
const quoteResult = await estimate(context, params)
console.log(
  `Estimated output: ${quoteResult.estimatedOutput?.amount} ${quoteResult.estimatedOutput?.token}`,
)

// Execute the swap
const result = await swap(context, params)

Both patterns provide identical functionality - the class-based approach offers a familiar class-based interface, while the functional approach allows for better tree-shaking and smaller bundle sizes.

Configuration

Custom Fees

SwapKit supports two approaches for charging custom developer fees.

1. Percentage-Based Fees

For straightforward percentage-based fees:

await kit.swap({
  from: { adapter, chain: Ethereum },
  tokenIn: 'USDC',
  tokenOut: 'DAI',
  amountIn: '100',
  config: {
    apiKey: process.env.CIRCLE_API_KEY,
    customFee: {
      percentageBps: 1000, // 10% fee (100 = 1%)
      recipientAddress: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
    },
  },
})

2. Callback-Based Fees

For complex fee logic:

Class-Based:

const kit = new SwapKit({
  customFeePolicy: {
    computeFee: async (ctx) => {
      // Full context with adapter, chain, tokens, amounts
      if (ctx.type === 'output') {
        // Output fee scenario
        // Access to minAmount and estimatedAmount
        const user = await getUser(ctx.from.address)
        if (user.isVIP) {
          return (parseFloat(ctx.minAmount) * 0.05).toString()
        }
        return (parseFloat(ctx.estimatedAmount) * 0.1).toString()
      }

      // Input fee scenario
      return (parseFloat(ctx.amountIn) * 0.05).toString()
    },

    resolveFeeRecipientAddress: (chain, ctx) => {
      return chain.type === 'solana'
        ? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'
        : '0x1234567890123456789012345678901234567890'
    },
  },
})

// Or set/update it later
kit.setCustomFeePolicy({
  computeFee: (ctx) => {
    if (ctx.from.chain.name === 'Ethereum') {
      return (parseFloat(ctx.amountIn) * 0.01).toString()
    }
    return (parseFloat(ctx.amountIn) * 0.005).toString()
  },
  resolveFeeRecipientAddress: (chain) => '0x...',
})

// Remove the fee policy when needed
kit.removeCustomFeePolicy()

Functional:

import {
  createSwapKitContext,
  setCustomFeePolicy,
  removeCustomFeePolicy,
} from '@circle-fin/swap-kit'

const context = createSwapKitContext({
  customFeePolicy: {
    computeFee: async (ctx) => {
      if (ctx.type === 'output') {
        return (parseFloat(ctx.estimatedAmount) * 0.1).toString()
      }
      return (parseFloat(ctx.amountIn) * 0.05).toString()
    },
    resolveFeeRecipientAddress: (chain, ctx) => {
      return chain.type === 'solana' ? 'Sol...' : '0x...'
    },
  },
})

// Or set/update later
setCustomFeePolicy(context, {
  computeFee: () => '0.05',
  resolveFeeRecipientAddress: (chain) => '0x...',
})

// Remove when needed
removeCustomFeePolicy(context)

Custom Providers (typed)

import { createSwapKitContext } from '@circle-fin/swap-kit'

class ExperimentalSwapProvider {
  readonly name = 'ExperimentalSwapProvider'
  // implements SwappingProvider methods (supportsRoute, estimate, swap)
}

const extraProviders = [new ExperimentalSwapProvider()] as const
const context = createSwapKitContext({ providers: extraProviders })

// TypeScript knows the exact provider types:
type RegisteredProviders = typeof context.providers
//    ^? readonly [...DefaultProviders, ExperimentalSwapProvider]

The context merges default providers with any custom providers you supply while preserving their literal types. This keeps context.providers strongly typed and ready for future provider integrations.

Authentication

Pass a Circle API key as config.apiKey to authenticate service-backed operations. Omit it to use the permissionless (keyless) path.

config: {
  apiKey: process.env.CIRCLE_API_KEY, // <ENV>_API_KEY:<keyId>:<keySecret>
}

The API key is a server-only secret — supplying it from a browser throws. Hold it on your server and forward the prepared transaction to the client.

Migrating from kitKey: config.kitKey is deprecated in favor of config.apiKey. It keeps working, and legacy KIT_KEY:<keyId>:<keySecret> values are still accepted, so you can move over at your own pace. When both fields are set, apiKey wins.

Swap Configuration Options

const params = {
  from: { adapter, chain: Ethereum },
  tokenIn: 'USDC',
  tokenOut: 'USDT',
  amountIn: '100',
  config: {
    // API key for authentication (optional — omit for permissionless mode)
    apiKey: process.env.CIRCLE_API_KEY,

    // Allowance strategy (default: 'permit')
    allowanceStrategy: 'permit', // or 'approve'

    // Maximum slippage in basis points (default: 300 = 3%)
    slippageBps: 300,

    // Minimum output amount (stop-limit)
    stopLimit: '95000000', // 95 USDT in smallest units

    // Custom fee for this specific swap (percentage approach)
    customFee: {
      percentageBps: 100, // 1% fee
      recipientAddress: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
    },

    // Batch approve + swap into one atomic call when the wallet supports it
    // (default). Set false to send approval and swap as two transactions.
    batchTransactions: true,
  },
}

Note: Use transaction-level percentageBps for simple fees, or kit-level setCustomFeePolicy() for complex logic. They are mutually exclusive.

Supported Tokens

SwapKit supports 16 tokens for fee collection. At least one token (input OR output) must be from this list.

Stablecoins (6 decimals):

  • USDC - USD Coin
  • EURC - Euro Coin
  • USDT - Tether USD
  • PYUSD - PayPal USD

Stablecoins (18 decimals):

  • DAI - MakerDAO stablecoin
  • USDE - Ethena USD

Wrapped Tokens:

  • WBTC - Wrapped Bitcoin (8 decimals)
  • WETH - Wrapped Ethereum (18 decimals)
  • WSOL - Wrapped Solana (9 decimals)
  • WAVAX - Wrapped Avalanche (18 decimals)
  • WPOL - Wrapped Polygon (18 decimals)

Native Token:

  • NATIVE - Resolves to chain's native gas token (ETH on Ethereum, SOL on Solana, etc.)

Important: At least one token (input OR output) must be from the supported list. Non-supported → Non-supported swaps are not allowed.

Examples:

// Swap between 6-decimal stablecoins
await kit.swap({
  from: { adapter, chain: 'Ethereum' },
  tokenIn: 'EURC',
  tokenOut: 'USDC',
  amountIn: '100.50',
  config: { apiKey: process.env.CIRCLE_API_KEY },
})

// Swap DAI (18 decimals) to USDC
await kit.swap({
  from: { adapter, chain: 'Ethereum' },
  tokenIn: 'DAI',
  tokenOut: 'USDC',
  amountIn: '500.0', // Automatically handles 18-decimal precision
  config: { apiKey: process.env.CIRCLE_API_KEY },
})

// Swap native gas token to stablecoin (generic)
await kit.swap({
  from: { adapter, chain: 'Ethereum' },
  tokenIn: 'NATIVE', // ETH on Ethereum, POL on Polygon, SOL on Solana, etc.
  tokenOut: 'USDC',
  amountIn: '1.5',
  config: { apiKey: process.env.CIRCLE_API_KEY },
})

// Swap wrapped ETH to stablecoin on Polygon
await kit.swap({
  from: { adapter, chain: 'Polygon' },
  tokenIn: 'WETH', // Wrapped ETH on Polygon
  tokenOut: 'USDC',
  amountIn: '0.5',
  config: { apiKey: process.env.CIRCLE_API_KEY },
})

Note: Use NATIVE for the chain's native gas token. Chain-specific symbols like ETH, POL are not supported as swap token aliases — use NATIVE or contract addresses instead.

Type Definitions

SwapParams

interface SwapParams {
  from: AdapterContext // Source adapter and chain
  tokenIn: SupportedToken // Input token
  tokenOut: SupportedToken // Output token
  amountIn: string // Decimal string (e.g., '10.5')
  config?: SwapConfig // Optional configuration
}

// SupportedToken can be:
// - Stablecoin aliases (6 decimals): 'USDC' | 'EURC' | 'USDT' | 'PYUSD'
// - Stablecoin aliases (18 decimals): 'DAI' | 'USDE'
// - Wrapped tokens: 'WBTC' (8 dec) | 'WETH' | 'WSOL' (9 dec) | 'WAVAX' | 'WPOL' (18 dec)
// - Native token: 'NATIVE' (chain's native gas token)
type SupportedToken =
  | 'USDC'
  | 'EURC'
  | 'USDT'
  | 'USDE'
  | 'DAI'
  | 'PYUSD'
  | 'WBTC'
  | 'WETH'
  | 'WSOL'
  | 'WAVAX'
  | 'WPOL'
  | 'NATIVE'

SwapEstimate

The estimate result includes input context fields for correlating estimates with inputs:

interface SwapEstimate {
  // Input context (populated from your params)
  tokenIn: SupportedToken // e.g., 'NATIVE'
  tokenOut: SupportedToken // e.g., 'USDC'
  amountIn: string // e.g., '0.00001'
  chain: string // e.g., 'Ethereum'
  fromAddress: string // e.g., '0x2971...5EE9f'
  toAddress: string // e.g., '0x2971...5EE9f'

  // Estimate details
  transaction: object // Raw transaction to sign and submit
  stopLimit: string // Minimum output in base units
  estimatedOutput?: string // Human-readable expected output
  fees?: ServiceSwapFee[] // Fee breakdown
}

SwapResult

The swap result uses a simplified chain field:

interface SwapResult {
  tokenIn: SupportedToken
  tokenOut: SupportedToken
  chain: string // e.g., 'Ethereum'
  amountIn: string // Human-readable amount
  fromAddress: string
  toAddress: string
  txHash: string
  explorerUrl?: string
  fees?: ServiceSwapFee[]
  config?: SwapResultConfig
}

Resolving Chain Name to ChainDefinition

Both SwapEstimate and SwapResult return a simplified chain string (e.g., 'Ethereum') If you need the full chain definition, use the getChainByEnum utility:

import { getChainByEnum } from '@circle-fin/swap-kit'

// After getting a swap result or estimate
const result = await kit.swap(params)

// Resolve the chain name back to full ChainDefinition
const chainDef = getChainByEnum(result.chain)
console.log(chainDef.chainId) // 1 (for Ethereum)
console.log(chainDef.rpcEndpoints) // ['https://...']

CustomFeePolicy

interface CustomFeePolicy {
  computeFee: (params: SwapParams) => Promise<string> | string
  resolveFeeRecipientAddress: (
    chain: ChainDefinition,
    params: SwapParams,
  ) => Promise<string> | string
}

Validation

SwapKit provides comprehensive runtime validation:

import { assertSwapParams, swapParamsSchema } from '@circle-fin/swap-kit'

try {
  assertSwapParams(params, swapParamsSchema)
  // Parameters are valid
} catch (error) {
  console.error('Validation failed:', error.message)
}

Usage Patterns: Class vs Functional

SwapKit supports both class-based and functional programming styles. Choose based on your preferences:

Use Class-Based (SwapKit) When:

  • ✅ You prefer traditional class-based patterns
  • ✅ Your codebase already uses class-based libraries
  • ✅ You want a familiar API similar to other SDKs
  • ✅ You don't need aggressive tree-shaking optimizations

Use Functional (createSwapKitContext + operations) When:

  • ✅ You prefer functional programming patterns
  • ✅ You need maximum tree-shaking for smaller bundles
  • ✅ You want to import only specific operations
  • ✅ You're building a performance-critical application

Both approaches:

  • ✅ Provide identical functionality
  • ✅ Use the same underlying operations
  • ✅ Offer full TypeScript support
  • ✅ Include comprehensive validation

Example: Choosing an approach

// Class-based: Great for general use
import { SwapKit } from '@circle-fin/swap-kit'
const kit = new SwapKit()
await kit.swap(params)

// Functional: Great for tree-shaking
import { createSwapKitContext, swap } from '@circle-fin/swap-kit'
const context = createSwapKitContext()
await swap(context, params)

License

Apache-2.0

Support

For issues and questions, please visit the GitHub repository.

版本与发布记录

@circle-fin/swap-kit 共发布 26 个版本,首次发布于 2026/03/18;过去 12 个月发布了 26 个版本。

版本发布日期距今
1.9.1latest2026/11/063 天前
1.9.02026/10/3110 天前
1.8.22026/10/2317 天前
1.8.12026/10/2119 天前
1.8.02026/10/1624 天前
1.7.12026/09/301 个月前

关于 @circle-fin/swap-kit 的常见问题

@circle-fin/swap-kit 是什么?

A Circle SDK for single-chain token swaps with minimal code

如何安装 @circle-fin/swap-kit?

在项目目录运行 npm install @circle-fin/swap-kit,或使用 pnpm add / yarn add / bun add。

@circle-fin/swap-kit 支持 TypeScript 吗?

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

@circle-fin/swap-kit 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@circle-fin/swap-kit 需要什么版本的 Node.js?

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

@circle-fin/swap-kit 可以商用吗?

@circle-fin/swap-kit 使用 未声明 许可。package.json 没有声明许可证。没有许可证的代码默认保留全部权利,商用前请联系作者或查看仓库中的 LICENSE 文件。以上为概括,不构成法律意见,请以许可原文为准。

@circle-fin/swap-kit 的下载量有多少?

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

@circle-fin/swap-kit 还在维护吗?

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