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 🙏

© 2025 – Pkg Stats / Ryan Hefner

pump-trader

v1.0.2

Published

PumpFun 交易库 - 自动判断 Token Program 和内盘/外盘

Downloads

335

Readme

PumpTrader 改进版本

📋 核心功能

✨ 新增功能

  1. 自动 Token Program 检测

    • 自动识别代币使用的是 TOKEN_PROGRAM_ID 还是 TOKEN_2022_PROGRAM_ID
    • 支持缓存机制,提高性能
    • 透明处理,无需手动指定
  2. 自动内盘/外盘判断

    • 自动检测代币是否完成内盘绑定曲线
    • 智能选择是否使用 bonding curveAMM 交易
    • 提供统一的 autoBuy()autoSell() 接口
  3. TypeScript 支持

    • 完整的类型定义 (index.ts)
    • 类型安全的接口
    • 更好的 IDE 自动完成
  4. JavaScript/CommonJS 兼容

    • 改进的 JavaScript 版本 (index.js)
    • 同时支持 ESM 和 CommonJS 导入

🚀 快速开始

基础设置

import { PumpTrader } from './index.js';

const RPC_URL = "https://api.mainnet-beta.solana.com";
const PRIVATE_KEY = "your_base58_private_key_here";

const trader = new PumpTrader(RPC_URL, PRIVATE_KEY);

TypeScript 导入

import { PumpTrader, TradeOptions, TradeResult } from './index';

const trader = new PumpTrader(RPC_URL, PRIVATE_KEY);

🎯 核心 API

1. Token Program 检测

自动检测 Token Program

// 自动检测代币使用的 token program
const tokenProgram = await trader.detectTokenProgram(tokenAddr);

console.log(tokenProgram.type);       // "TOKEN_PROGRAM_ID" 或 "TOKEN_2022_PROGRAM_ID"
console.log(tokenProgram.programId);  // PublicKey

特点:

  • 自动缓存结果
  • 失败自动回退
  • 无需手动指定

2. 内盘/外盘检测

判断交易模式

// 返回 "bonding" 或 "amm"
const mode = await trader.getTradeMode(tokenAddr);

if (mode === "bonding") {
  console.log("代币还在内盘");
} else {
  console.log("代币已进入外盘");
}

检查是否完成内盘

const isCompleted = await trader.isAmmCompleted(tokenAddr);

3. 统一交易接口(推荐)

自动买入

const tradeOpt = {
  maxSolPerTx: BigInt(1_000_000_000),  // 1 SOL
  slippage: {
    base: 500,        // 5% 基础滑点
    min: 300,         // 最小 3%
    max: 1000,        // 最大 10%
    impactFactor: 1
  },
  priority: {
    base: 5000,       // microLamports
    enableRandom: true,
    randomRange: 5000
  }
};

// 自动判断内盘/外盘,自动选择合适的交易方式
const result = await trader.autoBuy(tokenAddr, BigInt(100_000_000), tradeOpt);

// 结果
console.log(result.pendingTransactions);  // 待确认的交易
console.log(result.failedTransactions);   // 失败的交易

自动卖出

// 自动判断内盘/外盘,自动卖出
const result = await trader.autoSell(tokenAddr, BigInt(1_000_000), tradeOpt);

🔧 进阶 API

内盘交易(手动方式)

// 内盘买入
const buyResult = await trader.buy(tokenAddr, solAmount, tradeOpt);

// 内盘卖出
const sellResult = await trader.sell(tokenAddr, tokenAmount, tradeOpt);

外盘交易(手动方式)

// 外盘买入
const buyResult = await trader.ammBuy(tokenAddr, solAmount, tradeOpt);

// 外盘卖出
const sellResult = await trader.ammSell(tokenAddr, tokenAmount, tradeOpt);

📊 查询接口

获取价格和状态

const { price, completed } = await trader.getPriceAndStatus(tokenAddr);

console.log(price);      // 当前价格 (SOL)
console.log(completed);  // 是否完成内盘

查询余额

查询单个代币余额

// 查询指定代币的余额
const balance = await trader.tokenBalance(tokenAddr);
console.log(balance);  // 返回数字,例如:123.45

查询所有代币余额

// 查询账户所有的代币(余额 > 0)
const allTokens = await trader.tokenBalance();

// 返回数组:[{ mint, amount, decimals, uiAmount }, ...]
allTokens.forEach((token) => {
  console.log(`${token.mint}: ${token.uiAmount}`);
});

使用专用方法

// 直接调用方法查询所有代币
const allBalances = await trader.getAllTokenBalances();

// SOL 余额
const solBalance = await trader.solBalance();

获取元数据

const metadata = await trader.fetchMeta(tokenAddr);

console.log(metadata?.name);
console.log(metadata?.symbol);
console.log(metadata?.uri);

📡 事件监听

监听交易事件

import { PublicKey } from '@solana/web3.js';

const tokenMint = new PublicKey(tokenAddr);

const unsubscribe = trader.listenTrades(
  (event) => {
    console.log("交易类型:", event.isBuy ? "买入" : "卖出");
    console.log("SOL 数量:", Number(event.solAmount) / 1e9);
    console.log("代币数量:", Number(event.tokenAmount) / 1e6);
    console.log("用户:", event.user);
    console.log("时间戳:", event.timestamp);
    console.log("交易哈希:", event.signature);
  },
  tokenMint  // 可选,指定监听特定代币
);

// 停止监听
unsubscribe();

✅ 交易确认

轮询确认交易

const result = await trader.confirmTransactionWithPolling(
  signature,              // 交易哈希
  lastValidBlockHeight,   // 最后有效块高
  5,                      // 最大尝试次数
  2000                    // 延迟 (毫秒)
);

console.log("交易已确认:", result);

