npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

changenow-sdk

v1.0.8

Published

ChangeNOW API SDK for Node.js and browser

Downloads

26

Readme

ChangeNOW SDK

npm version TypeScript License: MIT

ChangeNOW SDK 是一个用于与 ChangeNOW API 交互的 TypeScript/JavaScript 库。提供简单易用的接口来进行加密货币交换操作。

功能特点

  • 🚀 完整的 TypeScript 支持 - 提供完整的类型定义
  • 🔄 自动重试机制 - 内置智能重试和错误处理
  • 🛡️ 错误处理 - 详细的错误分类和处理
  • 📦 零依赖 - 只依赖 axios(已内置)
  • 🎯 简单易用 - 直观的 API 设计
  • 🔗 完整的 API 覆盖 - 实现 ChangeNOW API V1 与主要 V2 端点
  • 🧰 丰富的工具函数 - 提供货币对检查、地址验证等实用工具

安装

npm install changenow-sdk

快速开始

基本用法

import { ChangeNOWSDK } from 'changenow-sdk';

// 初始化 SDK(不需要 API 密钥)
const sdk = new ChangeNOWSDK();

// 获取支持的货币列表
const currencies = await sdk.getAvailableCurrencies();
console.log('支持的货币:', currencies.length);

// 获取 BTC 到 ETH 的汇率
const rate = await sdk.getRate('btc', 'eth');
console.log(`BTC 到 ETH 汇率: 1 BTC = ${rate.rate} ETH`);

// 估算交易金额
const estimate = await sdk.estimateAmount('btc', 'eth', 1);
console.log(`1 BTC 可兑换约 ${estimate.estimatedAmount} ETH`);

创建交易

import { ChangeNOWSDK } from 'changenow-sdk';

const sdk = new ChangeNOWSDK();

// 创建交易
const transaction = await sdk.createTransaction({
  fromCurrency: 'btc',
  toCurrency: 'eth',
  amount: 1,
  address: '0x742d35Cc6634C0532925a3b8D8077cE3F7C4dD2', // 接收地址
  refundAddress: 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh', // 退款地址(可选)
  contactEmail: '[email protected]' // 联系邮箱(可选)
});

console.log('交易ID:', transaction.id);
console.log('支付地址:', transaction.payinAddress);
console.log('预计接收金额:', transaction.expectedReceiveAmount);

监控交易状态

import { ChangeNOWSDK } from 'changenow-sdk';

const sdk = new ChangeNOWSDK();

// 监控交易状态
const transactionId = 'your-transaction-id';

while (true) {
  const status = await sdk.getTransactionStatus(transactionId);

  console.log(`交易状态: ${status.status}`);

  if (status.status === 'finished') {
    console.log('交易完成!');
    console.log(`实际接收金额: ${status.amount}`);
    break;
  } else if (status.status === 'failed') {
    console.log('交易失败');
    break;
  }

  // 等待 30 秒后再次检查
  await new Promise(resolve => setTimeout(resolve, 30000));
}

高级用法

使用 API 密钥

方法1:环境变量(推荐)

  1. 创建 .env 文件:
cp .env.example .env
  1. 编辑 .env 文件,填入你的API密钥:
# v1 使用的公共/私有 API Key(传入到 x-api-key)
CHANGENOW_API_KEY=your_v1_api_key_here

# v2 使用的 API Key(传入到 X-CHANGENOW-API-KEY),如未配置则回退使用 CHANGENOW_API_KEY
CHANGENOW_API_KEY_V2=your_v2_api_key_here
  1. 在代码中使用:
import { ChangeNOWSDK } from 'changenow-sdk';

const sdk = new ChangeNOWSDK(); // 会自动读取环境变量 CHANGENOW_API_KEY 与 CHANGENOW_API_KEY_V2

方法2:直接传入API密钥

import { ChangeNOWSDK } from 'changenow-sdk';

const sdk = new ChangeNOWSDK('your-api-key-here');

自定义配置与多 Key 管理

import { ChangeNOWSDK, DEFAULT_RETRY_CONFIG } from 'changenow-sdk';

const customRetryConfig = {
  ...DEFAULT_RETRY_CONFIG,
  maxAttempts: 5,
  baseDelay: 2000
};

const sdk = new ChangeNOWSDK('your-v1-api-key', 'https://api.changenow.io/v1', customRetryConfig);

// 也可以在运行时分别设置 v1/v2 的 Key:
sdk.setV1ApiKey('your-v1-api-key'); // 作用于 x-api-key
sdk.setV2ApiKey('your-v2-api-key'); // 作用于 X-CHANGENOW-API-KEY
// 或一次性设置
sdk.setApiKeys({ v1: 'your-v1-api-key', v2: 'your-v2-api-key' });

直接使用 API 客户端

import { ChangeNOWAPI } from 'changenow-sdk';

const api = new ChangeNOWAPI('your-api-key');

// 获取货币信息
const btcInfo = await api.getCurrency('btc');
console.log(btcInfo);

