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

# Non-Custodial Wallets

> User-controlled wallets with delegation-based spending authority for card payments

## What are Non-Custodial Wallets?

Non-custodial wallets are user-controlled blockchain wallets where users maintain full custody of their private keys and assets. The platform never has access to private keys. Instead, users grant spending authority through blockchain-based delegation, allowing the platform to charge their wallets for card payments while users retain complete control.

## Key Benefits

<CardGroup cols={2}>
  <Card title="Self-Custody" icon="user-shield">
    Users maintain full control of their private keys and assets. No trust required in platform custody.
  </Card>

  <Card title="Web3 Native" icon="cube">
    Seamless integration with existing Web3 wallets (MetaMask, Phantom, WalletConnect).
  </Card>

  <Card title="Flexible Withdrawals" icon="money-bill-transfer">
    Withdraw credit and rewards directly to any user-controlled external wallet.
  </Card>

  <Card title="On-Chain Transparency" icon="magnifying-glass">
    All spending authority is recorded on-chain with verifiable allowances.
  </Card>
</CardGroup>

## How It Works

Non-custodial wallet integration uses delegation to enable card payments:

```mermaid theme={null}
graph TB
    A[User's External Wallet] -->|1. Delegate Spending Authority| B[Platform Smart Contract]
    B -->|2. Record Allowance On-Chain| C[Blockchain]
    D[User Makes Card Purchase] -->|3. Request Charge| B
    B -->|4. Verify Allowance| C
    C -->|5. Confirm Authority| B
    B -->|6. Deduct Funds| A
    B -->|7. Complete Transaction| D
```

### Delegation Flow

<Steps>
  <Step title="User Connects Wallet">
    User connects their Web3 wallet (MetaMask, Phantom, etc.) through your application.
  </Step>

  <Step title="Request Delegation Token">
    Your backend requests a delegation token from the API.
  </Step>

  <Step title="Approve On-Chain">
    User approves blockchain transaction granting spending authority to platform smart contract.
  </Step>

  <Step title="Submit Proof">
    Your backend submits transaction proof to complete wallet registration.
  </Step>

  <Step title="Card Payments Enabled">
    User can now make card payments, with funds deducted from their delegated wallet.
  </Step>
</Steps>

[Complete Delegation Guide →](/guides/delegation)

## External Wallets vs Credit/Reward Withdrawals

Non-custodial mode supports two types of operations:

### External Wallets (Card Funding)

User-controlled wallets that fund card payments via delegation:

**Capabilities:**

* Delegate spending authority for card payments
* View balance and allowance
* Manage priority order for multiple wallets
* Automatically charged for card transactions

[Learn more about External Wallets →](/guides/wallet/non-custodial/external-wallets)

### Credit/Reward Withdrawals

Platform-held credits and rewards can be withdrawn to user's external wallets:

**Capabilities:**

* View credit and reward balances
* Estimate withdrawal fees
* Withdraw to registered external wallets
* Automatic routing to highest priority wallet

<Note>
  In non-custodial environments, credit and reward withdrawals go to user-registered external wallets, not whitelisted addresses. Priority determines which external wallet receives the funds.
</Note>

## Supported Networks

| Network      | Currencies | Type    | Delegation Method        |
| ------------ | ---------- | ------- | ------------------------ |
| **Linea**    | USDC, USDT | EVM     | ERC-20 approve()         |
| **Ethereum** | USDC, USDT | EVM     | ERC-20 approve()         |
| **Solana**   | USDC, USDT | Non-EVM | Token account delegation |

<Note>
  For US-based users, Linea operations automatically route to US-specific infrastructure when the `x-us-env: true` header or `region=us` parameter is used.
</Note>

## Delegation Security Model

Delegation provides controlled spending authority while maintaining user custody:

### What Users Control

<CardGroup cols={2}>
  <Card title="Private Keys" icon="key">
    Users always control their private keys. Platform never has access.
  </Card>

  <Card title="Spending Limits" icon="gauge">
    Users set maximum allowance when delegating. Platform cannot exceed this limit.
  </Card>

  <Card title="Revocation" icon="ban">
    Users can revoke delegation at any time by interacting with blockchain directly.
  </Card>

  <Card title="Asset Custody" icon="vault">
    Funds remain in user's wallet until card transaction occurs.
  </Card>
