> ## 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.

# External Wallet Priority

> Control wallet priority for card payments and credit/reward withdrawals

## Overview

Priority management determines the order in which external wallets are evaluated for funding transactions. When users have multiple registered external wallets, priority controls:

1. **Card Payments**: Which wallet funds card purchases
2. **Credit/Reward Withdrawals**: Which wallet receives platform credits and rewards

When a transaction is initiated, the platform checks wallets in priority order (1, 2, 3...). The first wallet with sufficient balance and allowance to cover the entire transaction cost is used. **Only one wallet funds each transaction** - multi-funding is not supported.

Lower priority numbers are evaluated first (priority 1 before priority 2).

## How Priority Works

<Warning>
  **Critical**: Only ONE wallet funds each transaction. The platform evaluates wallets sequentially in priority order and uses the first wallet with sufficient balance to cover the ENTIRE transaction cost. If a wallet has insufficient balance, it's skipped entirely - partial funding from multiple wallets is NOT supported.
</Warning>

### Sequential Wallet Evaluation

```mermaid theme={null}
graph TB
    A[Transaction Initiated] --> B{Check Priority 1 Wallet}
    B -->|Sufficient Balance/Allowance<br/>for ENTIRE transaction| C[Use Priority 1 Wallet]
    C --> D[Transaction Complete]
    B -->|Insufficient Balance| E{Check Priority 2 Wallet}
    E -->|Sufficient Balance<br/>for ENTIRE transaction| F[Use Priority 2 Wallet]
    F --> D
    E -->|Insufficient Balance| G{Check Priority 3 Wallet}
    G -->|Sufficient Balance<br/>for ENTIRE transaction| H[Use Priority 3 Wallet]
    H --> D
    G -->|Insufficient Balance| I[Transaction Failed]
```

The platform checks each wallet in order until it finds one that can cover the full transaction amount. If no single wallet has enough balance, the transaction fails.

## Viewing Current Priority

Get the current priority order for all registered external wallets:

<CodeGroup>
  ```bash Request 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": "0x3a11a86cf218c448be519728cd3ac5c741fb3424",
      "currency": "usdc",
      "network": "linea",
      "priority": 1
    },
    {
      "id": 552,
      "address": "0x7b22c97de329f3b8dc3b1c472f9af2b2e5c84a91",
      "currency": "usdt",
      "network": "ethereum",
      "priority": 2
    },
    {
      "id": 553,
      "address": "DYw8jCTfwHNRJhhmFcbXvVDTqWMEVFBX6ZKUmG5CNSKK",
      "currency": "usdc",
      "network": "solana",
      "priority": 3
    }
  ]
  ```
</CodeGroup>

### Response Fields

| Field      | Description                                        |
| ---------- | -------------------------------------------------- |
| `id`       | Wallet identifier (required for updating priority) |
| `address`  | Blockchain wallet address                          |
| `currency` | Currency in this wallet                            |
| `network`  | Blockchain network                                 |
| `priority` | Current priority order (lower = higher precedence) |

## Updating Priority

Change the priority order of external wallets:

<CodeGroup>
  ```bash Request theme={null}
  curl -X PUT "https://api.example.com/v1/wallet/external/priority" \
    -H "x-client-key: YOUR_PUBLIC_KEY" \
    -H "Authorization: Bearer USER_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "wallets": [
        {
          "id": 552,
          "priority": 1
        },
        {
          "id": 551,
          "priority": 2
        },
        {
          "id": 553,
          "priority": 3
        }
      ]
    }'
  ```

  ```json Response theme={null}
  {
    "success": true
  }
  ```
</CodeGroup>

<Warning>
  You must include **ALL** registered external wallets when updating priority. The API replaces the entire priority configuration with the provided list.
</Warning>

### Request Parameters

| Field                | Required | Description                                         |
| -------------------- | -------- | --------------------------------------------------- |
| `wallets`            | Yes      | Array of all wallets with new priority assignments  |
| `wallets[].id`       | Yes      | Wallet identifier from GET priority response        |
| `wallets[].priority` | Yes      | New priority value (must be sequential: 1, 2, 3...) |

