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

# Generate Delegation Token

> Generate a single-use token to initiate wallet delegation (Step 1 of 3)

## Overview

This endpoint generates a single-use delegation token required to initiate the wallet delegation flow. This is **Step 1** of a 3-step process that allows users to delegate spending authority from their non-custodial wallets to the platform for card payments.

<Note>
  **When to Use**: Call this endpoint when a user initiates the delegation flow in your application. The returned token is required to finalize delegation in Step 3 after the user completes wallet connection and blockchain approval.
</Note>

## Delegation Workflow

The complete delegation process involves three steps:

1. **Backend (This Endpoint)**: Request delegation token from API
2. **Frontend (Your Implementation)**: User connects wallet and approves blockchain transaction
3. **Backend**: Submit delegation proof using blockchain-specific endpoint:
   * `POST /v1/delegation/evm/post-approval` for EVM chains (Linea/Ethereum)
   * `POST /v1/delegation/solana/post-approval` for Solana

See the [Delegation Guide](/guides/delegation/implementation) for complete implementation details.

## Authentication

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

<ParamField header="Authorization" type="string" required>
  Bearer token format: `Bearer {access_token}`
</ParamField>

## Query Parameters

<ParamField query="region" type="string">
  Region identifier for environment routing. Use `us` for US-specific Linea routing.

  **Example**: `?region=us`
</ParamField>

<Note>
  Alternatively, you can use the `x-us-env: true` header instead of the region query parameter.
</Note>

## Response

<ResponseField name="token" type="string" required>
  Single-use delegation token (UUID format). This token is used in Step 3 to finalize the delegation.

  **Characteristics:**

  * Single-use only - becomes invalid after use in POST approval endpoint
  * \~10 minute lifetime - complete the delegation flow before expiration
  * Must be passed to your frontend for use after wallet connection
</ResponseField>

<ResponseField name="nonce" type="string" required>
  Unique nonce that must be included in the post-approval request. This nonce links the delegation token request to the final approval submission.

  **Example**: `5f8a9b2c4d3e1a7b9c6d8e2f`

  **Important**: Store this nonce alongside the token and pass both to your frontend. Both values are required when submitting the delegation proof in Step 3.
</ResponseField>

<RequestExample>
  ```bash cURL theme={null}
  curl --request GET \
    --url 'https://dev.api.baanx.com/v1/delegation/token' \
    --header 'x-client-key: YOUR_PUBLIC_KEY' \
    --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
  ```

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

  url = "https://dev.api.baanx.com/v1/delegation/token"

  headers = {
      "x-client-key": "YOUR_PUBLIC_KEY",
      "Authorization": "Bearer YOUR_ACCESS_TOKEN"
  }

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

  print(f"Delegation token: {data['token']}")
  print(f"Nonce: {data['nonce']}")
  ```

  ```javascript JavaScript theme={null}
  const url = 'https://dev.api.baanx.com/v1/delegation/token';

  const response = await fetch(url, {
    method: 'GET',
    headers: {
      'x-client-key': 'YOUR_PUBLIC_KEY',
      'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
    }
  });

  const data = await response.json();
  console.log('Delegation token:', data.token);
  ```

  ```typescript TypeScript theme={null}
  interface DelegationTokenResponse {
    token: string;
    nonce: string;
  }

  const url = 'https://dev.api.baanx.com/v1/delegation/token';

  const response = await fetch(url, {
    method: 'GET',
    headers: {
      'x-client-key': 'YOUR_PUBLIC_KEY',
      'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
    }
  });

  const data: DelegationTokenResponse = await response.json();
  console.log('Delegation token:', data.token);
  console.log('Nonce:', data.nonce);
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success theme={null}
  {
    "token": "100a99cf-f4d3-4fa1-9be9-2e9828b20ebc",
    "nonce": "5f8a9b2c4d3e1a7b9c6d8e2f"
  }
  ```

  ```json 401 Unauthorized theme={null}
  {
    "message": "Invalid or expired access token"
  }
  ```

  ```json 422 Validation Error theme={null}
  {
    "message": "Validation failed",
    "errors": [
      {
        "field": "region",
        "message": "Invalid region identifier"
      }
    ]
  }
  ```

  ```json 500 Internal Server Error theme={null}
  {
    "message": "An unexpected error occurred. Please try again later."
  }
  ```
</ResponseExample>

## Response Codes

| Code | Description                                             |
| ---- | ------------------------------------------------------- |
| 200  | Delegation token generated successfully                 |
| 401  | Authentication failed - invalid or expired access token |
| 422  | Validation error - invalid request parameters           |
| 498  | Invalid client key                                      |
| 499  | Missing client key                                      |
| 500  | Internal server error                                   |

## Next Steps

After receiving the delegation token:

1. **Store the token temporarily** in your application state or session
2. **Pass it to your frontend** where the user will connect their wallet
3. **Proceed to Step 2** - implement wallet connection UI (MetaMask, WalletConnect, Phantom, etc.)
4. **Complete Step 3** - submit delegation proof to the appropriate endpoint:
   * [POST /v1/delegation/evm/post-approval](/api-reference/delegation/evm-post-approval) for EVM chains
   * [POST /v1/delegation/solana/post-approval](/api-reference/delegation/solana-post-approval) for Solana

## Token Characteristics

<Warning>
  **Important Token Properties:**

  * **Single-Use**: The token becomes invalid after successful use in Step 3
  * **10 Minute Expiry**: Complete the entire delegation flow within this timeframe
  * **UUID Format**: Token follows standard UUID v4 format
  * **Non-Renewable**: If expired, generate a new token by calling this endpoint again
</Warning>

## Implementation Example

Here's a complete backend flow example:

```python Python Backend Flow theme={null}
import requests
from typing import Dict

