solanab-jup-python-sdk


Namesolanab-jup-python-sdk JSON
Version 2.0.6 PyPI version JSON
download
home_pageNone
SummaryHigh-performance sync/async Python SDK for Jupiter Exchange APIs, powered by curl_cffi.
upload_time2025-07-23 10:34:30
maintainerNone
docs_urlNone
authorNone
requires_python>=3.9
licenseMIT
keywords jupiter sdk solana
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # **Jupiter Python SDK**

[![PyPI version](https://badge.fury.io/py/solanab-jup-python-sdk.svg)](https://badge.fury.io/py/solanab-jup-python-sdk)
[![Python](https://img.shields.io/pypi/pyversions/solanab-jup-python-sdk.svg)](https://pypi.org/project/solanab-jup-python-sdk/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A high-performance, async-first Python SDK for seamless interaction with the Jupiter Ultra API, powered by `curl_cffi` for maximum speed and flexibility.

With Ultra API, you don't need to manage or connect to any RPC endpoints, or deal with complex configurations. Everything from getting quotes to transaction execution happens directly through a powerful API.

Or as we like to say around here: **"RPCs are for NPCs."**

## **Table of Contents**

- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Configuration](#configuration)
- [API Reference](#api-reference)
- [Usage Examples](#usage-examples)
- [Best Practices](#best-practices)
- [Advanced Usage](#advanced-usage)
- [Error Handling](#error-handling)
- [Contributing](#contributing)
- [Resources](#resources)

## **Features**

- 🚀 **High Performance**: Built on `curl_cffi` for blazing-fast HTTP requests
- 🔄 **Async/Sync Support**: Both asynchronous and synchronous clients available
- 🛡️ **Token Safety**: Built-in shield API for token security warnings
- 💰 **Balance Checking**: Easy balance retrieval for any Solana address
- 🔧 **Advanced Configuration**: Support for proxies, custom DNS, and more
- 📦 **Type Safety**: Full type hints with Pydantic models
- 🎯 **Zero Configuration**: Works out of the box with minimal setup

## **Installation**

```bash
pip install solanab-jup-python-sdk
```

### Requirements

- Python 3.9 or higher
- A Solana wallet private key (for transaction signing)

## **Quick Start**

### Async Example

```python
import asyncio
from jup_python_sdk.clients.ultra_api_client import AsyncUltraApiClient
from jup_python_sdk.models.ultra_api.ultra_order_request_model import UltraOrderRequest

async def main():
    # Initialize the async client
    client = AsyncUltraApiClient()

    # Create a swap order
    order_request = UltraOrderRequest(
        input_mint="So11111111111111111111111111111111111111112",  # WSOL
        output_mint="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",  # USDC
        amount=10000000,  # 0.01 WSOL
        taker=await client.get_public_key(),
    )

    try:
        # Execute the swap
        response = await client.order_and_execute(order_request)
        print(f"Transaction: https://solscan.io/tx/{response['signature']}")
    finally:
        await client.close()

asyncio.run(main())
```

### Sync Example

```python
from jup_python_sdk.clients.ultra_api_client import UltraApiClient
from jup_python_sdk.models.ultra_api.ultra_order_request_model import UltraOrderRequest

# Initialize the sync client
client = UltraApiClient()

# Create and execute a swap
order_request = UltraOrderRequest(
    input_mint="So11111111111111111111111111111111111111112",  # WSOL
    output_mint="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",  # USDC
    amount=10000000,  # 0.01 WSOL
    taker=client.get_public_key(),
)

response = client.order_and_execute(order_request)
print(f"Transaction: https://solscan.io/tx/{response['signature']}")
client.close()
```

## **Configuration**

### Environment Variables

Set up your private key as an environment variable:

```bash
# Base58 format (standard Solana format)
export PRIVATE_KEY=your_base58_private_key_here

# OR as a uint8 array
export PRIVATE_KEY=[10,229,131,132,213,96,74,22,...]
```

### Client Configuration

```python
from jup_python_sdk.clients.ultra_api_client import AsyncUltraApiClient

# With API key (for enhanced access)
client = AsyncUltraApiClient(
    api_key="YOUR_API_KEY",  # Get from https://portal.jup.ag/onboard
    private_key_env_var="CUSTOM_PRIVATE_KEY"  # Custom env var name
)

# With custom client configuration
client = AsyncUltraApiClient(
    client_kwargs={
        "timeout": 30,  # 30 seconds timeout
        "impersonate": "chrome110",  # Browser impersonation
        "verify": True,  # SSL verification
    }
)
```

## **API Reference**

### UltraApiClient / AsyncUltraApiClient

The main client classes for interacting with the Jupiter Ultra API.

#### Methods

##### `order(request: UltraOrderRequest) -> dict`

Get a swap order from the Jupiter Ultra API.

**Parameters:**

- `request`: An `UltraOrderRequest` object containing:
  - `input_mint` (str): Input token mint address
  - `output_mint` (str): Output token mint address
  - `amount` (int): Amount in smallest unit (e.g., lamports for SOL)
  - `taker` (str, optional): Taker's public key
  - `referral_account` (str, optional): Referral account address
  - `referral_fee` (int, optional): Referral fee in basis points

**Returns:** Dict containing order details including `requestId` and `transaction`

##### `execute(request: UltraExecuteRequest) -> dict`

Execute a previously created order.

**Parameters:**

- `request`: An `UltraExecuteRequest` object containing:
  - `request_id` (str): The request ID from the order
  - `signed_transaction` (str): Base64-encoded signed transaction

**Returns:** Dict containing execution result including `signature` and `status`

##### `order_and_execute(request: UltraOrderRequest) -> dict`

Create and execute an order in a single call.

**Parameters:**

- `request`: Same as `order()` method

**Returns:** Dict containing execution result including `signature` and `status`

##### `balances(address: str) -> dict`

Get token balances for a Solana address.

**Parameters:**

- `address` (str): Solana public key address

**Returns:** Dict mapping token symbols to balance details:

```python
{
    "SOL": {
        "amount": "100000000",
        "uiAmount": 0.1,
        "slot": 123456,
        "isFrozen": False
    }
}
```

##### `shield(mints: list[str]) -> dict`

Check tokens for safety warnings.

**Parameters:**

- `mints` (list[str]): List of token mint addresses to check

**Returns:** Dict containing warnings for each mint:

```python
{
    "warnings": {
        "mint_address": [
            {
                "type": "warning_type",
                "message": "Warning description"
            }
        ]
    }
}
```

### Models

#### UltraOrderRequest

Pydantic model for creating swap orders.

```python
UltraOrderRequest(
    input_mint="So11111111111111111111111111111111111111112",
    output_mint="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
    amount=10000000,
    taker="your_public_key",
    referral_account="optional_referral_address",
    referral_fee=50  # 0.5% in basis points
)
```

#### UltraExecuteRequest

Pydantic model for executing orders.

```python
UltraExecuteRequest(
    request_id="order_request_id",
    signed_transaction="base64_encoded_signed_transaction"
)
```

## **Usage Examples**

### Check Token Balances

```python
import asyncio
from jup_python_sdk.clients.ultra_api_client import AsyncUltraApiClient

async def check_balances():
    client = AsyncUltraApiClient()

    # Get your wallet address
    address = await client.get_public_key()

    # Fetch balances
    balances = await client.balances(address)

    for token, details in balances.items():
        print(f"{token}: {details['uiAmount']} (frozen: {details['isFrozen']})")

    await client.close()

asyncio.run(check_balances())
```

### Check Token Safety

```python
import asyncio
from jup_python_sdk.clients.ultra_api_client import AsyncUltraApiClient

async def check_token_safety():
    client = AsyncUltraApiClient()

    # Popular tokens to check
    mints = [
        "So11111111111111111111111111111111111111112",  # WSOL
        "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",  # USDC
        "DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263",  # BONK
    ]

    shield_response = await client.shield(mints)

    for mint, warnings in shield_response.get("warnings", {}).items():
        if warnings:
            print(f"⚠️ {mint} has warnings:")
            for warning in warnings:
                print(f"  - {warning['type']}: {warning['message']}")
        else:
            print(f"✅ {mint} appears safe")

    await client.close()

asyncio.run(check_token_safety())
```

### Concurrent Operations

```python
import asyncio
from jup_python_sdk.clients.ultra_api_client import AsyncUltraApiClient

async def concurrent_operations():
    client = AsyncUltraApiClient()

    # Define multiple tokens to check
    tokens = [
        "So11111111111111111111111111111111111111112",
        "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
        "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB",
    ]

    # Create tasks for concurrent execution
    tasks = []
    for token in tokens:
        task = client.shield([token])
        tasks.append(task)

    # Execute all requests concurrently
    results = await asyncio.gather(*tasks)

    # Process results
    for token, result in zip(tokens, results):
        print(f"Token {token}: {result}")

    await client.close()

asyncio.run(concurrent_operations())
```

## **Best Practices**

### 1. Always Close Clients

```python
# Using try/finally
client = AsyncUltraApiClient()
try:
    # Your code here
    pass
finally:
    await client.close()

# Or using async context manager (if implemented)
async with AsyncUltraApiClient() as client:
    # Your code here
    pass
```

### 2. Error Handling

```python
try:
    response = await client.order_and_execute(order_request)

    if response.get("status") == "Failed":
        print(f"Transaction failed: {response.get('error')}")
    else:
        print(f"Success: {response['signature']}")

except Exception as e:
    print(f"Error occurred: {e}")
```

### 3. Rate Limiting

```python
import asyncio

# Use semaphore to limit concurrent requests
semaphore = asyncio.Semaphore(5)  # Max 5 concurrent requests

async def rate_limited_request(client, mint):
    async with semaphore:
        return await client.shield([mint])
```

### 4. Retry Logic

```python
import asyncio
from typing import Optional

async def retry_request(func, max_retries=3, delay=1.0):
    for attempt in range(max_retries):
        try:
            return await func()
        except Exception as e:
            if attempt == max_retries - 1:
                raise
            await asyncio.sleep(delay * (attempt + 1))
```

### 5. Token Amount Calculations

```python
# Always work with the smallest unit (lamports for SOL)
sol_amount = 0.01  # SOL
lamports = int(sol_amount * 10**9)  # Convert to lamports

# For other tokens, check their decimals
usdc_amount = 10.0  # USDC
usdc_smallest_unit = int(usdc_amount * 10**6)  # USDC has 6 decimals
```

## **Advanced Usage**

### Using Proxies

```python
# SOCKS5 proxy
proxies = {"https": "socks5://user:pass@host:port"}
client = AsyncUltraApiClient(client_kwargs={"proxies": proxies})

# HTTP proxy
proxies = {
    "http": "http://user:pass@proxy.example.com:8080",
    "https": "http://user:pass@proxy.example.com:8080",
}
client = AsyncUltraApiClient(client_kwargs={"proxies": proxies})
```

### Custom DNS Resolution

```python
# Force specific DNS resolution
client = AsyncUltraApiClient(
    client_kwargs={
        "resolve": ["api.jup.ag:443:1.2.3.4"],
        "dns_servers": ["1.1.1.1", "1.0.0.1"],
    }
)
```

### Custom Headers and Browser Impersonation

```python
# Default: Uses "realworld" - randomly selects browser based on market share
client = AsyncUltraApiClient()

# Specify a specific browser version
client = AsyncUltraApiClient(
    client_kwargs={
        "impersonate": "chrome124",  # Specific browser version
    }
)

# Use latest version of a browser
client = AsyncUltraApiClient(
    client_kwargs={
        "impersonate": "chrome",  # Latest Chrome
    }
)

# Custom headers with browser impersonation
client = AsyncUltraApiClient(
    client_kwargs={
        "impersonate": "safari",  # Latest Safari
        "headers": {
            "Accept-Language": "en-US,en;q=0.9",
        }
    }
)
```

**Note**: By default, the SDK uses `impersonate="realworld"` which randomly selects a browser version based on current market share. This helps avoid detection and provides better anonymity.

## **Error Handling**

The SDK may raise various exceptions:

### Common Exceptions

```python
try:
    response = await client.order_and_execute(order_request)
except ValueError as e:
    # Invalid private key format
    print(f"Configuration error: {e}")
except requests.HTTPError as e:
    # HTTP errors (4xx, 5xx)
    print(f"API error: {e}")
except Exception as e:
    # Other errors
    print(f"Unexpected error: {e}")
```

### Response Status Handling

```python
response = await client.order_and_execute(order_request)

if response.get("status") == "Failed":
    error_code = response.get("code")
    error_message = response.get("error")

    if error_code == "INSUFFICIENT_BALANCE":
        print("Not enough balance for the swap")
    elif error_code == "SLIPPAGE_EXCEEDED":
        print("Slippage tolerance exceeded")
    else:
        print(f"Transaction failed: {error_message}")
```

## **Contributing**

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

### Development Setup

```bash
# Clone the repository
git clone https://github.com/solanab/jup-python-sdk.git
cd jup-python-sdk

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

# Run tests
pytest

# Run linters
ruff check .
ruff format .
```

## **Resources**

- [Ultra API Documentation](https://dev.jup.ag/docs/ultra-api/)
- [Jupiter Portal](https://portal.jup.ag/onboard) - Get your API key
- [Discord Community](https://discord.gg/jup)
- [GitHub Repository](https://github.com/solanab/jup-python-sdk)

## **License**

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## **Disclaimer**

🚨 **This project is actively maintained.**
While we strive for stability, the SDK is under active development. We recommend staying updated with the latest releases. Important updates will be announced in the [Discord server](https://discord.gg/jup).

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "solanab-jup-python-sdk",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "jupiter, sdk, solana",
    "author": null,
    "author_email": "Fiji <charismoutafidis@gmail.com>, solanab <whiredj@gmail.com>",
    "download_url": "https://files.pythonhosted.org/packages/45/f8/8525f0894249aa274be38d26658d29e0787da8f0e2dcd919c429c468aefb/solanab_jup_python_sdk-2.0.6.tar.gz",
    "platform": null,
    "description": "# **Jupiter Python SDK**\n\n[![PyPI version](https://badge.fury.io/py/solanab-jup-python-sdk.svg)](https://badge.fury.io/py/solanab-jup-python-sdk)\n[![Python](https://img.shields.io/pypi/pyversions/solanab-jup-python-sdk.svg)](https://pypi.org/project/solanab-jup-python-sdk/)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\nA high-performance, async-first Python SDK for seamless interaction with the Jupiter Ultra API, powered by `curl_cffi` for maximum speed and flexibility.\n\nWith Ultra API, you don't need to manage or connect to any RPC endpoints, or deal with complex configurations. Everything from getting quotes to transaction execution happens directly through a powerful API.\n\nOr as we like to say around here: **\"RPCs are for NPCs.\"**\n\n## **Table of Contents**\n\n- [Features](#features)\n- [Installation](#installation)\n- [Quick Start](#quick-start)\n- [Configuration](#configuration)\n- [API Reference](#api-reference)\n- [Usage Examples](#usage-examples)\n- [Best Practices](#best-practices)\n- [Advanced Usage](#advanced-usage)\n- [Error Handling](#error-handling)\n- [Contributing](#contributing)\n- [Resources](#resources)\n\n## **Features**\n\n- \ud83d\ude80 **High Performance**: Built on `curl_cffi` for blazing-fast HTTP requests\n- \ud83d\udd04 **Async/Sync Support**: Both asynchronous and synchronous clients available\n- \ud83d\udee1\ufe0f **Token Safety**: Built-in shield API for token security warnings\n- \ud83d\udcb0 **Balance Checking**: Easy balance retrieval for any Solana address\n- \ud83d\udd27 **Advanced Configuration**: Support for proxies, custom DNS, and more\n- \ud83d\udce6 **Type Safety**: Full type hints with Pydantic models\n- \ud83c\udfaf **Zero Configuration**: Works out of the box with minimal setup\n\n## **Installation**\n\n```bash\npip install solanab-jup-python-sdk\n```\n\n### Requirements\n\n- Python 3.9 or higher\n- A Solana wallet private key (for transaction signing)\n\n## **Quick Start**\n\n### Async Example\n\n```python\nimport asyncio\nfrom jup_python_sdk.clients.ultra_api_client import AsyncUltraApiClient\nfrom jup_python_sdk.models.ultra_api.ultra_order_request_model import UltraOrderRequest\n\nasync def main():\n    # Initialize the async client\n    client = AsyncUltraApiClient()\n\n    # Create a swap order\n    order_request = UltraOrderRequest(\n        input_mint=\"So11111111111111111111111111111111111111112\",  # WSOL\n        output_mint=\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\",  # USDC\n        amount=10000000,  # 0.01 WSOL\n        taker=await client.get_public_key(),\n    )\n\n    try:\n        # Execute the swap\n        response = await client.order_and_execute(order_request)\n        print(f\"Transaction: https://solscan.io/tx/{response['signature']}\")\n    finally:\n        await client.close()\n\nasyncio.run(main())\n```\n\n### Sync Example\n\n```python\nfrom jup_python_sdk.clients.ultra_api_client import UltraApiClient\nfrom jup_python_sdk.models.ultra_api.ultra_order_request_model import UltraOrderRequest\n\n# Initialize the sync client\nclient = UltraApiClient()\n\n# Create and execute a swap\norder_request = UltraOrderRequest(\n    input_mint=\"So11111111111111111111111111111111111111112\",  # WSOL\n    output_mint=\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\",  # USDC\n    amount=10000000,  # 0.01 WSOL\n    taker=client.get_public_key(),\n)\n\nresponse = client.order_and_execute(order_request)\nprint(f\"Transaction: https://solscan.io/tx/{response['signature']}\")\nclient.close()\n```\n\n## **Configuration**\n\n### Environment Variables\n\nSet up your private key as an environment variable:\n\n```bash\n# Base58 format (standard Solana format)\nexport PRIVATE_KEY=your_base58_private_key_here\n\n# OR as a uint8 array\nexport PRIVATE_KEY=[10,229,131,132,213,96,74,22,...]\n```\n\n### Client Configuration\n\n```python\nfrom jup_python_sdk.clients.ultra_api_client import AsyncUltraApiClient\n\n# With API key (for enhanced access)\nclient = AsyncUltraApiClient(\n    api_key=\"YOUR_API_KEY\",  # Get from https://portal.jup.ag/onboard\n    private_key_env_var=\"CUSTOM_PRIVATE_KEY\"  # Custom env var name\n)\n\n# With custom client configuration\nclient = AsyncUltraApiClient(\n    client_kwargs={\n        \"timeout\": 30,  # 30 seconds timeout\n        \"impersonate\": \"chrome110\",  # Browser impersonation\n        \"verify\": True,  # SSL verification\n    }\n)\n```\n\n## **API Reference**\n\n### UltraApiClient / AsyncUltraApiClient\n\nThe main client classes for interacting with the Jupiter Ultra API.\n\n#### Methods\n\n##### `order(request: UltraOrderRequest) -> dict`\n\nGet a swap order from the Jupiter Ultra API.\n\n**Parameters:**\n\n- `request`: An `UltraOrderRequest` object containing:\n  - `input_mint` (str): Input token mint address\n  - `output_mint` (str): Output token mint address\n  - `amount` (int): Amount in smallest unit (e.g., lamports for SOL)\n  - `taker` (str, optional): Taker's public key\n  - `referral_account` (str, optional): Referral account address\n  - `referral_fee` (int, optional): Referral fee in basis points\n\n**Returns:** Dict containing order details including `requestId` and `transaction`\n\n##### `execute(request: UltraExecuteRequest) -> dict`\n\nExecute a previously created order.\n\n**Parameters:**\n\n- `request`: An `UltraExecuteRequest` object containing:\n  - `request_id` (str): The request ID from the order\n  - `signed_transaction` (str): Base64-encoded signed transaction\n\n**Returns:** Dict containing execution result including `signature` and `status`\n\n##### `order_and_execute(request: UltraOrderRequest) -> dict`\n\nCreate and execute an order in a single call.\n\n**Parameters:**\n\n- `request`: Same as `order()` method\n\n**Returns:** Dict containing execution result including `signature` and `status`\n\n##### `balances(address: str) -> dict`\n\nGet token balances for a Solana address.\n\n**Parameters:**\n\n- `address` (str): Solana public key address\n\n**Returns:** Dict mapping token symbols to balance details:\n\n```python\n{\n    \"SOL\": {\n        \"amount\": \"100000000\",\n        \"uiAmount\": 0.1,\n        \"slot\": 123456,\n        \"isFrozen\": False\n    }\n}\n```\n\n##### `shield(mints: list[str]) -> dict`\n\nCheck tokens for safety warnings.\n\n**Parameters:**\n\n- `mints` (list[str]): List of token mint addresses to check\n\n**Returns:** Dict containing warnings for each mint:\n\n```python\n{\n    \"warnings\": {\n        \"mint_address\": [\n            {\n                \"type\": \"warning_type\",\n                \"message\": \"Warning description\"\n            }\n        ]\n    }\n}\n```\n\n### Models\n\n#### UltraOrderRequest\n\nPydantic model for creating swap orders.\n\n```python\nUltraOrderRequest(\n    input_mint=\"So11111111111111111111111111111111111111112\",\n    output_mint=\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\",\n    amount=10000000,\n    taker=\"your_public_key\",\n    referral_account=\"optional_referral_address\",\n    referral_fee=50  # 0.5% in basis points\n)\n```\n\n#### UltraExecuteRequest\n\nPydantic model for executing orders.\n\n```python\nUltraExecuteRequest(\n    request_id=\"order_request_id\",\n    signed_transaction=\"base64_encoded_signed_transaction\"\n)\n```\n\n## **Usage Examples**\n\n### Check Token Balances\n\n```python\nimport asyncio\nfrom jup_python_sdk.clients.ultra_api_client import AsyncUltraApiClient\n\nasync def check_balances():\n    client = AsyncUltraApiClient()\n\n    # Get your wallet address\n    address = await client.get_public_key()\n\n    # Fetch balances\n    balances = await client.balances(address)\n\n    for token, details in balances.items():\n        print(f\"{token}: {details['uiAmount']} (frozen: {details['isFrozen']})\")\n\n    await client.close()\n\nasyncio.run(check_balances())\n```\n\n### Check Token Safety\n\n```python\nimport asyncio\nfrom jup_python_sdk.clients.ultra_api_client import AsyncUltraApiClient\n\nasync def check_token_safety():\n    client = AsyncUltraApiClient()\n\n    # Popular tokens to check\n    mints = [\n        \"So11111111111111111111111111111111111111112\",  # WSOL\n        \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\",  # USDC\n        \"DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263\",  # BONK\n    ]\n\n    shield_response = await client.shield(mints)\n\n    for mint, warnings in shield_response.get(\"warnings\", {}).items():\n        if warnings:\n            print(f\"\u26a0\ufe0f {mint} has warnings:\")\n            for warning in warnings:\n                print(f\"  - {warning['type']}: {warning['message']}\")\n        else:\n            print(f\"\u2705 {mint} appears safe\")\n\n    await client.close()\n\nasyncio.run(check_token_safety())\n```\n\n### Concurrent Operations\n\n```python\nimport asyncio\nfrom jup_python_sdk.clients.ultra_api_client import AsyncUltraApiClient\n\nasync def concurrent_operations():\n    client = AsyncUltraApiClient()\n\n    # Define multiple tokens to check\n    tokens = [\n        \"So11111111111111111111111111111111111111112\",\n        \"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\",\n        \"Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB\",\n    ]\n\n    # Create tasks for concurrent execution\n    tasks = []\n    for token in tokens:\n        task = client.shield([token])\n        tasks.append(task)\n\n    # Execute all requests concurrently\n    results = await asyncio.gather(*tasks)\n\n    # Process results\n    for token, result in zip(tokens, results):\n        print(f\"Token {token}: {result}\")\n\n    await client.close()\n\nasyncio.run(concurrent_operations())\n```\n\n## **Best Practices**\n\n### 1. Always Close Clients\n\n```python\n# Using try/finally\nclient = AsyncUltraApiClient()\ntry:\n    # Your code here\n    pass\nfinally:\n    await client.close()\n\n# Or using async context manager (if implemented)\nasync with AsyncUltraApiClient() as client:\n    # Your code here\n    pass\n```\n\n### 2. Error Handling\n\n```python\ntry:\n    response = await client.order_and_execute(order_request)\n\n    if response.get(\"status\") == \"Failed\":\n        print(f\"Transaction failed: {response.get('error')}\")\n    else:\n        print(f\"Success: {response['signature']}\")\n\nexcept Exception as e:\n    print(f\"Error occurred: {e}\")\n```\n\n### 3. Rate Limiting\n\n```python\nimport asyncio\n\n# Use semaphore to limit concurrent requests\nsemaphore = asyncio.Semaphore(5)  # Max 5 concurrent requests\n\nasync def rate_limited_request(client, mint):\n    async with semaphore:\n        return await client.shield([mint])\n```\n\n### 4. Retry Logic\n\n```python\nimport asyncio\nfrom typing import Optional\n\nasync def retry_request(func, max_retries=3, delay=1.0):\n    for attempt in range(max_retries):\n        try:\n            return await func()\n        except Exception as e:\n            if attempt == max_retries - 1:\n                raise\n            await asyncio.sleep(delay * (attempt + 1))\n```\n\n### 5. Token Amount Calculations\n\n```python\n# Always work with the smallest unit (lamports for SOL)\nsol_amount = 0.01  # SOL\nlamports = int(sol_amount * 10**9)  # Convert to lamports\n\n# For other tokens, check their decimals\nusdc_amount = 10.0  # USDC\nusdc_smallest_unit = int(usdc_amount * 10**6)  # USDC has 6 decimals\n```\n\n## **Advanced Usage**\n\n### Using Proxies\n\n```python\n# SOCKS5 proxy\nproxies = {\"https\": \"socks5://user:pass@host:port\"}\nclient = AsyncUltraApiClient(client_kwargs={\"proxies\": proxies})\n\n# HTTP proxy\nproxies = {\n    \"http\": \"http://user:pass@proxy.example.com:8080\",\n    \"https\": \"http://user:pass@proxy.example.com:8080\",\n}\nclient = AsyncUltraApiClient(client_kwargs={\"proxies\": proxies})\n```\n\n### Custom DNS Resolution\n\n```python\n# Force specific DNS resolution\nclient = AsyncUltraApiClient(\n    client_kwargs={\n        \"resolve\": [\"api.jup.ag:443:1.2.3.4\"],\n        \"dns_servers\": [\"1.1.1.1\", \"1.0.0.1\"],\n    }\n)\n```\n\n### Custom Headers and Browser Impersonation\n\n```python\n# Default: Uses \"realworld\" - randomly selects browser based on market share\nclient = AsyncUltraApiClient()\n\n# Specify a specific browser version\nclient = AsyncUltraApiClient(\n    client_kwargs={\n        \"impersonate\": \"chrome124\",  # Specific browser version\n    }\n)\n\n# Use latest version of a browser\nclient = AsyncUltraApiClient(\n    client_kwargs={\n        \"impersonate\": \"chrome\",  # Latest Chrome\n    }\n)\n\n# Custom headers with browser impersonation\nclient = AsyncUltraApiClient(\n    client_kwargs={\n        \"impersonate\": \"safari\",  # Latest Safari\n        \"headers\": {\n            \"Accept-Language\": \"en-US,en;q=0.9\",\n        }\n    }\n)\n```\n\n**Note**: By default, the SDK uses `impersonate=\"realworld\"` which randomly selects a browser version based on current market share. This helps avoid detection and provides better anonymity.\n\n## **Error Handling**\n\nThe SDK may raise various exceptions:\n\n### Common Exceptions\n\n```python\ntry:\n    response = await client.order_and_execute(order_request)\nexcept ValueError as e:\n    # Invalid private key format\n    print(f\"Configuration error: {e}\")\nexcept requests.HTTPError as e:\n    # HTTP errors (4xx, 5xx)\n    print(f\"API error: {e}\")\nexcept Exception as e:\n    # Other errors\n    print(f\"Unexpected error: {e}\")\n```\n\n### Response Status Handling\n\n```python\nresponse = await client.order_and_execute(order_request)\n\nif response.get(\"status\") == \"Failed\":\n    error_code = response.get(\"code\")\n    error_message = response.get(\"error\")\n\n    if error_code == \"INSUFFICIENT_BALANCE\":\n        print(\"Not enough balance for the swap\")\n    elif error_code == \"SLIPPAGE_EXCEEDED\":\n        print(\"Slippage tolerance exceeded\")\n    else:\n        print(f\"Transaction failed: {error_message}\")\n```\n\n## **Contributing**\n\nContributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.\n\n### Development Setup\n\n```bash\n# Clone the repository\ngit clone https://github.com/solanab/jup-python-sdk.git\ncd jup-python-sdk\n\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Run linters\nruff check .\nruff format .\n```\n\n## **Resources**\n\n- [Ultra API Documentation](https://dev.jup.ag/docs/ultra-api/)\n- [Jupiter Portal](https://portal.jup.ag/onboard) - Get your API key\n- [Discord Community](https://discord.gg/jup)\n- [GitHub Repository](https://github.com/solanab/jup-python-sdk)\n\n## **License**\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## **Disclaimer**\n\n\ud83d\udea8 **This project is actively maintained.**\nWhile we strive for stability, the SDK is under active development. We recommend staying updated with the latest releases. Important updates will be announced in the [Discord server](https://discord.gg/jup).\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "High-performance sync/async Python SDK for Jupiter Exchange APIs, powered by curl_cffi.",
    "version": "2.0.6",
    "project_urls": {
        "homepage": "https://github.com/solanab/jup-python-sdk",
        "repository": "https://github.com/solanab/jup-python-sdk"
    },
    "split_keywords": [
        "jupiter",
        " sdk",
        " solana"
    ],
    "urls": [
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "4eae07fd35437b6a1332390bc56945699c70dcce58537bb2697c7543c67c9761",
                "md5": "410b6cadc29db9069b45bb612f195e49",
                "sha256": "d39335a6f7afb15ffc6275dca25f95f9eeea472d077398d8185c916d4d2bc6a0"
            },
            "downloads": -1,
            "filename": "solanab_jup_python_sdk-2.0.6-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "410b6cadc29db9069b45bb612f195e49",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 13692,
            "upload_time": "2025-07-23T10:34:29",
            "upload_time_iso_8601": "2025-07-23T10:34:29.693593Z",
            "url": "https://files.pythonhosted.org/packages/4e/ae/07fd35437b6a1332390bc56945699c70dcce58537bb2697c7543c67c9761/solanab_jup_python_sdk-2.0.6-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": null,
            "digests": {
                "blake2b_256": "45f88525f0894249aa274be38d26658d29e0787da8f0e2dcd919c429c468aefb",
                "md5": "cd2240cd389405ed53f7423c294388e4",
                "sha256": "441107184fd3838655caa337c97b7ecdad44b0ffef9108465dadbc8745ba0835"
            },
            "downloads": -1,
            "filename": "solanab_jup_python_sdk-2.0.6.tar.gz",
            "has_sig": false,
            "md5_digest": "cd2240cd389405ed53f7423c294388e4",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 79726,
            "upload_time": "2025-07-23T10:34:30",
            "upload_time_iso_8601": "2025-07-23T10:34:30.558241Z",
            "url": "https://files.pythonhosted.org/packages/45/f8/8525f0894249aa274be38d26658d29e0787da8f0e2dcd919c429c468aefb/solanab_jup_python_sdk-2.0.6.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-07-23 10:34:30",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "solanab",
    "github_project": "jup-python-sdk",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "solanab-jup-python-sdk"
}
        
Elapsed time: 1.13170s