</CardGroup>

### What Platform Can Do

<Card title="Charge for Card Transactions" icon="credit-card">
  Platform can deduct funds up to the delegated allowance for approved card purchases. Each charge is recorded on-chain.
</Card>

### What Platform Cannot Do

<Warning>
  The platform **cannot**:

  * Access private keys
  * Transfer funds beyond delegated allowance
  * Withdraw funds without card transaction
  * Change allowance without user approval
</Warning>

## Common Workflows

### Workflow 1: Initial Wallet Delegation

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Frontend
    participant Backend
    participant API
    participant Blockchain
    participant Wallet

    User->>Frontend: Click "Connect Wallet"
    Frontend->>Backend: Request delegation token
    Backend->>API: GET /v1/delegation/token
    API-->>Backend: Return token
    Backend-->>Frontend: Pass token
    Frontend->>Wallet: Prompt wallet connection
    User->>Wallet: Approve connection
    Wallet-->>Frontend: Connected
    Frontend->>Wallet: Request approval transaction
    User->>Wallet: Sign transaction
    Wallet->>Blockchain: Submit approval
    Blockchain-->>Wallet: Confirm transaction
    Wallet-->>Frontend: txHash & signature
    Frontend->>Backend: Submit proof
    Backend->>API: POST /v1/delegation/evm/post-approval
    API-->>Backend: Success
    Backend-->>Frontend: Wallet registered
    Frontend-->>User: Ready for card payments
```

### Workflow 2: Credit Withdrawal to External Wallet

```mermaid theme={null}
sequenceDiagram
    participant User
    participant App
    participant API
    participant Blockchain

    User->>App: Request credit withdrawal
    App->>API: GET /v1/wallet/credit/withdraw-estimation
    API-->>App: Fee estimate
    App-->>User: Display amount & fees
    User->>App: Confirm withdrawal
    App->>API: POST /v1/wallet/credit/withdraw
    API->>Blockchain: Execute transaction
    Blockchain-->>API: txHash
    API-->>App: Return txHash
    App-->>User: Show confirmation