// 获取最小交易金额
const minAmount = await api.getMinimalExchangeAmount('btc', 'eth');
console.log(`最小交易金额: ${minAmount.minAmount} ${minAmount.ticker}`);

API 参考

ChangeNOWSDK 类

构造函数

new ChangeNOWSDK(apiKey?: string, baseURL?: string, retryConfig?: RetryConfig)

方法

  • getAvailableCurrencies(): Promise<Currency[]> - 获取所有支持的货币
  • getCurrencyInfo(ticker: string): Promise<Currency | null> - 获取特定货币信息
  • getRate(from: string, to: string): Promise<ExchangeRate> - 获取汇率
  • getMinimumAmount(from: string, to: string): Promise<MinimalExchangeAmount> - 获取最小交易金额
  • getAmountRange(from: string, to: string): Promise<ExchangeRange> - 获取交易金额范围
  • estimateAmount(from: string, to: string, amount: number, flow?: 'standard' | 'fixed-rate'): Promise<EstimatedExchangeAmount> - 估算交易金额
  • createTransaction(params: CreateTransactionRequest): Promise<Transaction> - 创建交易
  • getTransactionStatus(transactionId: string): Promise<TransactionStatus> - 获取交易状态
  • getTransactionsStatus(transactionIds: string[]): Promise<TransactionStatus[]> - 批量获取交易状态

API V2 新功能

交易对和市场信息

  • getAvailablePairs(): Promise<CurrencyPair[]> - 获取所有可用的交易对
  • validateAddress(currency: string, address: string): Promise<AddressValidation> - 验证地址格式
  • getUserAddresses(): Promise<UserAddress[]> - 获取用户地址列表

费用和估算

  • getNetworkFee(currency: string, amount?: number): Promise<NetworkFee> - 获取预估网络手续费
  • getMarketEstimate(currency: string, fiatCurrency?: string): Promise<MarketEstimate> - 获取市场估算

交易历史

  • getExchangeHistory(params?: object): Promise<Exchange[]> - 获取交易历史

API V2 Exchange(新增)

  • getV2ExchangeCurrencies(params?): Promise<Currency[]> - 获取可用于 v2 交换的币种列表,可按 activeflowbuysell 过滤。
  • getV2AvailablePairs(params?): Promise<string[]> - 获取所有可用交易对(含网络维度),可按币种/网络/flow 过滤。
  • getV2MinimalAmount(params): Promise<MinimalExchangeAmount> - 获取指定 from/to 币种与网络的最小可交换金额(含 flow)。
  • getV2Range(params): Promise<ExchangeRange> - 获取指定 from/to 币种与网络的最小/最大可交换金额区间。
  • getV2EstimatedAmount(params): Promise<V2EstimatedExchangeAmount> - 获取 v2 估算金额(支持 direct/reverse、standard/fixed-rate、useRateId)。
  • getV2NetworkFee(params): Promise<V2NetworkFeeEstimate> - 获取 v2 交换的网络费估算(包含存入/取出/合计及可选折算信息)。
  • getV2ExchangeById(id): Promise<V2ExchangeById> - 按交易 ID 查询 v2 交换详情和状态。
  • getV2ExchangeActions(id): Promise<V2ExchangeActions> - 查询该笔 v2 交易是否可继续(push)或可退款(refund),及相关额度信息。
  • continueV2Exchange(request): Promise<{ result: boolean }> - 继续(push)一笔可继续的 v2 交易,可携带 amount/currency/network。
  • refundV2Exchange(request): Promise<{ result: boolean }> - 触发 v2 交易退款到退款地址或原地址。
  • createV2Exchange(request): Promise<Transaction> - 创建 v2 交易(支持网络、flow、direct/reverse、rateId 等参数)。
  • getV2Exchanges(params?): Promise<V2ExchangesList> - 查询合作方 v2 交易列表,支持分页、排序与状态过滤。
  • getV2MarketsEstimate(params): Promise<V2MarketsEstimate> - 获取市场估算(不含费用),用于快速参考的直/反向估算。

API V2 Fiat(新增)

  • createFiatTransaction(request): Promise<FiatTransaction> - 创建法币到加密货币的兑换订单,需提供法币金额、方向、收款地址及客户联系信息。
  • getFiatEstimate(params): Promise<FiatEstimate> - 获取法币通道的估算(支持 from/to 币种与网络、金额与通道类型)。
  • getFiatStatus(id): Promise<FiatStatus> - 查询法币订单健康/状态信息(通过 id)。
  • getFiatMarketMinMaxRange(fromTo): Promise<FiatMarketMinMaxRange> - 查询法币市场的最小/最大额度范围(如 eth-eth_eur)。
  • getFiatCurrenciesFiat(): Promise<FiatCurrenciesList> - 获取法币侧可用的法币列表(可用于入金)。
  • getFiatCurrenciesCrypto(): Promise<FiatCurrenciesList> - 获取法币侧可买的加密货币列表。

