> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chipipay.com/llms.txt
> Use this file to discover all available pages before exploring further.

# get_wallet

> Retrieves wallet information for a user by their external user ID.

## Usage

```python theme={null}
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
* `public_key`: Wallet's public address
* `encrypted_private_key`: AES encrypted private key
* `wallet_type`: Type of wallet
* `normalized_public_key`: Normalized public key
* `chain`: Blockchain network
* `is_deployed`: Whether the wallet contract is deployed
* `external_user_id`: Your application's user ID
* `organization_id`: Organization ID (optional)
* `api_public_key`: Organization API public key
* `created_at`: Wallet creation timestamp
* `updated_at`: Last update timestamp

Returns `None` if wallet is not found.

## Example Implementation

```python theme={null}
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.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.public_key}")
```

## Async Version

For async applications, use `aget_wallet`:

```python theme={null}
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

```python theme={null}
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

    # 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

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

## Complete Example with Caching

```python theme={null}
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:

```python theme={null}
from chipi_sdk import GetWalletParams, TransferParams, ChainToken, WalletData

# 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=WalletData(
                public_key=wallet_response.public_key,
                encrypted_private_key=wallet_response.encrypted_private_key,
            ),
            token=ChainToken.USDC,
            recipient="0x...",
            amount="10.0",
        )
    )
    print(f"Transfer completed: {tx_hash}")
```

## Error Handling

```python theme={null}
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,
            "public_key": wallet_response.public_key,
            "encrypted_private_key": wallet_response.encrypted_private_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']}")
```

## Related Methods

* [create\_wallet](/sdk/python/methods/create-wallet) - Create a new wallet
* [transfer](/sdk/python/methods/transfer) - Send tokens from the wallet
* [get\_token\_balance](/sdk/backend/methods/get-wallet) - Check wallet balance