## Priority Use Cases

### For Card Payments

Priority determines the order in which wallets are evaluated when a card transaction occurs. The first wallet with sufficient balance to cover the entire purchase amount is used. Only one wallet is charged per transaction.

<AccordionGroup>
  <Accordion title="Fee Optimization">
    Set lower-fee networks to higher priority to minimize transaction costs.

    **Example:**

    * Priority 1: USDC on Linea (fees: \$0.01-0.05)
    * Priority 2: USDC on Ethereum (fees: \$2-5)
    * Priority 3: USDC on Solana (fees: \$0.0001)

    Card transactions will check Linea first. If Linea wallet has sufficient balance for the entire transaction, it's used. If Linea has insufficient balance, the platform moves to Ethereum. Only one wallet funds each purchase.
  </Accordion>

  <Accordion title="Balance Management">
    Spend from smaller balance wallets first to consolidate funds.

    **Example:**

    * Priority 1: Wallet with \$200 balance (spend this first)
    * Priority 2: Wallet with \$1000 balance (backup)
    * Priority 3: Wallet with \$5000 balance (emergency reserve)
  </Accordion>

  <Accordion title="Currency Preference">
    Prefer spending one stablecoin over another based on personal preference or market conditions.

    **Example:**

    * Priority 1: USDC wallet
    * Priority 2: USDT wallet
    * Priority 3: DAI wallet
  </Accordion>

  <Accordion title="Network Reliability">
    Prioritize more reliable networks during periods of high congestion.

    **Example During Ethereum Congestion:**

    * Priority 1: Solana wallet (fast, cheap)
    * Priority 2: Linea wallet (moderate)
    * Priority 3: Ethereum wallet (congested)
  </Accordion>
</AccordionGroup>

### For Credit/Reward Withdrawals

Priority determines which wallet receives credit and reward withdrawals. For withdrawals, the priority 1 wallet always receives the funds (if it has sufficient capacity). If priority 1 wallet cannot receive the funds, the transaction will fail.

<AccordionGroup>
  <Accordion title="Primary Holding Wallet">
    Receive all credits and rewards in your main holding wallet.

    **Example:**

    * Priority 1: Hardware wallet (secure long-term storage)
    * Priority 2: Hot wallet (not used for withdrawals)

    All platform credits and rewards automatically go to your priority 1 hardware wallet. Priority 2 wallet serves as a backup for card payments only.
  </Accordion>

  <Accordion title="DeFi Deployment">
    Automatically route rewards to wallet connected to DeFi protocols.

    **Example:**

    * Priority 1: DeFi wallet (earning yield)
    * Priority 2: Spending wallet (daily use)

    Rewards flow directly into yield-earning positions.
  </Accordion>

  <Accordion title="Network Selection">
    Receive withdrawals on preferred network for lower fees or faster processing.

    **Example:**

    * Priority 1: Linea wallet (low withdrawal fees)
    * Priority 2: Ethereum wallet (backup)
  </Accordion>
</AccordionGroup>

## Transaction Flow Examples

### Example 1: Card Payment with Multiple Wallets

**Setup:**

* Priority 1: USDC Linea ($50 balance, $50 allowance)
* Priority 2: USDT Ethereum ($200 balance, $200 allowance)
* Priority 3: USDC Solana ($1000 balance, $1000 allowance)

**Transaction: \$75 Purchase**

<Steps>
  <Step title="Check Priority 1 (Linea)">
    Platform checks Linea wallet. Balance: $50. Insufficient for $75 purchase. **Wallet skipped entirely.**
  </Step>

  <Step title="Check Priority 2 (Ethereum)">
    Platform checks Ethereum wallet. Balance: $200. **Sufficient!** Uses this wallet to fund the entire $75 transaction.
  </Step>

  <Step title="Transaction Complete">
    Purchase approved. Ethereum wallet balance now \$125. Solana wallet (Priority 3) was never checked. **Only Ethereum wallet was used.**
  </Step>
</Steps>

