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

# Manage External Wallet Priority

> View and update the priority order of external wallets for withdrawals

## Overview

Manage the priority order of registered external wallets. Priority determines the order in which wallets are evaluated for funding transactions. 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 checked first (priority 1 before priority 2).

**Use Cases:**

* Control wallet selection order for transactions
* Optimize for network fees across chains
* Ensure transactions succeed with fallback wallets
* Route withdrawals to specific wallets

***

## GET - Retrieve External Wallet Priority

Get the current priority order of all registered external wallets. Wallets are evaluated in this order for transactions, with the first wallet having sufficient balance to cover the entire transaction cost being used. Only one wallet is used per transaction.

### Authentication

<ParamField header="x-client-key" type="string" required>
  Your public API client key
</ParamField>

<ParamField header="Authorization" type="string" required>
  Bearer token for authentication
</ParamField>

### Response

<ResponseField name="id" type="number">
  Wallet priority identifier
</ResponseField>

<ResponseField name="address" type="string">
  Blockchain wallet address
</ResponseField>

<ResponseField name="currency" type="string">
  Currency code (e.g., "usdc", "usdt")
</ResponseField>

<ResponseField name="network" type="string">
  Blockchain network (e.g., "linea", "ethereum", "solana")
</ResponseField>

<ResponseField name="priority" type="number">
  Current priority value (lower = higher priority)
</ResponseField>

<ResponseExample>
  ```json 200 - Success theme={null}
  [
    {
      "id": 551,
      "address": "0x3a11a86cf218c448be519728cd3ac5c741fb3424",
      "currency": "usdc",
      "network": "linea",
      "priority": 1
    },
    {
      "id": 552,
      "address": "0x7b22c1e6f8a4d92b5c3d8e9f1a2b3c4d5e6f7890",
      "currency": "usdt",
      "network": "ethereum",
      "priority": 2
    },
    {
      "id": 553,
      "address": "DYw8jCTfwHNRJhhmFcbXvVDTqWMEVFBX6ZKUmG5CNSKK",
      "currency": "usdc",
      "network": "solana",
      "priority": 3
    }
  ]
  ```
