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

# Withdraw from Credit Wallet

> Initiate a withdrawal from credit wallet to external wallet address

## Overview

This endpoint initiates a withdrawal from the authenticated user's credit wallet to their registered external wallet address. The withdrawal is processed on-chain on the Linea network, and the net amount received equals the requested amount minus network gas fees.

**Prerequisites:**

* User must have a registered external wallet (completed delegation flow)
* Credit wallet must have sufficient balance to cover withdrawal amount + fees
* User must be verified and in good standing

**Process Flow:**

1. Check available balance with `GET /v1/wallet/credit`
2. Estimate fees with `GET /v1/wallet/credit/withdraw-estimation`
3. Initiate withdrawal with this endpoint
4. Monitor transaction on blockchain using returned `txHash`
5. Verify completion with `GET /v1/wallet/history`

## Authentication

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

<ParamField header="Authorization" type="string" required>
  Bearer token obtained from OAuth flow or direct login
</ParamField>

## Query Parameters

<ParamField query="x-us-env" type="boolean" default={false}>
  Set to `true` to route request to US backend environment (if available for your client)
</ParamField>

## Request Body

<ParamField body="amount" type="string" required>
  Amount to withdraw in USDC (decimal string). Must not exceed available balance.
</ParamField>

## Response

<ResponseField name="txHash" type="string">
  Blockchain transaction hash of the withdrawal. Use this to track transaction status on the Linea network.
</ResponseField>

<ResponseExample>
  ```json 200 - Success theme={null}
  {
    "txHash": "0xb92de09d893e8162b0861c0f7321f68df02212efbc58f208839ae3f176d89638"
  }
  ```

  ```json 400 - Bad Request theme={null}
  {
    "message": "Insufficient balance"
  }
  ```

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

  ```json 403 - Authorization Error theme={null}
  {
    "message": "Not authorized"
  }
  ```

  ```json 422 - Validation Error theme={null}
  {
    "message": "amount must be a positive number"
  }
  ```

  ```json 500 - Internal Server Error theme={null}
  {
    "message": "Internal server error"
  }
  ```
</ResponseExample>