**Result:** User pays Ethereum network fees but transaction succeeds. Priority 1 wallet had insufficient balance (was skipped), so Priority 2 was used for the entire transaction. No funds were taken from Priority 1 wallet.

### Example 2: Credit Withdrawal

**Setup:**

* Priority 1: Linea wallet (0x3a11...)
* Priority 2: Ethereum wallet (0x7b22...)
* User has \$100 credit balance

**Transaction: Withdraw \$100 Credit**

<Steps>
  <Step title="User Requests Withdrawal">
    User calls `POST /v1/wallet/credit/withdraw` with amount: "100"
  </Step>

  <Step title="Platform Selects Priority 1 Wallet">
    Platform identifies Priority 1 wallet (Linea) as the withdrawal destination. Priority 2 and 3 wallets are NOT considered for withdrawals.
  </Step>

  <Step title="Execute On-Chain Transfer">
    Platform sends the entire \$100 USDC to Priority 1 Linea wallet address
  </Step>

  <Step title="Return Transaction Hash">
    API returns `txHash` for blockchain verification
  </Step>
</Steps>

**Result:** User receives the entire \$100 credit in their Linea wallet (Priority 1). Ethereum wallet (Priority 2) is not used. For withdrawals, only the priority 1 wallet receives funds.

## Implementation Examples

### Get and Display Priority

<CodeGroup>
  ```javascript JavaScript theme={null}
  async function fetchWalletPriority(userToken) {
    const response = await fetch(
      'https://api.example.com/v1/wallet/external/priority',
      {
        headers: {
          'x-client-key': 'YOUR_PUBLIC_KEY',
          'Authorization': `Bearer ${userToken}`
        }
      }
    );

    const wallets = await response.json();

    // Sort by priority (already sorted, but explicit)
    return wallets.sort((a, b) => a.priority - b.priority);
  }

  // Usage
  const priorityWallets = await fetchWalletPriority(userToken);

  console.log('Card Payment Priority:');
  priorityWallets.forEach((wallet, index) => {
    console.log(`${index + 1}. ${wallet.network} ${wallet.currency.toUpperCase()}`);
    console.log(`   ${wallet.address}`);
  });
  ```

  ```python Python theme={null}
  import requests
  from typing import List, Dict

  def fetch_wallet_priority(user_token: str) -> List[Dict]:
      response = requests.get(
          'https://api.example.com/v1/wallet/external/priority',
          headers={
              'x-client-key': 'YOUR_PUBLIC_KEY',
              'Authorization': f'Bearer {user_token}'
          }
      )

      wallets = response.json()

      # Sort by priority
      return sorted(wallets, key=lambda w: w['priority'])

  # Usage
  priority_wallets = fetch_wallet_priority(user_token)

  print('Card Payment Priority:')
  for index, wallet in enumerate(priority_wallets):
      print(f"{index + 1}. {wallet['network']} {wallet['currency'].upper()}")
      print(f"   {wallet['address']}")
  ```
</CodeGroup>

### Update Priority

