Skip to main content

Python SDK for interacting with Pump Swap AMM protocol on Solana

Project description

PumpSwap SDK Python

A complete Python SDK for interacting with the Pump Swap AMM protocol on Solana. This SDK provides both high-level and low-level interfaces for creating pools, performing swaps, managing liquidity, and collecting fees.

Features

  • 🔄 Token Swaps: Buy and sell tokens using constant product AMM formula
  • 💧 Liquidity Management: Add and remove liquidity from pools
  • 🏭 Pool Creation: Create new AMM pools with custom parameters
  • 💰 Fee Collection: Collect protocol and creator fees
  • 🎁 Token Incentives: Claim trading rewards and incentives
  • 📊 Real-time Data: Fetch live pool data and user balances
  • 🔧 Admin Functions: Protocol administration and configuration
  • Full Validation: Comprehensive input validation and error handling

Installation

pip install pumpswap-python-sdk

For development:

pip install pumpswap-python-sdk[dev]

Quick Start

Basic Usage

from pump_swap_sdk import PumpAmmSdk, OnlinePumpAmmSdk
from solana.rpc.api import Client
from solders.pubkey import Pubkey

# Initialize SDK with blockchain connection
connection = Client("https://api.mainnet-beta.solana.com")
sdk = OnlinePumpAmmSdk(connection=connection)

# Get pool state for swaps
pool_address = Pubkey.from_string("YOUR_POOL_ADDRESS")
user_address = Pubkey.from_string("YOUR_WALLET_ADDRESS")

swap_state = sdk.swap_solana_state(pool_address, user_address)

# Calculate swap amounts
result = sdk.buy_base_input(
    swap_state=swap_state,
    base=1_000_000,  # 1 token (6 decimals)
    slippage=100     # 1% slippage
)

print(f"Quote needed: {result.ui_quote}")
print(f"Max quote with slippage: {result.max_quote}")

Creating a Pool

from pump_swap_sdk import OnlinePumpAmmSdk
from solders.keypair import Keypair

# Initialize with your keypair
creator_keypair = Keypair.from_secret_key(your_secret_key)
sdk = OnlinePumpAmmSdk(connection=connection)

# Create pool state
create_state = sdk.create_pool_solana_state(
    index=0,
    creator=creator_keypair.pubkey(),
    base_mint=Pubkey.from_string("BASE_TOKEN_MINT"),
    quote_mint=Pubkey.from_string("QUOTE_TOKEN_MINT")
)

# Build creation instructions
instructions = sdk.create_pool_instructions(
    create_pool_state=create_state,
    base_in=1_000_000_000,    # Initial base tokens
    quote_in=1_000_000_000    # Initial quote tokens
)

Managing Liquidity

# Get liquidity state
liquidity_state = sdk.liquidity_solana_state(pool_address, user_address)

# Add liquidity with base token amount
deposit_result = sdk.deposit_base_input(
    liquidity_state=liquidity_state,
    base=1_000_000,  # Base token amount
    slippage=100     # 1% slippage
)

print(f"Quote needed: {deposit_result.quote}")
print(f"LP tokens to receive: {deposit_result.lp_token}")

# Remove liquidity
withdraw_result = sdk.withdraw_inputs(
    liquidity_state=liquidity_state,
    lp_amount=500_000,  # LP tokens to burn
    slippage=100        # 1% slippage
)

print(f"Base tokens to receive: {withdraw_result.base}")
print(f"Quote tokens to receive: {withdraw_result.quote}")

Advanced Usage

Offline SDK (No Blockchain Connection)

from pump_swap_sdk import PumpAmmSdk

# Use offline SDK for calculations without network calls
offline_sdk = PumpAmmSdk()

# You'll need to provide the state data manually
from pump_swap_sdk.types import SwapSolanaState, Pool, GlobalConfig

# Build state with your data
swap_state = SwapSolanaState(
    pool=your_pool_data,
    global_config=your_global_config,
    pool_base_amount=base_reserve,
    pool_quote_amount=quote_reserve,
    # ... other required fields
)

# Perform calculations
result = offline_sdk.buy_base_input(swap_state, 1_000_000, 100)

Fee Calculations

from pump_swap_sdk.sdk.fees import compute_fees_bps

# Calculate current fee rates
fees = compute_fees_bps(
    global_config=global_config,
    fee_config=fee_config,
    market_cap=current_market_cap
)

print(f"LP Fee: {fees.lp_fee_bps} bps")
print(f"Protocol Fee: {fees.protocol_fee_bps} bps")
print(f"Creator Fee: {fees.creator_fee_bps} bps")
print(f"Total Fee: {fees.total_fee_bps} bps")

Token Incentives

# Check unclaimed rewards
unclaimed = sdk.get_total_unclaimed_tokens(user_address)
print(f"Unclaimed tokens: {unclaimed}")