## Code Examples

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://dev.api.baanx.com/v1/wallet/credit/withdraw" \
    -H "x-client-key: YOUR_CLIENT_KEY" \
    -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
    -H "Content-Type: application/json" \
    -d '{
      "amount": "10.00"
    }'
  ```

  ```python Python theme={null}
  import requests
  from decimal import Decimal

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

  withdrawal_amount = Decimal("10.00")
  data = {
      "amount": str(withdrawal_amount)
  }

  response = requests.post(url, headers=headers, json=data)

  if response.status_code == 200:
      result = response.json()
      tx_hash = result['txHash']
      print(f"Withdrawal initiated!")
      print(f"Transaction hash: {tx_hash}")
      print(f"Track on Linea: https://lineascan.build/tx/{tx_hash}")
  else:
      error = response.json()
      print(f"Error: {error['message']}")
  ```

  ```javascript JavaScript theme={null}
  async function withdrawFromCredit(amount) {
    const response = await fetch(
      'https://dev.api.baanx.com/v1/wallet/credit/withdraw',
      {
        method: 'POST',
        headers: {
          'x-client-key': 'YOUR_CLIENT_KEY',
          'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ amount: amount.toString() })
      }
    );

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message);
    }

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

  try {
    const txHash = await withdrawFromCredit(10.00);
    console.log('Withdrawal successful:', txHash);
  } catch (error) {
    console.error('Withdrawal failed:', error.message);
  }
  ```

  ```typescript TypeScript theme={null}
  interface WithdrawalRequest {
    amount: string;
  }

  interface WithdrawalResponse {
    txHash: string;
  }

  async function withdrawFromCreditWallet(
    amount: string
  ): Promise<string> {
    const response = await fetch(
      'https://dev.api.baanx.com/v1/wallet/credit/withdraw',
      {
        method: 'POST',
        headers: {
          'x-client-key': 'YOUR_CLIENT_KEY',
          'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ amount })
      }
    );

    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message);
    }

    const data: WithdrawalResponse = await response.json();
    return data.txHash;
  }

  const txHash = await withdrawFromCreditWallet('10.00');
  console.log(`Transaction: ${txHash}`);
  ```
</CodeGroup>

## Complete Withdrawal Flow

<Steps>
  <Step title="Check Balance">
    Verify sufficient funds are available

    ```javascript theme={null}
    const wallet = await fetch('/v1/wallet/credit');
    const { balance } = await wallet.json();
    ```
  </Step>

  <Step title="Estimate Fees">
    Get current network fee estimate

    ```javascript theme={null}
    const fees = await fetch('/v1/wallet/credit/withdraw-estimation');
    const { usdc: feeAmount } = await fees.json();
    ```
  </Step>

  <Step title="Calculate Net Amount">
    Show user what they'll receive

    ```javascript theme={null}
    const netAmount = parseFloat(balance) - parseFloat(feeAmount);
    // Display: "You will receive ~${netAmount} USDC"
    ```
  </Step>

  <Step title="Initiate Withdrawal">
    Execute the withdrawal

    ```javascript theme={null}
    const result = await fetch('/v1/wallet/credit/withdraw', {
      method: 'POST',
      body: JSON.stringify({ amount: '10.00' })
    });
    const { txHash } = await result.json();
    ```
  </Step>

  <Step title="Monitor Transaction">
    Track blockchain confirmation

    ```javascript theme={null}
    // Poll blockchain or use webhook
    const txUrl = `https://lineascan.build/tx/${txHash}`;
    // Wait for confirmations (typically 1-3 minutes on Linea)
    ```
  </Step>
</Steps>

## Important Notes

<Warning>
  **Insufficient Balance**: The withdrawal amount plus estimated fees must not exceed available balance. Always validate balance before calling this endpoint.
</Warning>

<Note>
  **Network Fees**: Fees are deducted from the withdrawal amount. If withdrawing 10 USDC with 0.02 USDC fee, user receives 9.98 USDC.
</Note>

<Tip>
  **Transaction Monitoring**: Use the returned `txHash` to track transaction status on Linea block explorer. Typical confirmation time is 1-3 minutes.
</Tip>

## Error Handling

### Common Errors

**Insufficient Balance**

```json theme={null}
{
  "message": "Insufficient balance for withdrawal"
}
```

Solution: Check balance with `GET /v1/wallet/credit` and ensure amount + fees \< balance.

**No External Wallet**

```json theme={null}
{
  "message": "No external wallet registered"
}
```

Solution: User must complete delegation flow to register an external wallet first.

**Invalid Amount**

```json theme={null}
{
  "message": "amount must be a positive number"
}
```

Solution: Validate amount format and ensure it's a positive decimal string.

**Withdrawal Not Allowed**

```json theme={null}
{
  "message": "Withdrawals are not allowed for this wallet"
}
```

Solution: Check `isWithdrawable` flag on `GET /v1/wallet/credit` before attempting withdrawal.

## Edge Cases

### Minimum Withdrawal Amounts

Gas fees make very small withdrawals uneconomical:

```javascript theme={null}
const minViableWithdrawal = 1.00;
if (parseFloat(amount) < minViableWithdrawal) {
  alert('Minimum withdrawal is 1.00 USDC due to network fees');
}
```

### Concurrent Withdrawals

Only one withdrawal can be processed at a time per wallet:

```javascript theme={null}
let withdrawalInProgress = false;

async function safeWithdraw(amount) {
  if (withdrawalInProgress) {
    throw new Error('Withdrawal already in progress');
  }

  withdrawalInProgress = true;
  try {
    return await withdrawFromCredit(amount);
  } finally {
    withdrawalInProgress = false;
  }
}
```

### Network Congestion

During high traffic, transactions may take longer:

* Implement retry logic with exponential backoff
* Display estimated confirmation time to users
* Consider queuing withdrawals for later processing

## Related Endpoints

* [Estimate Credit Withdrawal Fees](/api-reference/wallet/credit-withdraw-estimation) - Calculate fees before withdrawal
* [Get Credit Wallet Balance](/api-reference/wallet/credit) - Check available balance
* [Get External Wallets](/api-reference/wallet/external) - View registered withdrawal destinations
* [Get Wallet History](/api-reference/wallet/history) - Verify withdrawal completion
