pumpdotfun-sdk

repository·main·Indexed 21 days ago

https://github.com/rckprtr/pumpdotfun-sdk

A TypeScript library for interacting with the Pump.fun decentralized application on the Solana blockchain. The SDK enables developers to programmatically create tokens, buy and sell tokens via bonding curves, and subscribe to real-time protocol events such as createEvent, tradeEvent, and completeEvent. It includes the PumpDotFunSDK class for token lifecycle management, AMM and BondingCurveAccount classes for price and market cap calculations, and utilities for parsing raw program events and global account data.

Tokens
9K
Snippets
36
Records
42
Agent score
74%

What's inside pumpdotfun-sdk

  1. Pump.fun Data Structures

    main

    The program uses several key data structures for state management:

    global

    Stores the program-wide configuration:

    • initialized: bool
    • authority: pubkey
    • feeRecipient: pubkey
    • initialVirtualTokenReserves: u64
    • initialVirtualSolReserves: u64
    • initialRealTokenReserves: u64
    • tokenTotalSupply: u64
    • feeBasisPoints: u64

    bondingCurve

    Stores the state for an individual token's bonding curve:

    • virtualTokenReserves: u64
    • virtualSolReserves: u64
    • realTokenReserves: u64
    • realSolReserves: u64
    • tokenTotalSupply: u64
    • complete: bool
  2. Understand PumpFun event data structures

    main

    The SDK uses several event types to describe lifecycle changes on Pump.fun. These are aggregated in the PumpFunEventHandlers interface. Key event types include:

    • CreateEvent: Emitted when a new token is created. Contains mint, bondingCurve, and user addresses.
    • TradeEvent: Emitted on buys/sells. Includes solAmount, tokenAmount, and reserve states (virtualSolReserves, virtualTokenReserves, realSolReserves, realTokenReserves).
    • CompleteEvent: Emitted when a bonding curve is completed.
    • SetParamsEvent: Emitted when parameters like feeBasisPoints or tokenTotalSupply are set.
    export type CreateEvent = {
      name: string;
      symbol: string;
      uri: string;
      mint: PublicKey;
      bondingCurve: PublicKey;
      user: PublicKey;
    };
    
    export type TradeEvent = {
      mint: PublicKey;
      solAmount: bigint;
      tokenAmount: bigint;
      isBuy: boolean;
      user: PublicKey;
      timestamp: number;
      virtualSolReserves: bigint;
      virtualTokenReserves: bigint;
      realSolReserves: bigint;
      realTokenReserves: bigint;
    };
    
    export type CompleteEvent = {
      user: PublicKey;
      mint: PublicKey;
      bondingCurve: PublicKey;
      timestamp: number;
    };
    
    export type SetParamsEvent = {
      feeRecipient: PublicKey;
      initialVirtualTokenReserves: bigint;
      initialVirtualSolReserves: bigint;
      initialRealTokenReserves: bigint;
      tokenTotalSupply: bigint;
      feeBasisPoints: bigint;
    };
  3. Initialize the PumpFunSDK

    main

    To use the SDK, instantiate the PumpFunSDK class by passing an Anchor Provider. The SDK will automatically initialize the underlying program using the internal IDL and set up the connection via the provider.

    import { PumpFunSDK } from "pumpdotfun-sdk";
    import { AnchorProvider, Connection, Keypair } from "@solana/web3.js";
    
    const connection = new Connection("https://api.mainnet-beta.solana.com");
    const wallet = Keypair.generate(); // Use your actual wallet
    const provider = new AnchorProvider(connection, wallet as any, {});
    
    const sdk = new PumpFunSDK(provider);
  4. Run the basic token lifecycle example

    main

    To run the full lifecycle example (creating, buying, and selling tokens), follow these steps:

    1. Configure Environment: Create a .env file and set your HELIUS_RPC_URL.
    2. Fund Account: Ensure you have an account with at least 0.004 SOL.
    3. Execute: Run the following command:
    npx ts-node example/basic/index.ts
  5. Create, buy, and sell tokens with PumpDotFunSDK

    main

    The PumpDotFunSDK class provides high-level methods for token lifecycle management on Pump.fun.

    Core Methods

    createAndBuy

    Creates a new token and immediately executes a buy transaction.

    Signature:

    async createAndBuy(
      creator: Keypair,
      mint: Keypair,
      createTokenMetadata: CreateTokenMetadata,
      buyAmountSol: bigint,
      slippageBasisPoints: bigint = 500n,
      priorityFees?: PriorityFee,
      commitment: Commitment = DEFAULT_COMMITMENT,
      finality: Finality = DEFAULT_FINALITY
    ): Promise<TransactionResult>

    buy

    Buys a specified amount of tokens using SOL.

    Signature:

    async buy(
      buyer: Keypair,
      mint: PublicKey,
      buyAmountSol: bigint,
      slippageBasisPoints: bigint = 500n,
      priorityFees?: PriorityFee,
      commitment: Commitment = DEFAULT_COMMITMENT,
      finality: Finality = DEFAULT_FINALITY
    ): Promise<TransactionResult>

    sell

    Sells a specified amount of tokens.

    Signature:

    async sell(
      seller: Keypair,
      mint: PublicKey,
      sellTokenAmount: bigint,
      slippageBasisPoints: bigint = 500n,
      priorityFees?: PriorityFee,
      commitment: Commitment = DEFAULT_COMMITMENT,
      finality: Finality = DEFAULT_FINALITY
    ): Promise<TransactionResult>
  6. Subscribe to Pump.fun events

    main

    The SDK allows you to listen to real-time protocol events using addEventListener. You can subscribe to specific event types and provide a callback function that receives the event data, the slot, and the transaction signature.

    Event Types

    Supported event types include:

    • createEvent
    • tradeEvent
    • completeEvent

    Managing Listeners

    • Use addEventListener to start listening. It returns a numeric eventId.
    • Use removeEventListener(eventId: number) to stop listening to a specific event.
    const createEventId = sdk.addEventListener("createEvent", (event, slot, signature) => {
      console.log("createEvent", event, slot, signature);
    });
    
    // To stop listening:
    sdk.removeEventListener(createEventId);
  7. Pump.fun Program Instructions

    main

    The Pump.fun program exposes several instructions for managing the lifecycle of tokens and bonding curves.

    • create: Creates a new coin and its associated bonding curve. Requires name, symbol, uri, and creator (pubkey).
    • buy: Buys tokens from a bonding curve. Requires amount (u64) and maxSolCost (u64) to handle slippage.
    • sell: Sells tokens back into a bonding curve. Requires amount (u64) and minSolOutput (u64) to handle slippage.
    • withdraw: Allows an admin to withdraw liquidity for migration once a bonding curve is complete.
    • initialize: Creates the global state.
    • setParams: Sets the global state parameters (e.g., fee recipient, reserves, and fee basis points).
  8. Listen to PumpFun program events

    main

    The SDK provides an addEventListener method to subscribe to real-time on-chain events emitted by the PumpFun program. Supported event types are:

    • createEvent
    • tradeEvent
    • completeEvent
    • setParamsEvent

    Usage: Pass the event type and a callback function that receives the processed event, the slot, and the transaction signature.

    sdk.addEventListener("tradeEvent", (event, slot, signature) => {
      console.log(`Trade detected at slot ${slot}:`, event);
      console.log(`Signature: ${signature}`);
    });
    
    // To stop listening:
    // const eventId = sdk.addEventListener(...);
    // sdk.removeEventListener(eventId);
  9. Transform raw Pump.fun events into typed objects

    main

    The src/events.ts module provides utility functions to transform raw program event data into structured, typed objects. These functions convert string-based addresses into @solana/web3.js PublicKey instances and convert numeric strings or raw values into BigInt or Number types. This is useful when processing logs from a Solana RPC or websocket to ensure data types are correct for your application logic.

    import { toCreateEvent, toTradeEvent } from 'pumpdotfun-sdk';
    
    // Example: Transforming a raw CreateEvent
    const rawCreateEvent = {
      name: "Token Name",
      symbol: "TKN",
      uri: "https://uri.com",
      mint: "Address1...",
      bondingCurve: "Address2...",
      user: "Address3..."
    };
    
    const event = toCreateEvent(rawCreateEvent);
    // event.mint is now a PublicKey object
  10. Import the PumpDotFunSDK entrypoint

    main

    The pumpdotfun-sdk package exports its core functionality through a single entrypoint. You can access the main SDK class, utility functions, type definitions, event handlers, and account-specific logic by importing from the root package. The primary interface for interacting with the protocol is the PumpDotFunSDK class (exported from ./pumpfun.js).

    import { PumpDotFunSDK, ... } from 'pumpdotfun-sdk';