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

# Get Blockchain Configuration

> Retrieve blockchain network configuration including chain IDs, token contract addresses, and spender addresses required for wallet delegation

## Overview

This endpoint retrieves blockchain network configuration required to implement wallet delegation in your frontend application. Use this data before initiating the delegation flow to get the correct contract addresses and chain IDs for the user's selected network.

<Note>
  **When to Use**: Call this endpoint before Step 2 of the delegation workflow to get the correct contract addresses, chain IDs, and spender addresses for building approval transactions in the user's wallet provider.
</Note>

## What You'll Get

* **Chain IDs** for each supported network (Linea, Ethereum)
* **Token contract addresses** (USDC, USDT) for each network
* **Platform spender addresses** that users will approve for token spending
* **Network-specific configuration** for building approval transactions
* **Solana token mint addresses** and delegate address

## Use Case

Use this configuration data in your frontend (Step 2 of delegation) to construct the correct approval transaction with the right contract addresses and chain ID for the user's wallet provider.

## 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="network" type="string">
  Filter by network name to get configuration for a specific blockchain network.

  **Supported values**: `ethereum`, `linea`, `solana`, `etherlink`

  **Example**: `?network=ethereum`

  **Note**: If not specified, returns configuration for all supported networks.
</ParamField>

<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="networks" type="array" required>
  Array of network configurations matching the query filters

  <Expandable title="Network Configuration Object">
    <ResponseField name="network" type="string" required>
      Network identifier

      **Example**: `ethereum`, `linea`, `solana`
    </ResponseField>

    <ResponseField name="environment" type="string" required>
      Deployment environment

      **Example**: `production`, `staging`, `development`
    </ResponseField>

    <ResponseField name="chainId" type="string" required>
      Blockchain chain ID (as string to support large numbers)

      **Example**: `"1"` (Ethereum), `"59144"` (Linea)
    </ResponseField>

    <ResponseField name="delegationContract" type="string" required>
      Delegation smart contract address

      **Example**: `0xb453ba76d9ca952115e9e32ca069c96e846c5d9d`
    </ResponseField>

    <ResponseField name="tokens" type="object" required>
      Map of token symbol to token configuration

      <Expandable title="Token Configuration">
        <ResponseField name="symbol" type="string" required>
          Token symbol

          **Example**: `usdc`, `usdt`, `musd`
        </ResponseField>

        <ResponseField name="decimals" type="integer" required>
          Number of decimal places for the token

          **Example**: `6` (USDC/USDT), `18` (ETH)
        </ResponseField>

        <ResponseField name="address" type="string" required>
          Token contract address

          **Example**: `0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48`
        </ResponseField>
      </Expandable>
    </ResponseField>
  </Expandable>
</ResponseField>

<ResponseField name="count" type="integer" required>
  Number of networks returned in the response

  **Example**: `1` (when filtering by network), `3` (when getting all networks)
</ResponseField>

<ResponseField name="_links" type="object" required>
  HATEOAS links for API navigation

  <Expandable title="Links Object">
    <ResponseField name="self" type="string" required>
      Current request URL path and query parameters

      **Example**: `/v1/delegation/chain/config?network=ethereum`
    </ResponseField>
  </Expandable>