def initiate_delegation(user_access_token: str) -> Dict[str, str]:
    url = "https://dev.api.baanx.com/v1/delegation/token"

    headers = {
        "x-client-key": "YOUR_PUBLIC_KEY",
        "Authorization": f"Bearer {user_access_token}"
    }

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

    if response.status_code == 200:
        data = response.json()
        delegation_token = data["token"]
        nonce = data["nonce"]

        # Store both token and nonce temporarily (e.g., in session, cache, or database)
        # Pass both values to your frontend for Step 2
        return {
            "success": True,
            "token": delegation_token,
            "nonce": nonce
        }
    else:
        return {
            "success": False,
            "error": response.json().get("message", "Failed to generate token")
        }

# Usage
result = initiate_delegation(user_access_token="user_token_here")
if result["success"]:
    print(f"Send these to frontend - Token: {result['token']}, Nonce: {result['nonce']}")
else:
    print(f"Error: {result['error']}")
```

## Common Error Scenarios

### Token Expiration

If the user takes longer than 10 minutes to complete the wallet connection and approval:

```json theme={null}
{
  "message": "Delegation token has expired"
}
```

**Solution**: Generate a new token by calling this endpoint again.

### Invalid Access Token

If the user's access token is invalid or expired:

```json theme={null}
{
  "message": "Invalid or expired access token"
}
```

**Solution**: Refresh the user's access token using the OAuth refresh token flow.

### Missing Authentication

If required headers are missing:

```json theme={null}
{
  "message": "Missing required header: Authorization"
}
```

**Solution**: Ensure both `x-client-key` and `Authorization` headers are included.

## Best Practices

<Accordion title="Security Considerations">
  * **Never expose tokens to client-side logging** - delegation tokens should be handled securely
  * **Use HTTPS only** - all API communication must be encrypted
  * **Implement token cleanup** - clear expired tokens from your storage
  * **Validate token format** - ensure received token is a valid UUID before passing to frontend
</Accordion>

<Accordion title="Error Handling">
  * **Implement retry logic** with exponential backoff for network failures
  * **Handle token expiration gracefully** - inform users they need to restart the flow
  * **Provide clear user feedback** - explain why delegation failed and next steps
  * **Log errors appropriately** - track failures for debugging without exposing sensitive data
</Accordion>

<Accordion title="User Experience">
  * **Display progress indicators** - show users they're on Step 1 of 3
  * **Set user expectations** - inform users about the \~10 minute time limit
  * **Provide help documentation** - link to guides explaining the delegation process
  * **Enable easy restart** - if token expires, make it simple to generate a new one
</Accordion>

## Related Endpoints

* [POST /v1/delegation/evm/post-approval](/api-reference/delegation/evm-post-approval) - Complete EVM wallet delegation (Step 3)
* [POST /v1/delegation/solana/post-approval](/api-reference/delegation/solana-post-approval) - Complete Solana wallet delegation (Step 3)
* [GET /v1/wallet/external](/api-reference/wallet/external) - List delegated wallets
* [Manage External Wallet Priority](/api-reference/wallet/external-priority) - Get and update wallet priority order

## Further Reading

* [Delegation Overview](/guides/delegation/overview) - Understand delegation concepts
* [Implementation Guide](/guides/delegation/implementation) - Complete integration walkthrough
* [EVM Chains](/guides/delegation/evm-chains) - EVM-specific implementation details
* [Solana](/guides/delegation/solana) - Solana-specific implementation details