<CodeGroup>
  ```javascript JavaScript theme={null}
  async function updateWalletPriority(userToken, newPriorityOrder) {
    // newPriorityOrder is array of wallet IDs in desired order
    const payload = {
      wallets: newPriorityOrder.map((id, index) => ({
        id: id,
        priority: index + 1
      }))
    };

    const response = await fetch(
      'https://api.example.com/v1/wallet/external/priority',
      {
        method: 'PUT',
        headers: {
          'x-client-key': 'YOUR_PUBLIC_KEY',
          'Authorization': `Bearer ${userToken}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(payload)
      }
    );

    if (!response.ok) {
      throw new Error('Failed to update priority');
    }

    return await response.json();
  }

  // Usage: Move wallet 553 to priority 1, others shift down
  const currentOrder = [551, 552, 553]; // Current wallet IDs in priority order
  const newOrder = [553, 551, 552]; // New desired order

  await updateWalletPriority(userToken, newOrder);
  ```

  ```python Python theme={null}
  import requests
  from typing import List

  def update_wallet_priority(user_token: str, new_priority_order: List[int]) -> dict:
      # new_priority_order is list of wallet IDs in desired order
      payload = {
          'wallets': [
              {'id': wallet_id, 'priority': index + 1}
              for index, wallet_id in enumerate(new_priority_order)
          ]
      }

      response = requests.put(
          'https://api.example.com/v1/wallet/external/priority',
          headers={
              'x-client-key': 'YOUR_PUBLIC_KEY',
              'Authorization': f'Bearer {user_token}',
              'Content-Type': 'application/json'
          },
          json=payload
      )

      response.raise_for_status()
      return response.json()

  # Usage: Move wallet 553 to priority 1
  current_order = [551, 552, 553]
  new_order = [553, 551, 552]

  result = update_wallet_priority(user_token, new_order)
  ```
</CodeGroup>

### Priority Management UI

<CodeGroup>
  ```jsx React Component theme={null}
  import { useState, useEffect } from 'react';

  function PriorityManager({ userToken }) {
    const [wallets, setWallets] = useState([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
      fetchPriority();
    }, []);

    const fetchPriority = async () => {
      const response = await fetch(
        'https://api.example.com/v1/wallet/external/priority',
        {
          headers: {
            'x-client-key': 'YOUR_PUBLIC_KEY',
            'Authorization': `Bearer ${userToken}`
          }
        }
      );

      const data = await response.json();
      setWallets(data.sort((a, b) => a.priority - b.priority));
    };

    const movePriority = async (walletId, direction) => {
      const currentIndex = wallets.findIndex(w => w.id === walletId);
      const newIndex = direction === 'up'
        ? currentIndex - 1
        : currentIndex + 1;

      if (newIndex < 0 || newIndex >= wallets.length) return;

      const reorderedWallets = [...wallets];
      const [movedWallet] = reorderedWallets.splice(currentIndex, 1);
      reorderedWallets.splice(newIndex, 0, movedWallet);

      setLoading(true);

      const payload = {
        wallets: reorderedWallets.map((w, index) => ({
          id: w.id,
          priority: index + 1
        }))
      };

      await fetch(
        'https://api.example.com/v1/wallet/external/priority',
        {
          method: 'PUT',
          headers: {
            'x-client-key': 'YOUR_PUBLIC_KEY',
            'Authorization': `Bearer ${userToken}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(payload)
        }
      );

      await fetchPriority();
      setLoading(false);
    };

    return (
      <div className="priority-manager">
        <h3>Wallet Priority</h3>
        <p className="description">
          Lower numbers are used first for card payments and withdrawals
        </p>

        <div className="wallet-list">
          {wallets.map((wallet, index) => (
            <div key={wallet.id} className="priority-item">
              <div className="priority-number">#{wallet.priority}</div>

              <div className="wallet-info">
                <div className="wallet-header">
                  <strong>{wallet.currency.toUpperCase()}</strong>
                  <span className="network-badge">{wallet.network}</span>
                </div>
                <code className="address">
                  {wallet.address.slice(0, 10)}...{wallet.address.slice(-8)}
                </code>
              </div>

              <div className="priority-controls">
                <button
                  onClick={() => movePriority(wallet.id, 'up')}
                  disabled={index === 0 || loading}
                  className="btn-icon"
                  title="Move up"
                >
                  ↑
                </button>
                <button
                  onClick={() => movePriority(wallet.id, 'down')}
                  disabled={index === wallets.length - 1 || loading}
                  className="btn-icon"
                  title="Move down"
                >
                  ↓
                </button>
              </div>
            </div>
          ))}
        </div>

        <div className="info-box">
          <h4>How Priority Works</h4>
          <ul>
            <li>Card payments: Platform checks wallets in order (1, 2, 3). First wallet with sufficient balance for ENTIRE transaction is used</li>
            <li>Credit/reward withdrawals: Always go to Priority 1 wallet only</li>
            <li>Only ONE wallet is used per transaction - no multi-wallet funding</li>
            <li>If all wallets have insufficient balance, transaction fails</li>
          </ul>
        </div>
      </div>
    );
  }
  ```
</CodeGroup>

## Priority Best Practices

<Card title="Start with Fee Optimization" icon="dollar-sign">
  Set lowest-fee networks (Linea, Solana) to priority 1 for cost-effective card payments. Higher-fee networks (Ethereum) as backup.
</Card>

<Card title="Consider Transaction Speed" icon="bolt">
  For time-sensitive purchases, prioritize faster networks (Solana: 5-30s, Linea: 1-2min) over slower ones (Ethereum: 5-15min).
</Card>

<Card title="Balance Distribution" icon="scale-balanced">
  Don't over-concentrate funds in Priority 1. Maintain balances across multiple priorities for redundancy.
</Card>

<Card title="Update Dynamically" icon="arrows-rotate">
  Allow users to easily adjust priority based on changing needs (travel, large purchase upcoming, network congestion).
</Card>

<Card title="Show Fallback Behavior" icon="info-circle">
  Clearly communicate that Priority 2 and 3 are backups, only used if Priority 1 has insufficient balance for the entire transaction. Each wallet must be able to fund the full transaction amount.
</Card>

<Card title="Withdrawal Clarity" icon="hand-holding-dollar">
  Inform users that credit/reward withdrawals **always** go to Priority 1 wallet ONLY. Make this explicit in UI. Priority 2+ wallets are never used for withdrawals.
</Card>

## Error Handling

### All Wallets Insufficient

```json theme={null}
{
  "error": "Insufficient funds",
  "code": "WALLET_ALL_INSUFFICIENT",
  "message": "None of the registered wallets have sufficient balance or allowance to cover the entire transaction"
}
```

**Cause:** This occurs when the platform checks all wallets in priority order and none have sufficient balance to fund the ENTIRE transaction. Partial funding is not supported, so if no single wallet can cover the full amount, the transaction fails.

**Solution:** User needs to either fund one of their wallets with enough balance for the full transaction, or redelegate with higher allowance.

### Invalid Wallet IDs

```json theme={null}
{
  "error": "Invalid wallet ID",
  "code": "WALLET_INVALID_ID",
  "message": "One or more wallet IDs do not exist or do not belong to this user"
}
```

**Solution:** Fetch current wallets with GET priority endpoint and use returned IDs.

### Non-Sequential Priority

```json theme={null}
{
  "error": "Invalid priority values",
  "code": "WALLET_INVALID_PRIORITY",
  "message": "Priority values must be sequential starting from 1"
}
```

**Solution:** Ensure priority values are 1, 2, 3, ... with no gaps or duplicates.

### Missing Wallets in Update

```json theme={null}
{
  "error": "Incomplete wallet list",
  "code": "WALLET_INCOMPLETE_LIST",
  "message": "Must include all registered wallets when updating priority"
}
```

**Solution:** Include all wallets from GET priority response in PUT request.

## Network-Specific Considerations

### Linea Priority Strategy

**Recommended:** Priority 1 for daily spending

**Reasons:**

* Low fees (\$0.01-0.05 per transaction)
* Fast confirmations (1-2 minutes)
* US environment support
* Optimal for frequent card use

### Ethereum Priority Strategy

**Recommended:** Priority 2 or 3 (backup)

**Reasons:**

* Higher fees (\$2-10 depending on congestion)
* Slower confirmations (5-15 minutes)
* Best as fallback, not primary

**When to Use Priority 1:**

* Network congestion low (weekends, off-hours)
* Large balance only on Ethereum
* Participating in Ethereum-specific rewards

### Solana Priority Strategy

**Recommended:** Priority 1 for speed-sensitive or Priority 3 for backup

**Reasons:**

* Extremely low fees (\~\$0.0001)
* Very fast confirmations (5-30 seconds)
* Occasional network instability

**When to Use Priority 1:**

* Cost is paramount
* Speed is critical
* Network is stable

## Next Steps

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

  <Card title="Delegation Guide" icon="link" href="/guides/delegation">
    Learn how to register external wallets
  </Card>

  <Card title="Credit/Reward Withdrawals" icon="money-bill-transfer" href="/guides/wallet/non-custodial#credit-and-reward-wallets">
    Understand how priority affects withdrawals
  </Card>

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