pumpfun-rs Rust SDK

repository·master·Indexed 41 days ago

https://github.com/nhuxhr/pumpfun-rs

A Rust SDK (v4.6.0) for interacting with the Pump.fun Solana program. It allows developers to programmatically create tokens, manage buy/sell trades, and monitor real-time on-chain events via WebSockets. The library provides high-level abstractions for PDA management, Associated Token Account (ATA) handling, and bonding curve calculations, including market cap and buyout price utilities.

Tokens
15.3K
Snippets
46
Records
59
Agent score
50%

What's inside pumpfun-rs

  1. Understand the pumpfun SDK architecture

    master

    The SDK is modularized to separate concerns:

    • accounts: Contains structs for deserializing on-chain state (e.g., BondingCurveAccount).
    • common: Utility functions and types, including the stream module for WebSockets.
    • constants: Program-specific constants like seeds and public keys.
    • error: Custom error types for robust error handling.
    • instructions: Builders for constructing transaction instructions.
    • utils: General helper functions.

    The PumpFun struct acts as a high-level facade, managing the complexities of Program Derived Addresses (PDAs), transaction construction/signing, IPFS metadata uploads, and priority fee configurations.

  2. Set up local development with the test validator

    master

    The repository includes a script to download and configure a Solana test validator pre-loaded with the Pump.fun program and dependencies.

    1. Navigate to the scripts directory: cd <path-to-pumpfun-rs-repo>/scripts
    2. Run the validator: ./pumpfun-test-validator.sh
    3. For verbose output: ./pumpfun-test-validator.sh --log
    cd <path-to-pumpfun-rs-repo>/scripts
    ./pumpfun-test-validator.sh
  3. Set up a local development environment

    master

    The SDK includes a test validator script that automatically downloads and configures a Solana test validator with the Pump.fun program and required dependencies.

    To use it:

    1. Navigate to the scripts directory in the repository.
    2. Run the ./pumpfun-test-validator.sh script.
    3. Use the --log flag if you need to see detailed logs.
    # Navigate to the scripts directory
    cd <path-to-pumpfun-rs-repo>/scripts
    
    # Run the test validator
    ./pumpfun-test-validator.sh
    
    # Or with custom options
    ./pumpfun-test-validator.sh --log
  4. Understand the BondingCurveAccount structure

    master

    The BondingCurveAccount is the core data structure used by the Pump.fun Solana Program to manage token pricing and liquidity. It tracks both virtual reserves (used for mathematical price calculations) and real reserves (the actual assets available for trading).

    Fields:

    • discriminator: u64 unique identifier for the bonding curve.
    • virtual_token_reserves: u64 virtual token reserves for price calculations.
    • virtual_sol_reserves: u64 virtual SOL reserves for price calculations.
    • real_token_reserves: u64 actual token reserves available for trading.
    • real_sol_reserves: u64 actual SOL reserves available for trading.
    • token_total_supply: u64 total supply of tokens.
    • complete: bool indicates if the bonding curve is finalized.
    • creator: Pubkey the address of the token creator.
  5. Understand the GlobalAccount structure

    master
    The GlobalAccount represents the global configuration state of the Pump.fun Solana Program. It manages critical parameters for token pricing, fee distribution, and pool migration settings. Developers interacting with the program's state will use this structure to understand current fee rates, reserve levels, and authority permissions.
  6. PumpFunEvent enum types

    master

    The PumpFunEvent enum is the central type for all parsed on-chain events. It includes:

    • Create(CreateEvent): Emitted when a new token is created.
    • Trade(TradeEvent): Emitted when a token is bought or sold.
    • Complete(CompleteEvent): Emitted when a bonding curve operation completes.
    • SetParams(SetParamsEvent): Emitted when global program parameters are updated.
    • Unhandled(String, Vec<u8>): Contains the signature and raw bytes for known but unhandled event discriminators.
    • Unknown(String, Vec<u8>): Contains the signature and raw bytes for unrecognized discriminators.
  7. Configure pumpfun feature flags

    master

    You can customize the SDK behavior in your Cargo.toml using feature flags.

    FeatureDefaultDescription
    create-ataEnabledAutomatically creates ATAs during purchases. Disable to manage manually.
    close-ataEnabledAutomatically closes unused ATAs after selling to reclaim rent.
    versioned-txDisabledEnables support for Versioned Transactions and Address Lookup Tables (ALTs).
    streamDisabledEnables WebSocket-based real-time event subscriptions.

    Cargo.toml Examples:

    Use default features (create-ata and close-ata enabled):

    pumpfun = "4.6.0"

    Disable all default features:

    pumpfun = { version = "4.6.0", default-features = false }

    Enable specific features (e.g., Versioned Transactions):

    pumpfun = { version = "4.6.0", default-features = false, features = ["versioned-tx"] }

    Enable real-time streaming:

    pumpfun = { version = "4.6.0", features = ["stream"] }
  8. Initialize the PumpFun client

    master

    To interact with the Pump.fun program, create a new PumpFun client instance. This requires an Arc<Keypair> for the payer and a Cluster configuration which defines the RPC endpoint, commitment level, and default priority fees.

    use pumpfun::{PumpFun, common::types::{Cluster, PriorityFee}};
    use solana_sdk::{commitment_config::CommitmentConfig, signature::Keypair};
    use std::sync::Arc;
    
    // Create a new client connected to devnet
    let payer = Arc::new(Keypair::new());
    let commitment = CommitmentConfig::confirmed();
    let priority_fee = PriorityFee::default();
    let cluster = Cluster::devnet(commitment, priority_fee);
    let client = PumpFun::new(payer, cluster);
    use pumpfun::{PumpFun, common::types::{Cluster, PriorityFee}};
    use solana_sdk::{commitment_config::CommitmentConfig, signature::Keypair};
    use std::sync::Arc;
    
    let payer = Arc::new(Keypair::new());
    let commitment = CommitmentConfig::confirmed();
    let priority_fee = PriorityFee::default();
    let cluster = Cluster::devnet(commitment, priority_fee);
    let client = PumpFun::new(payer, cluster);
  9. Create a new token with metadata

    master

    Use client.create() to launch a new token. You must provide a mint Keypair, a CreateTokenMetadata struct containing the token's name, symbol, description, and image path, and an optional PriorityFee.

    use pumpfun::{utils::CreateTokenMetadata, PumpFun};
    
    let metadata = CreateTokenMetadata {
        name: "Lorem ipsum".to_string(),
        symbol: "LIP".to_string(),
        description: "Lorem ipsum dolor, sit amet..." .to_string(),
        file: "/path/to/image.png".to_string(),
        twitter: None,
        telegram: None,
        website: Some("https://example.com".to_string()),
    };
    
    // signature is returned upon success
    let signature = client.create(mint.insecure_clone(), metadata, fee).await.unwrap();
  10. Use the PumpFun client for token operations

    master

    The PumpFun struct is the primary entry point for interacting with the program. It abstracts complex tasks like PDA management, transaction signing, and ATA management.

    Key Capabilities:

    • Automatic ATA Management: The SDK automatically creates Associated Token Accounts (ATAs) during buy transactions by default.
    • Token Creation: Use create or create_and_buy with CreateTokenMetadata to launch new tokens.
    • Trading: Use buy and sell methods. sell includes slippage protection.
    • State Queries: Use get_bonding_curve_account to fetch the current state of a token's bonding curve.
    use pumpfun::{
        accounts::BondingCurveAccount,
        common::types::{Cluster, PriorityFee},
        utils::CreateTokenMetadata,
        PumpFun,
    };
    // ... imports for solana_sdk and std
    
    // Initialize client
    let payer = Arc::new(Keypair::new());
    let client = PumpFun::new(
        payer.clone(),
        Cluster::localnet(CommitmentConfig::finalized(), PriorityFee::default()),
    );
    
    // Example: Create a token
    let metadata = CreateTokenMetadata {
        name: "Token Name".to_string(),
        symbol: "TKN".to_string(),
        description: "Description".to_string(),
        file: "/path/to/image.png".to_string(),
        twitter: None,
        telegram: None,
        website: Some("https://example.com".to_string()),
    };
    let signature = client.create(mint_keypair, metadata, fee).await.unwrap();
    
    // Example: Buy tokens
    let signature = client.buy(mint_pubkey, sol_amount, track_volume, None, fee).await.unwrap();
    
    // Example: Sell tokens
    let signature = client.sell(mint_pubkey, None, None, fee).await.unwrap();