💾 缓存管理

Token Program 缓存

// 获取缓存的 token program 信息
const cached = trader.getCachedTokenProgram(tokenAddr);

// 清除特定 Token 的缓存
trader.clearTokenProgramCache(tokenAddr);

// 清除所有缓存
trader.clearTokenProgramCache();

👛 钱包信息

获取钱包和连接

const wallet = trader.getWallet();
const connection = trader.getConnection();

console.log("公钥:", wallet.publicKey.toBase58());
console.log("RPC 端点:", connection.rpcEndpoint);

📝 TypeScript 类型

TradeOptions

interface TradeOptions {
  maxSolPerTx: bigint;
  slippage: {
    base: number;
    max?: number;
    min?: number;
    impactFactor?: number;
  };
  priority: {
    base: number;
    enableRandom?: boolean;
    randomRange?: number;
  };
}

TradeResult

interface TradeResult {
  pendingTransactions: PendingTransaction[];
  failedTransactions: FailedTransaction[];
}

interface PendingTransaction {
  signature: string;
  lastValidBlockHeight: number;
  index: number;
}

interface FailedTransaction {
  index: number;
  error: string;
}

TokenProgramType

interface TokenProgramType {
  type: "TOKEN_PROGRAM_ID" | "TOKEN_2022_PROGRAM_ID";
  programId: PublicKey;
}

🔍 使用示例

示例 1: 自动交易(推荐)

async function autoTrade() {
  const trader = new PumpTrader(RPC, PRIVATE_KEY);
  
  const tradeOpt = {
    maxSolPerTx: BigInt(1_000_000_000),
    slippage: { base: 500 },
    priority: { base: 5000 }
  };

  // 自动判断内盘/外盘,自动买入
  const result = await trader.autoBuy(tokenAddr, BigInt(100_000_000), tradeOpt);
  
  // 确认第一笔交易
  if (result.pendingTransactions.length > 0) {
    const tx = result.pendingTransactions[0];
    await trader.confirmTransactionWithPolling(tx.signature, tx.lastValidBlockHeight);
  }
}

示例 2: 批量操作

async function batchTrade() {
  const trader = new PumpTrader(RPC, PRIVATE_KEY);
  const tokens = ["addr1", "addr2", "addr3"];

  for (const tokenAddr of tokens) {
    try {
      // 检测内盘/外盘
      const mode = await trader.getTradeMode(tokenAddr);
      console.log(`${tokenAddr}: ${mode}`);
      
      // 自动买入
      const result = await trader.autoBuy(tokenAddr, BigInt(10_000_000), tradeOpt);
      console.log(`发送了 ${result.pendingTransactions.length} 笔交易`);
    } catch (error) {
      console.error(`${tokenAddr}: ${error.message}`);
    }
  }
}

示例 3: 监听和交易

async function listenAndTrade() {
  const trader = new PumpTrader(RPC, PRIVATE_KEY);
  const tokenMint = new PublicKey(tokenAddr);

  // 监听交易
  const unsubscribe = trader.listenTrades((event) => {
    if (event.isBuy) {
      console.log(`新买单: ${Number(event.solAmount) / 1e9} SOL`);
      // 可以根据交易事件触发自动交易
    }
  }, tokenMint);

  // 监听 60 秒
  setTimeout(() => unsubscribe(), 60000);
}

🛠️ 文件结构

pump_trader/
├── index.js              # 改进的 JavaScript 实现
├── index.ts              # TypeScript 类型定义和实现
├── examples.js           # JavaScript 使用示例
├── examples.ts           # TypeScript 使用示例
├── README.md             # 本文档
└── package.json          # 项目配置

📦 依赖项

{
  "@solana/web3.js": "^1.78.0",
  "@solana/spl-token": "^0.3.10",
  "bn.js": "^5.2.1",
  "bs58": "^5.0.0"
}

⚡ 性能优化

Token Program 缓存

// 首次调用:会调用 getMint()
const prog1 = await trader.detectTokenProgram(tokenAddr);  // 较慢

// 后续调用:使用缓存
const prog2 = await trader.detectTokenProgram(tokenAddr);  // 很快

批量操作建议

// ✅ 推荐:使用 autoBuy/autoSell
const result = await trader.autoBuy(tokenAddr, amount, tradeOpt);

// ❌ 不推荐:多次调用 buy/ammBuy
// 代码更复杂,需要手动判断内盘/外盘

🔐 安全建议

  1. 私钥管理

    • 使用环境变量存储私钥
    • 不要在代码中硬编码私钥
    • 使用专用的钱包管理库
  2. RPC 端点

    • 考虑使用专用 RPC 服务
    • 不要公开 RPC 端点
    • 对 RPC 请求设置速率限制
  3. 交易参数

    • 测试网上先验证逻辑
    • 正确设置滑点和优先级费用
    • 监控交易状态

🐛 常见问题

Q: Token Program 检测失败怎么办?

try {
  const prog = await trader.detectTokenProgram(tokenAddr);
} catch (error) {
  console.error("检测失败,可能是无效的代币地址");
  // 1. 检查代币地址是否正确
  // 2. 检查 RPC 连接
  // 3. 重试
}

Q: 如何禁用缓存?

// 每次都重新检测
const prog = await trader.detectTokenProgram(tokenAddr);
trader.clearTokenProgramCache(tokenAddr);  // 立即清除缓存

Q: 如何选择内盘还是外盘?

// 使用 autoBuy/autoSell 让库自动选择
const result = await trader.autoBuy(tokenAddr, amount, tradeOpt);

// 或者手动检查
const mode = await trader.getTradeMode(tokenAddr);
if (mode === "bonding") {
  // 手动调用内盘方法
} else {
  // 手动调用外盘方法
}