# Check today's earned rewards
today_rewards = sdk.get_current_day_tokens(user_address)
print(f"Today's rewards: {today_rewards}")

SDK Architecture

Core Classes

  • PumpAmmSdk: High-level offline SDK for calculations
  • OnlinePumpAmmSdk: Online SDK with blockchain connectivity
  • PumpAmmAdminSdk: Admin SDK for protocol management

Key Modules

  • swap_operations: Buy/sell token calculations
  • liquidity_operations: Deposit/withdraw liquidity calculations
  • fees: Fee calculation utilities
  • token_incentives: Trading reward calculations
  • pda: Program Derived Address utilities
  • utils: Mathematical and utility functions

Mathematical Formulas

The SDK implements a constant product AMM using the formula x * y = k:

Swap Calculations

Buy tokens (base input):

quote_needed = ceil_div(quote_reserve * base_amount, base_reserve - base_amount)

Sell tokens (base input):

quote_received = floor_div(quote_reserve * base_amount, base_reserve + base_amount)

Liquidity Calculations

LP tokens for deposit:

lp_tokens = min(
    base_amount * total_lp_supply / base_reserve,
    quote_amount * total_lp_supply / quote_reserve
)

Tokens from LP withdrawal:

base_amount = lp_amount * base_reserve / total_lp_supply
quote_amount = lp_amount * quote_reserve / total_lp_supply

Error Handling

The SDK provides comprehensive error handling:

from pump_swap_sdk.exceptions import (
    InsufficientLiquidityError,
    SlippageExceededError,
    ValidationError
)

try:
    result = sdk.buy_base_input(swap_state, amount, slippage)
except InsufficientLiquidityError:
    print("Not enough liquidity for this trade")
except SlippageExceededError:
    print("Price moved beyond slippage tolerance")
except ValidationError as e:
    print(f"Invalid input: {e}")

Configuration

Environment Variables

# Solana RPC endpoint
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com

# Program ID (optional, defaults to mainnet)
PUMP_AMM_PROGRAM_ID=6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P

Custom Configuration

from pump_swap_sdk import OnlinePumpAmmSdk
from solders.pubkey import Pubkey

# Use custom program ID
custom_program_id = Pubkey.from_string("YOUR_PROGRAM_ID")
sdk = OnlinePumpAmmSdk(
    connection=connection,
    program_id=custom_program_id
)

Testing

Run the test suite:

# Install development dependencies
pip install -e .[dev]

# Run tests
pytest

# Run with coverage
pytest --cov=pump_swap_sdk --cov-report=html

# Run specific test categories
pytest -m unit        # Unit tests only
pytest -m integration # Integration tests only

Examples

Check out the examples/ directory for complete working examples:

  • basic_swap.py: Simple token swap
  • liquidity_management.py: Add/remove liquidity
  • pool_creation.py: Create a new AMM pool
  • fee_calculation.py: Calculate trading fees
  • admin_operations.py: Protocol administration

Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

# Clone the repository
git clone https://github.com/pump-fun/pump-swap-sdk-python.git
cd pump-swap-sdk-python

# Create virtual environment
python -m venv venv
source venv/bin/activate  # Linux/Mac
# or
venv\\Scripts\\activate  # Windows

# Install in development mode
pip install -e .[dev]

# Install pre-commit hooks
pre-commit install

# Run tests
pytest

Documentation

Support

License

This project is licensed under the MIT License - see the LICENSE file for details.

Related Projects


Built with ❤️ by the Pump.fun team

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pumpswap_python_sdk-1.0.0.tar.gz (39.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pumpswap_python_sdk-1.0.0-py3-none-any.whl (30.7 kB view details)

Uploaded Python 3

File details

Details for the file pumpswap_python_sdk-1.0.0.tar.gz.

File metadata

  • Download URL: pumpswap_python_sdk-1.0.0.tar.gz
  • Upload date:
  • Size: 39.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.2

File hashes

Hashes for pumpswap_python_sdk-1.0.0.tar.gz
Algorithm Hash digest
SHA256 7f103a9a65261cee636ca1b8e1dbaf40d9a3e360eb3b46d9dc807d969434c360
MD5 179fdb24a27c3597e44806e22c7a792e
BLAKE2b-256 8f42bff5541937149dc36b74c30ccf154d5a5eb2789b0940d5f875c02a69fe95

See more details on using hashes here.

File details

Details for the file pumpswap_python_sdk-1.0.0-py3-none-any.whl.

File metadata

File hashes

Hashes for pumpswap_python_sdk-1.0.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1ce52c606a8f0c8897c715af8c0d5c6a18666fbe282cafab2edec3720966882a
MD5 9edff356c954395454feafdda08ed090
BLAKE2b-256 130ff3c81afc08069926b47701cb84506ab43fb0c87ead350d6a8d2369b795e9

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page