</ResponseField>

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

  ```bash cURL - Filter by Network theme={null}
  curl --request GET \
    --url 'https://dev.api.baanx.com/v1/delegation/chain/config?network=ethereum' \
    --header 'x-client-key: YOUR_PUBLIC_KEY' \
    --header 'Authorization: Bearer YOUR_ACCESS_TOKEN'
  ```

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

  # Get all networks
  url = "https://dev.api.baanx.com/v1/delegation/chain/config"
  headers = {
      "x-client-key": "YOUR_PUBLIC_KEY",
      "Authorization": "Bearer YOUR_ACCESS_TOKEN"
  }

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

  # Access network configurations
  for network in config['networks']:
      print(f"Network: {network['network']}")
      print(f"Chain ID: {network['chainId']}")
      print(f"Delegation Contract: {network['delegationContract']}")
      for symbol, token in network['tokens'].items():
          print(f"  {symbol.upper()}: {token['address']}")

  # Get specific network
  response = requests.get(url, params={"network": "ethereum"}, headers=headers)
  ethereumConfig = response.json()['networks'][0]
  print(f"Ethereum USDC: {ethereumConfig['tokens']['usdc']['address']}")
  ```

  ```javascript JavaScript theme={null}
  // Get all networks
  const url = 'https://dev.api.baanx.com/v1/delegation/chain/config';

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

  const config = await response.json();
  console.log(`Found ${config.count} networks`);

  // Find specific network
  const ethereum = config.networks.find(n => n.network === 'ethereum');
  if (ethereum) {
    console.log('Ethereum USDC:', ethereum.tokens.usdc.address);
  }

  // Get specific network directly
  const ethResponse = await fetch(`${url}?network=ethereum`, {
    method: 'GET',
    headers: {
      'x-client-key': 'YOUR_PUBLIC_KEY',
      'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
    }
  });
  const ethConfig = await ethResponse.json();
  console.log('Ethereum config:', ethConfig.networks[0]);
  ```

  ```typescript TypeScript theme={null}
  interface TokenConfig {
    symbol: string;
    decimals: number;
    address: string;
  }

  interface NetworkConfig {
    network: string;
    environment: string;
    chainId: string;
    delegationContract: string;
    tokens: Record<string, TokenConfig>;
  }

  interface ChainConfigResponse {
    networks: NetworkConfig[];
    count: number;
    _links: {
      self: string;
    };
  }

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

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

  const config: ChainConfigResponse = await response.json();
  console.log(`Loaded ${config.count} networks`);

  // Filter by network
  const lineaResponse = await fetch(`${url}?network=linea`, {
    method: 'GET',
    headers: {
      'x-client-key': 'YOUR_PUBLIC_KEY',
      'Authorization': 'Bearer YOUR_ACCESS_TOKEN'
    }
  });

  const lineaConfig: ChainConfigResponse = await lineaResponse.json();
  const linea = lineaConfig.networks[0];
  console.log('Linea Chain ID:', linea.chainId);
  console.log('Linea USDC:', linea.tokens.usdc.address);
  ```
</RequestExample>

<ResponseExample>
  ```json 200 Success - All Networks theme={null}
  {
    "networks": [
      {
        "network": "ethereum",
        "environment": "production",
        "chainId": "1",
        "delegationContract": "0xb453ba76d9ca952115e9e32ca069c96e846c5d9d",
        "tokens": {
          "usdc": {
            "symbol": "usdc",
            "decimals": 6,
            "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
          },
          "usdt": {
            "symbol": "usdt",
            "decimals": 6,
            "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7"
          }
        }
      },
      {
        "network": "linea",
        "environment": "production",
        "chainId": "59144",
        "delegationContract": "0x9dd23A4a0845f10d65D293776B792af1131c7B30",
        "tokens": {
          "usdc": {
            "symbol": "usdc",
            "decimals": 6,
            "address": "0x176211869ca2b568f2a7d4ee941e073a821ee1ff"
          },
          "usdt": {
            "symbol": "usdt",
            "decimals": 6,
            "address": "0xa219439258ca9da29e9cc4ce5596924745e12b93"
          }
        }
      }
    ],
    "count": 2,
    "_links": {
      "self": "/v1/delegation/chain/config"
    }
  }
  ```

  ```json 200 Success - Single Network (?network=ethereum) theme={null}
  {
    "networks": [
      {
        "network": "ethereum",
        "environment": "production",
        "chainId": "1",
        "delegationContract": "0xb453ba76d9ca952115e9e32ca069c96e846c5d9d",
        "tokens": {
          "usdc": {
            "symbol": "usdc",
            "decimals": 6,
            "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48"
          },
          "usdt": {
            "symbol": "usdt",
            "decimals": 6,
            "address": "0xdAC17F958D2ee523a2206206994597C13D831ec7"
          }
        }
      }
    ],
    "count": 1,
    "_links": {
      "self": "/v1/delegation/chain/config?network=ethereum"
    }
  }
  ```

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

  ```json 403 Forbidden theme={null}
  {
    "message": "Insufficient permissions to access blockchain configuration"
  }
  ```

  ```json 404 Not Found theme={null}
  {
    "error": "No networks found",
    "message": "Network 'polygon' not found for environment 'production'"
  }
  ```

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

## Response Codes

| Code | Description                                             |
| ---- | ------------------------------------------------------- |
| 200  | Blockchain configuration retrieved successfully         |
| 401  | Authentication failed - invalid or expired access token |
| 403  | Authorization failed - insufficient permissions         |
| 404  | No networks found for the specified filters             |
| 498  | Invalid client key                                      |
| 499  | Missing client key                                      |
| 500  | Internal server error                                   |

## Implementation Example

Here's how to use this endpoint in a complete delegation workflow:

```typescript TypeScript Implementation theme={null}
interface ChainConfig {
  linea: NetworkConfig;
  ethereum: NetworkConfig;
  solana: SolanaConfig;
}

interface NetworkConfig {
  chain_id: number;
  usdc_address: string;
  usdt_address: string;
  spender_address: string;
}

interface SolanaConfig {
  usdc_mint: string;
  usdt_mint: string;
  delegate_address: string;
}

async function loadBlockchainConfig(accessToken: string): Promise<ChainConfig> {
  const response = await fetch('https://dev.api.baanx.com/v1/delegation/chain/config', {
    method: 'GET',
    headers: {
      'x-client-key': 'YOUR_PUBLIC_KEY',
      'Authorization': `Bearer ${accessToken}`
    }
  });

  if (!response.ok) {
    throw new Error(`Failed to load config: ${response.status}`);
  }

  return await response.json();
}