```

## Allowance Management

When users delegate spending authority, they set an allowance (spending limit):

### How Allowances Work

* **Set During Delegation**: User specifies maximum amount platform can spend
* **Decreases with Use**: Each card transaction reduces available allowance
* **On-Chain Record**: Allowance is recorded and enforced by blockchain smart contracts
* **User-Controlled**: Only users can increase allowance through redelegation

<CodeGroup>
  ```bash Check Allowance theme={null}
  curl -X GET "https://api.example.com/v1/wallet/external" \
    -H "x-client-key: YOUR_PUBLIC_KEY" \
    -H "Authorization: Bearer USER_ACCESS_TOKEN"
  ```

  ```json Response theme={null}
  [
    {
      "address": "0x3a11a86cf218c448be519728cd3ac5c741fb3424",
      "currency": "usdc",
      "balance": "5000.00",
      "allowance": "3500",
      "network": "linea"
    }
  ]
  ```
</CodeGroup>

**In this example:**

* User delegated 5000 USDC initially
* Platform has spent 1500 USDC on card transactions
* Remaining allowance: 3500 USDC

<Note>
  When allowance runs low, prompt users to redelegate with a higher amount. The redelegation process follows the same flow as initial delegation.
</Note>

## Redelegation

Users need to redelegate when:

<AccordionGroup>
  <Accordion title="Allowance Exhausted">
    When card transactions have consumed the full delegated allowance, users must redelegate to continue using card payments.

    **When to Prompt:** Alert users when allowance drops below 10% of original amount or a threshold you define.
  </Accordion>

  <Accordion title="Increase Spending Limit">
    Users may want to increase their allowance for convenience or to accommodate larger purchases.

    **Example:** User initially delegated $500 but wants to increase to $2000 for an upcoming trip.
  </Accordion>

  <Accordion title="Smart Contract Upgrade">
    When platform upgrades smart contracts, users must redelegate to the new contract address.

    **Notification:** Platform will notify integrators of contract upgrades with migration timeline.
  </Accordion>

  <Accordion title="Network Migration">
    If user wants to switch from one network to another (e.g., Ethereum to Linea for lower fees).

    **Process:** Delegate from wallet on new network. Old delegation remains until allowance exhausted.
  </Accordion>
</AccordionGroup>

**Redelegation Process:** Identical to initial delegation. Follow the [Delegation Guide](/guides/delegation) with updated allowance amount.

## Priority Management

When users have multiple external wallets registered, priority determines:

1. Which wallet is charged for card transactions
2. Which wallet receives credit/reward withdrawals

<CodeGroup>
  ```bash Get Priority theme={null}
  curl -X GET "https://api.example.com/v1/wallet/external/priority" \
    -H "x-client-key: YOUR_PUBLIC_KEY" \
    -H "Authorization: Bearer USER_ACCESS_TOKEN"
  ```

  ```json Response theme={null}
  [
    {
      "id": 551,
      "address": "0x3a11...",
      "currency": "usdc",
      "network": "linea",
      "priority": 1
    },
    {
      "id": 552,
      "address": "0x7b22...",
      "currency": "usdt",
      "network": "ethereum",
      "priority": 2
    }
  ]
  ```
</CodeGroup>

**Priority Rules:**

* Lower numbers = higher priority (1 is used before 2)
* For **card payments**: Platform charges priority 1 wallet first, moves to 2 if insufficient
* For **withdrawals**: Platform sends to priority 1 wallet first, moves to 2 if transaction fails

[Learn more about Priority Management →](/guides/wallet/non-custodial/priority)

## Credit and Reward Wallets

In non-custodial environments, credit and reward wallets work differently from custodial mode:

### Viewing Balances

<CodeGroup>
  ```bash Credit Balance theme={null}
  curl -X GET "https://api.example.com/v1/wallet/credit" \
    -H "x-client-key: YOUR_PUBLIC_KEY" \
    -H "Authorization: Bearer USER_ACCESS_TOKEN"
  ```

  ```bash Reward Balance theme={null}
  curl -X GET "https://api.example.com/v1/wallet/reward" \
    -H "x-client-key: YOUR_PUBLIC_KEY" \
    -H "Authorization: Bearer USER_ACCESS_TOKEN"
  ```

  ```json Response (Both) theme={null}
  {
    "id": "098aeb90-e7f7-4f81-bc2e-4963330122c5",
    "balance": "125.50",
    "currency": "usdc",
    "isWithdrawable": true,
    "type": "CREDIT"
  }
  ```
</CodeGroup>

### Withdrawing to External Wallets

<Tabs>
  <Tab title="Estimate Fees">
    ```bash Credit theme={null}
    curl -X GET "https://api.example.com/v1/wallet/credit/withdraw-estimation" \
      -H "x-client-key: YOUR_PUBLIC_KEY" \
      -H "Authorization: Bearer USER_ACCESS_TOKEN"
    ```

    ```bash Reward theme={null}
    curl -X GET "https://api.example.com/v1/wallet/reward/withdraw-estimation" \
      -H "x-client-key: YOUR_PUBLIC_KEY" \
      -H "Authorization: Bearer USER_ACCESS_TOKEN"
    ```

    ```json Response theme={null}
    {
      "wei": "6219123007416",
      "eth": "0.000006219123007416",
      "usdc": "0.01644666445335518319452825472"
    }
    ```

    Platform covers gas fees. User receives full withdrawal amount.
  </Tab>

  <Tab title="Execute Withdrawal">
    ```bash Credit theme={null}
    curl -X POST "https://api.example.com/v1/wallet/credit/withdraw" \
      -H "x-client-key: YOUR_PUBLIC_KEY" \
      -H "Authorization: Bearer USER_ACCESS_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{"amount": "100"}'
    ```

    ```bash Reward theme={null}
    curl -X POST "https://api.example.com/v1/wallet/reward/withdraw" \
      -H "x-client-key: YOUR_PUBLIC_KEY" \
      -H "Authorization: Bearer USER_ACCESS_TOKEN" \
      -H "Content-Type: application/json" \
      -d '{"amount": "50"}'
    ```

    ```json Response theme={null}
    {
      "txHash": "0xb92de09d893e8162b0861c0f7321f68df02212efbc58f208839ae3f176d89638"
    }
    ```

    Funds are sent to highest priority external wallet registered by the user.
  </Tab>
</Tabs>

<Note>
  Credit and reward withdrawals currently support Linea network only. Funds are sent to the user's highest priority Linea external wallet.
</Note>

## Error Handling

### Insufficient Allowance

```json theme={null}
{
  "error": "Insufficient allowance",
  "code": "WALLET_INSUFFICIENT_ALLOWANCE",
  "message": "Delegated allowance is insufficient for this transaction"
}
```

**Solution:** Prompt user to redelegate with higher allowance.

### No External Wallet Registered

```json theme={null}
{
  "error": "No external wallet",
  "code": "WALLET_NO_EXTERNAL",
  "message": "User has not registered an external wallet"
}
```

**Solution:** Guide user through delegation flow to register their first external wallet.

### Allowance Expired

```json theme={null}
{
  "error": "Delegation expired",
  "code": "WALLET_DELEGATION_EXPIRED",
  "message": "Wallet delegation has expired and must be renewed"
}
```

**Solution:** Prompt user to redelegate. Follow standard delegation flow.

## Best Practices

<Card title="Proactive Allowance Monitoring" icon="gauge-high">
  Monitor allowance levels and alert users when allowance drops below 20% of original amount. Suggest redelegation before complete exhaustion.
</Card>

<Card title="Clear Delegation UX" icon="lightbulb">
  Explain delegation clearly: users grant spending authority but maintain custody. Use analogies like "credit card limit" to make the concept accessible.
</Card>

<Card title="Display Allowance Visually" icon="chart-simple">
  Show allowance status with progress bars or percentage indicators. Make it easy for users to understand their remaining spending capacity.
</Card>

<Card title="Support Multiple Wallets" icon="wallet">
  Allow users to register multiple external wallets for redundancy and flexibility. Implement priority management to let users control preferences.
</Card>

<Card title="Transparent Fee Display" icon="hand-holding-dollar">
  Show withdrawal fee estimates before users confirm credit/reward withdrawals. Transparency builds trust.
</Card>

<Card title="Blockchain Explorer Links" icon="link">
  Provide blockchain explorer links for delegation transactions and withdrawals so users can verify on-chain activity.
</Card>

## Security Considerations

<Warning>
  **Smart Contract Risk**: While delegation is enforced by blockchain smart contracts, users should verify contract addresses before approving. Display contract addresses clearly in your UI.
</Warning>

<Note>
  **Allowance Limit Strategy**: Recommend users start with conservative allowances (1-3 months of expected spending) and increase as needed. This limits exposure if private keys are compromised.
</Note>

<Note>
  **Wallet Software Security**: Users are responsible for securing their Web3 wallet software and seed phrases. Provide educational resources about wallet security best practices.
</Note>

## US Environment Routing

For US-based users, route requests to the US environment:

<Tabs>
  <Tab title="Header Method">
    ```bash theme={null}
    curl -X GET "https://api.example.com/v1/wallet/external" \
      -H "x-client-key: YOUR_PUBLIC_KEY" \
      -H "Authorization: Bearer USER_ACCESS_TOKEN" \
      -H "x-us-env: true"
    ```
  </Tab>

  <Tab title="Query Parameter Method">
    ```bash theme={null}
    curl -X GET "https://api.example.com/v1/wallet/external?region=us" \
      -H "x-client-key: YOUR_PUBLIC_KEY" \
      -H "Authorization: Bearer USER_ACCESS_TOKEN"
    ```
  </Tab>
</Tabs>

The US environment automatically routes Linea network operations to US-specific infrastructure.

## Next Steps

<CardGroup cols={2}>
  <Card title="Delegation Guide" icon="link" href="/guides/delegation">
    Complete guide to implementing wallet delegation
  </Card>

  <Card title="External Wallets" icon="wallet" href="/guides/wallet/non-custodial/external-wallets">
    View and manage registered external wallets
  </Card>

  <Card title="Priority Management" icon="list-ol" href="/guides/wallet/non-custodial/priority">
    Control wallet priority for payments and withdrawals
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference">
    Complete API documentation
  </Card>
</CardGroup>
