Skip to main content

Usage

from chipi_sdk import GetWalletParams

wallet_response = sdk.get_wallet(
    params=GetWalletParams(
        external_user_id="your-user-id-123"
    )
)

Parameters

  • external_user_id (str): Your application’s unique identifier for the user

Return Value

Returns a GetWalletResponse object containing:
  • id: Internal wallet ID
  • user_id: Internal user ID (optional)
  • org_id: Organization ID (optional)
  • wallet: WalletData object with:
    • public_key: Wallet’s public address
    • encrypted_private_key: AES encrypted private key
    • wallet_type: Type of wallet
    • normalized_public_key: Normalized public key
  • external_user_id: Your application’s user ID
  • created_at: Wallet creation timestamp
  • updated_at: Last update timestamp
Returns None if wallet is not found.

Example Implementation

from chipi_sdk import ChipiSDK, ChipiSDKConfig, GetWalletParams

# Initialize SDK
sdk = ChipiSDK(
    config=ChipiSDKConfig(
        api_public_key="pk_prod_your_public_key",
        api_secret_key="sk_prod_your_secret_key",
    )
)

def get_user_wallet(user_id: str):
    """Get wallet for a specific user."""
    try:
        wallet_response = sdk.get_wallet(
            params=GetWalletParams(external_user_id=user_id)
        )
        
        if wallet_response is None:
            print(f"No wallet found for user: {user_id}")
            return None
        
        print(f"✅ Wallet found!")
        print(f"   Address: {wallet_response.wallet.public_key}")
        print(f"   Created: {wallet_response.created_at}")
        
        return wallet_response
        
    except Exception as error:
        print(f"❌ Failed to get wallet: {error}")
        raise

# Usage
wallet = get_user_wallet("user-123")
if wallet:
    print(f"User wallet address: {wallet.wallet.public_key}")

Async Version

For async applications, use aget_wallet:
import asyncio

async def get_user_wallet_async(user_id: str):
    """Get wallet asynchronously."""
    wallet_response = await sdk.aget_wallet(
        params=GetWalletParams(external_user_id=user_id)
    )
    return wallet_response

# Run async
wallet = asyncio.run(get_user_wallet_async("user-123"))

Handling Missing Wallets

def get_or_create_wallet(user_id: str, user_pin: str):
    """Get existing wallet or create a new one."""
    from chipi_sdk import CreateWalletParams, WalletType
    
    # Try to get existing wallet
    wallet_response = sdk.get_wallet(
        params=GetWalletParams(external_user_id=user_id)
    )
    
    if wallet_response:
        print(f"Found existing wallet for {user_id}")
        return wallet_response.wallet
    
    # Create new wallet if not found
    print(f"Creating new wallet for {user_id}")
    new_wallet = sdk.create_wallet(
        params=CreateWalletParams(
            encrypt_key=user_pin,
            external_user_id=user_id,
            wallet_type=WalletType.CHIPI,
        )
    )
    
    return new_wallet.wallet

# Usage
wallet_data = get_or_create_wallet("user-123", "secure-pin-1234")

Complete Example with Caching

from chipi_sdk import ChipiSDK, ChipiSDKConfig, GetWalletParams
from functools import lru_cache
from datetime import datetime, timedelta

# Initialize SDK
sdk = ChipiSDK(
    config=ChipiSDKConfig(
        api_public_key="pk_prod_your_public_key",
        api_secret_key="sk_prod_your_secret_key",
    )
)

# Simple in-memory cache
wallet_cache = {}
cache_ttl = timedelta(minutes=5)

def get_wallet_cached(user_id: str):
    """Get wallet with caching to reduce API calls."""
    # Check cache
    if user_id in wallet_cache:
        cached_data, timestamp = wallet_cache[user_id]
        if datetime.now() - timestamp < cache_ttl:
            print(f"📦 Returning cached wallet for {user_id}")
            return cached_data
    
    # Fetch from API
    print(f"🌐 Fetching wallet from API for {user_id}")
    wallet_response = sdk.get_wallet(
        params=GetWalletParams(external_user_id=user_id)
    )
    
    # Update cache
    if wallet_response:
        wallet_cache[user_id] = (wallet_response, datetime.now())
    
    return wallet_response

# Usage
wallet1 = get_wallet_cached("user-123")  # API call
wallet2 = get_wallet_cached("user-123")  # From cache

Using Wallet Data for Transactions

After retrieving a wallet, you can use it for transactions:
from chipi_sdk import GetWalletParams, TransferParams, ChainToken

# Get wallet
wallet_response = sdk.get_wallet(
    params=GetWalletParams(external_user_id="user-123")
)

if wallet_response:
    # Use wallet for transfer
    tx_hash = sdk.transfer(
        params=TransferParams(
            encrypt_key="user-secure-pin",
            wallet=wallet_response.wallet,
            token=ChainToken.USDC,
            recipient="0x...",
            amount="10.0",
        )
    )
    print(f"Transfer completed: {tx_hash}")

Error Handling

from chipi_sdk import ChipiApiError, GetWalletParams

def safe_get_wallet(user_id: str):
    """Get wallet with error handling."""
    try:
        wallet_response = sdk.get_wallet(
            params=GetWalletParams(external_user_id=user_id)
        )
        
        if wallet_response is None:
            return {
                "success": False,
                "error": "Wallet not found",
                "user_id": user_id
            }
        
        return {
            "success": True,
            "wallet": wallet_response.wallet,
            "public_key": wallet_response.wallet.public_key,
            "created_at": wallet_response.created_at
        }
        
    except ChipiApiError as e:
        print(f"❌ API error: {e.message}")
        return {
            "success": False,
            "error": e.message,
            "status": e.status
        }
    except Exception as e:
        print(f"❌ Unexpected error: {e}")
        return {
            "success": False,
            "error": str(e)
        }

# Usage
result = safe_get_wallet("user-123")
if result["success"]:
    print(f"Wallet: {result['public_key']}")
else:
    print(f"Error: {result['error']}")