</ResponseExample>

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://dev.api.baanx.com/v1/wallet/external/priority" \
    -H "x-client-key: YOUR_CLIENT_KEY" \
    -H "Authorization: Bearer YOUR_ACCESS_TOKEN"
  ```

  ```python Python theme={null}
  import requests

  url = "https://dev.api.baanx.com/v1/wallet/external/priority"
  headers = {
      "x-client-key": "YOUR_CLIENT_KEY",
      "Authorization": "Bearer YOUR_ACCESS_TOKEN"
  }

  response = requests.get(url, headers=headers)
  priorities = response.json()

  print("Withdrawal Priority Order:")
  for wallet in sorted(priorities, key=lambda w: w['priority']):
      print(f"{wallet['priority']}. {wallet['currency'].upper()} on {wallet['network']} - {wallet['address'][:10]}...")
  ```

  ```typescript TypeScript theme={null}
  interface WalletPriority {
    id: number;
    address: string;
    currency: string;
    network: string;
    priority: number;
  }

  async function getExternalWalletPriority(): Promise<WalletPriority[]> {
    const response = await fetch(
      'https://dev.api.baanx.com/v1/wallet/external/priority',
      {
        headers: {
          'x-client-key': 'YOUR_CLIENT_KEY',
          'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
        }
      }
    );

    return await response.json();
  }

  const priorities = await getExternalWalletPriority();
  const ordered = priorities.sort((a, b) => a.priority - b.priority);
  console.log('Withdrawal order:', ordered.map(w => w.network));
  ```
</CodeGroup>

***

## PUT - Update External Wallet Priority

Update the priority order of external wallets for transaction funding. When a transaction is initiated, wallets are checked sequentially in this order until one with sufficient balance is found to fund the entire transaction. Only one wallet funds each transaction - partial funding from multiple wallets is not supported.

### Request Body

<ParamField body="wallets" type="array" required>
  Array of wallet priority updates

  <Expandable title="Wallet Priority Object">
    <ParamField body="id" type="number" required>
      Wallet priority ID from GET response
    </ParamField>

    <ParamField body="priority" type="number" required>
      New priority value (lower numbers = higher priority)
    </ParamField>
  </Expandable>
</ParamField>

### Response

<ResponseField name="success" type="boolean">
  Whether priority update was successful
</ResponseField>

<ResponseExample>
  ```json 200 - Success theme={null}
  {
    "success": true
  }
  ```

  ```json 401 - Authentication Error theme={null}
  {
    "message": "Not authenticated"
  }
  ```

  ```json 422 - Validation Error theme={null}
  {
    "message": "Invalid priority configuration"
  }
  ```
</ResponseExample>

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

  ```python Python theme={null}
  import requests

  url = "https://dev.api.baanx.com/v1/wallet/external/priority"
  headers = {
      "x-client-key": "YOUR_CLIENT_KEY",
      "Authorization": "Bearer YOUR_ACCESS_TOKEN",
      "Content-Type": "application/json"
  }

  current = requests.get(url, headers=headers).json()

  updated_priorities = []
  for index, wallet in enumerate(current):
      updated_priorities.append({
          "id": wallet['id'],
          "priority": index + 1
      })

  data = {"wallets": updated_priorities}
  response = requests.put(url, headers=headers, json=data)

  if response.status_code == 200:
      print("Priority updated successfully!")
  ```

  ```typescript TypeScript theme={null}
  async function updateExternalWalletPriority(
    priorities: Array<{ id: number; priority: number }>
  ): Promise<boolean> {
    const response = await fetch(
      'https://dev.api.baanx.com/v1/wallet/external/priority',
      {
        method: 'PUT',
        headers: {
          'x-client-key': 'YOUR_CLIENT_KEY',
          'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ wallets: priorities })
      }
    );

    const result = await response.json();
    return result.success;
  }

  await updateExternalWalletPriority([
    { id: 552, priority: 1 },
    { id: 551, priority: 2 }
  ]);
  ```
</CodeGroup>

***

## Use Cases

### Prioritize Low-Fee Networks

```javascript theme={null}
async function prioritizeByFees() {
  const wallets = await fetch('/v1/wallet/external/priority')
    .then(r => r.json());

  const feeTiers = {
    'linea': 1,
    'polygon': 2,
    'ethereum': 3
  };

  const reordered = wallets
    .sort((a, b) => (feeTiers[a.network] || 99) - (feeTiers[b.network] || 99))
    .map((w, index) => ({
      id: w.id,
      priority: index + 1
    }));

  await updateExternalWalletPriority(reordered);
  console.log('Prioritized wallets by lowest network fees');
}
```

### Move Specific Wallet to Top

```javascript theme={null}
async function moveWalletToTop(targetAddress) {
  const wallets = await fetch('/v1/wallet/external/priority')
    .then(r => r.json());

  const target = wallets.find(w => w.address === targetAddress);

  if (!target) {
    throw new Error('Wallet not found');
  }

  const priorities = [
    { id: target.id, priority: 1 },
    ...wallets
      .filter(w => w.id !== target.id)
      .map((w, index) => ({ id: w.id, priority: index + 2 }))
  ];

  await updateExternalWalletPriority(priorities);
}

await moveWalletToTop('0x3a11a86cf218c448be519728cd3ac5c741fb3424');
```

### Swap Two Wallet Priorities

```javascript theme={null}
async function swapPriorities(walletId1, walletId2) {
  const wallets = await fetch('/v1/wallet/external/priority')
    .then(r => r.json());

  const wallet1 = wallets.find(w => w.id === walletId1);
  const wallet2 = wallets.find(w => w.id === walletId2);

  const updates = wallets.map(w => ({
    id: w.id,
    priority:
      w.id === walletId1 ? wallet2.priority :
      w.id === walletId2 ? wallet1.priority :
      w.priority
  }));

  await updateExternalWalletPriority(updates);
}

await swapPriorities(551, 552);
```

### Currency-Based Priority

```javascript theme={null}
async function prioritizeByCurrency() {
  const wallets = await fetch('/v1/wallet/external/priority')
    .then(r => r.json());

  const currencyRanking = ['usdc', 'usdt', 'dai'];

  const reordered = wallets
    .sort((a, b) => {
      const rankA = currencyRanking.indexOf(a.currency);
      const rankB = currencyRanking.indexOf(b.currency);
      return (rankA === -1 ? 999 : rankA) - (rankB === -1 ? 999 : rankB);
    })
    .map((w, index) => ({
      id: w.id,
      priority: index + 1
    }));

  await updateExternalWalletPriority(reordered);
}
```

## Important Notes

<Warning>
  **Single-Wallet Funding**: Only ONE wallet funds each transaction. The platform checks wallets in priority order and uses the first one 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>

<Note>
  **Update All Wallets**: You must provide priority values for ALL registered external wallets. Partial updates may result in unexpected behavior.
</Note>

<Warning>
  **Unique Priorities**: Each wallet must have a unique priority value. Duplicate priorities will cause validation errors.
</Warning>

<Tip>
  **Transaction Failure**: If ALL priority wallets have insufficient balance to cover the full transaction cost, the transaction will fail. Ensure at least one wallet always has adequate funds.
</Tip>

## Priority Strategy Examples

### Balanced Approach

```javascript theme={null}
const strategies = {
  balanced: (wallets) => {
    return wallets
      .sort((a, b) => {
        if (a.network === 'linea') return -1;
        if (b.network === 'linea') return 1;
        return a.currency.localeCompare(b.currency);
      })
      .map((w, i) => ({ id: w.id, priority: i + 1 }));
  },

  singlePreferred: (wallets, preferredAddress) => {
    const preferred = wallets.find(w => w.address === preferredAddress);
    return [
      { id: preferred.id, priority: 1 },
      ...wallets
        .filter(w => w.id !== preferred.id)
        .map((w, i) => ({ id: w.id, priority: i + 2 }))
    ];
  },

  networkFirst: (wallets, preferredNetwork) => {
    return wallets
      .sort((a, b) => {
        if (a.network === preferredNetwork && b.network !== preferredNetwork) return -1;
        if (b.network === preferredNetwork && a.network !== preferredNetwork) return 1;
        return 0;
      })
      .map((w, i) => ({ id: w.id, priority: i + 1 }));
  }
};

const wallets = await getExternalWalletPriority();
const newPriorities = strategies.balanced(wallets);
await updateExternalWalletPriority(newPriorities);
```

## Edge Cases

### Single Wallet

With only one wallet, priority is always 1:

```javascript theme={null}
if (wallets.length === 1) {
  console.log('Only one wallet - priority management not applicable');
}
```

### Validation Before Update

```javascript theme={null}
function validatePriorityUpdate(updates) {
  const priorities = updates.map(u => u.priority);
  const ids = updates.map(u => u.id);

  if (new Set(priorities).size !== priorities.length) {
    throw new Error('Duplicate priority values not allowed');
  }

  if (new Set(ids).size !== ids.length) {
    throw new Error('Duplicate wallet IDs not allowed');
  }

  const maxPriority = Math.max(...priorities);
  if (maxPriority > updates.length) {
    console.warn('Priority gaps detected');
  }

  return true;
}
```

## Related Endpoints

* [Get External Wallets](/api-reference/wallet/external) - View all registered external wallets
* [Withdraw from Credit Wallet](/api-reference/wallet/credit-withdraw) - Withdrawal to priority 1 external wallet (if sufficient balance)
* [Withdraw from Reward Wallet](/api-reference/wallet/reward-withdraw) - Withdrawal to priority 1 external wallet (if sufficient balance)