API V1 固定汇率功能(新增)

固定汇率市场信息

  • getFixedRateMarkets(): Promise<FixedRateMarket[]> - 获取固定汇率市场信息
  • estimateFixedRateAmount(sendAmount, fromCurrency, toCurrency): Promise<EstimatedFixedRateAmount> - 预估固定汇率金额
  • estimateFixedRateAmountReverse(sendAmount, fromCurrency, toCurrency): Promise<EstimatedFixedRateAmount> - 预估固定汇率反向金额
  • getFixedRateRange(fromCurrency, toCurrency): Promise<FixedRateRange> - 获取固定汇率范围

固定汇率交易

  • createFixedRateTransaction(params): Promise<Transaction> - 创建固定汇率交易
  • createReverseFixedRateTransaction(params): Promise<Transaction> - 创建反向固定汇率交易

API V1 私有功能(新增)

货币和交易对

  • getCurrencyTargets(ticker): Promise<string[]> - 获取特定货币的目标货币列表
  • getTransactionList(): Promise<TransactionListItem[]> - 获取交易列表(需要私有API密钥)

工具函数

import {
  POPULAR_CURRENCIES,
  isStableCoin,
  validateAddress,
  formatAmount,
  getTransactionStatusLabel,
  isTransactionComplete,
  isPairSupported,
  formatCurrencyPair,
  isValidAddressFormat,
  calculateTotalCost
} from 'changenow-sdk';

// 常用货币常量
console.log(POPULAR_CURRENCIES.BTC); // 'btc'

// 检查是否为稳定币
const currency = await sdk.getCurrencyInfo('usdt');
console.log(isStableCoin(currency)); // true

// 验证地址
console.log(validateAddress('btc', 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh')); // true

// 格式化金额
console.log(formatAmount(0.00012345, 6)); // '0.000123'

// 获取状态标签
console.log(getTransactionStatusLabel('finished')); // '已完成'

// 检查交易是否完成
const tx = await sdk.getTransactionStatus('tx-id');
console.log(isTransactionComplete(tx)); // true

// 检查交易对是否支持
const pairs = await sdk.getAvailablePairs();
console.log(isPairSupported(pairs, 'btc', 'eth')); // true

// 格式化货币对显示
const pair = { from: 'btc', to: 'eth' };
console.log(formatCurrencyPair(pair)); // 'btc → eth'

// 验证地址格式
console.log(isValidAddressFormat('bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh')); // true

// 计算总成本
const total = calculateTotalCost(1, 0.0001);
console.log(`总成本: ${total} BTC`); // 总成本: 1.0001 BTC

// 固定汇率相关工具函数
import {
  isFixedRateTransaction,
  formatFixedRateMarket,
  validateFixedRateParams,
  getFixedRateValidityTime,
  formatFixedRateValidityTime
} from 'changenow-sdk';

// 检查是否为固定汇率交易
const tx = { flow: 'fixed-rate', rateId: 'abc123' };
console.log(isFixedRateTransaction(tx)); // true

// 格式化固定汇率市场信息
const market = { from: 'btc', to: 'eth', rate: 0.05, minFrom: 0.001, maxFrom: 10 };
console.log(formatFixedRateMarket(market)); // "btc → eth: 汇率 0.05, 范围 0.001-10"

// 验证固定汇率参数
const params = { fromCurrency: 'btc', toCurrency: 'eth', amount: 1, rateId: 'abc123', address: 'addr' };
const validation = validateFixedRateParams(params);
console.log(validation.valid); // true

// 固定汇率有效期
const validUntil = new Date(Date.now() + 10 * 60 * 1000).toISOString();
console.log(formatFixedRateValidityTime(validUntil)); // "10分 0秒"

错误处理

SDK 提供了详细的错误分类:

import { ChangeNOWError, RateLimitError, NetworkError, ValidationError } from 'changenow-sdk';

try {
  await sdk.createTransaction(params);
} catch (error) {
  if (error instanceof RateLimitError) {
    console.log(`请求过于频繁,请在 ${error.retryAfter} 秒后重试`);
  } else if (error instanceof ValidationError) {
    console.log(`参数错误: ${error.message}`);
  } else if (error instanceof NetworkError) {
    console.log('网络连接错误,请检查网络');
  } else if (error instanceof ChangeNOWError) {
    console.log(`ChangeNOW API 错误: ${error.message}`);
  }
}

类型定义

所有类型都已导出,可用于类型检查:

import type {
  Currency,
  Transaction,
  CreateTransactionRequest,
  TransactionStatus
} from 'changenow-sdk';

interface MyTransaction extends Transaction {
  // 扩展交易类型
}

许可证

MIT License - 详见 LICENSE 文件

贡献

欢迎提交 Issue 和 Pull Request!

免责声明

本 SDK 是非官方的,仅供学习和研究使用。请确保遵守相关法律法规和 ChangeNOW 的服务条款。