// Usage in delegation workflow
async function initiateDelegation(
  network: 'linea' | 'ethereum' | 'solana',
  currency: 'usdc' | 'usdt',
  amount: string
) {
  // Step 0: Get blockchain configuration
  const config = await loadBlockchainConfig(userAccessToken);

  if (network === 'solana') {
    // Use Solana configuration
    const mintAddress = currency === 'usdc' 
      ? config.solana.usdc_mint 
      : config.solana.usdt_mint;
    const delegateAddress = config.solana.delegate_address;
    
    // Proceed with Solana delegation logic...
  } else {
    // Use EVM configuration
    const networkConfig = config[network];
    const tokenAddress = currency === 'usdc' 
      ? networkConfig.usdc_address 
      : networkConfig.usdt_address;
    const spenderAddress = networkConfig.spender_address;
    const chainId = networkConfig.chain_id;
    
    // Proceed with EVM delegation logic...
    await approveTokenSpending(tokenAddress, spenderAddress, amount, chainId);
  }
}

async function approveTokenSpending(
  tokenAddress: string,
  spenderAddress: string,
  amount: string,
  chainId: number
) {
  // Verify user's wallet is on correct network
  const currentNetwork = await provider.getNetwork();
  if (currentNetwork.chainId !== chainId) {
    throw new Error(`Please switch to chain ID ${chainId}`);
  }

  // Create approval transaction using configuration
  const tokenContract = new ethers.Contract(tokenAddress, ERC20_ABI, signer);
  const tx = await tokenContract.approve(
    spenderAddress,
    ethers.utils.parseUnits(amount, 6) // Assuming 6 decimals for USDC/USDT
  );

  return await tx.wait();
}
```

## Security Best Practices

<Accordion title="Address Validation">
  * **Always verify contract addresses** - Compare received addresses against known good addresses
  * **Validate address format** - Ensure EVM addresses start with `0x` and are 42 characters long
  * **Check network compatibility** - Verify addresses match the intended blockchain network
  * **Use checksummed addresses** - Apply EIP-55 checksum validation for Ethereum addresses
</Accordion>

<Accordion title="Configuration Caching">
  * **Cache configuration temporarily** - Avoid repeated API calls during user session
  * **Implement cache invalidation** - Refresh configuration periodically or when errors occur
  * **Handle network-specific configs** - Store separate configurations for different networks
  * **Validate before use** - Always verify cached configuration is still valid
</Accordion>

<Accordion title="Error Handling">
  * **Handle network failures gracefully** - Implement retry logic with exponential backoff
  * **Provide fallback mechanisms** - Have backup methods if configuration loading fails
  * **Log configuration issues** - Track when configuration retrieval fails for debugging
  * **User-friendly error messages** - Explain clearly when configuration cannot be loaded
</Accordion>

## Common Use Cases

### Multi-Network Support

Configure your application to support multiple blockchain networks:

```typescript TypeScript Multi-Network theme={null}
class DelegationManager {
  private config: ChainConfig | null = null;

  async initialize(accessToken: string) {
    this.config = await loadBlockchainConfig(accessToken);
  }

  getNetworkOptions() {
    if (!this.config) throw new Error('Configuration not loaded');
    
    return [
      {
        name: 'Linea',
        chainId: this.config.linea.chain_id,
        currencies: ['USDC', 'USDT']
      },
      {
        name: 'Ethereum',
        chainId: this.config.ethereum.chain_id,
        currencies: ['USDC', 'USDT']
      },
      {
        name: 'Solana',
        currencies: ['USDC', 'USDT']
      }
    ];
  }

  getContractAddress(network: string, currency: string): string {
    if (!this.config) throw new Error('Configuration not loaded');
    
    const networkConfig = this.config[network as keyof ChainConfig];
    if (!networkConfig) throw new Error(`Unsupported network: ${network}`);
    
    if (network === 'solana') {
      const solanaConfig = networkConfig as SolanaConfig;
      return currency === 'usdc' ? solanaConfig.usdc_mint : solanaConfig.usdt_mint;
    } else {
      const evmConfig = networkConfig as NetworkConfig;
      return currency === 'usdc' ? evmConfig.usdc_address : evmConfig.usdt_address;
    }
  }
}
```

### Configuration Validation

Validate configuration data before using in transactions:

```javascript JavaScript Validation theme={null}
function validateChainConfig(config) {
  const requiredFields = {
    linea: ['chain_id', 'usdc_address', 'usdt_address', 'spender_address'],
    ethereum: ['chain_id', 'usdc_address', 'usdt_address', 'spender_address'],
    solana: ['usdc_mint', 'usdt_mint', 'delegate_address']
  };

  for (const [network, fields] of Object.entries(requiredFields)) {
    if (!config[network]) {
      throw new Error(`Missing ${network} configuration`);
    }

    for (const field of fields) {
      if (!config[network][field]) {
        throw new Error(`Missing ${field} in ${network} configuration`);
      }
    }
  }

  // Validate address formats
  const evmAddressRegex = /^0x[a-fA-F0-9]{40}$/;
  if (!evmAddressRegex.test(config.linea.usdc_address)) {
    throw new Error('Invalid Linea USDC address format');
  }

  return true;
}
```

## Related Endpoints

* [GET /v1/delegation/token](/api-reference/delegation/token) - Generate delegation token (Step 1)
* [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

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