> ## Documentation Index
> Fetch the complete documentation index at: https://devdraft.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Stablecoin Conversion

> Convert between different stablecoins and networks using Devdraft's cross-chain infrastructure

The Stablecoin Conversion endpoint enables you to convert between different stablecoins across various blockchain networks. This endpoint handles cross-chain conversions, currency exchanges, and network transfers seamlessly through Devdraft's unified infrastructure.

## Endpoint Details

* **Method:** `POST`
* **URL:** `/api/v0/transfers/stablecoin-conversion`
* **Content-Type:** `application/json`

## Authentication

This endpoint requires API key authentication using both:

* `x-client-key`: Your application's client key
* `x-client-secret`: Your application's client secret

## Request Body

<CodeGroup>
  ```json Request theme={null}
  {
    "sourceWalletId": "550e8400-e29b-41d4-a716-446655440000",
    "destinationWalletId": "660f9500-f30c-52e5-b827-557766551111",
    "sourceNetwork": "ethereum",
    "destinationNetwork": "solana",
    "sourceCurrency": "usdc",
    "destinationCurrency": "usdc",
    "amount": 1000.50
  }
  ```
</CodeGroup>

### Parameters

| Parameter           | Type   | Required | Description                       |
| ------------------- | ------ | -------- | --------------------------------- |
| sourceWalletId      | string | Yes      | The ID of your source wallet      |
| destinationWalletId | string | Yes      | The ID of your destination wallet |
| sourceNetwork       | string | Yes      | Source blockchain network         |
| destinationNetwork  | string | Yes      | Destination blockchain network    |
| sourceCurrency      | string | Yes      | Source stablecoin currency        |
| destinationCurrency | string | Yes      | Destination stablecoin currency   |
| amount              | number | Yes      | Amount to convert                 |

### Supported Networks

* **Ethereum** (`ethereum`)
* **Solana** (`solana`)
* **Base** (`base`)
* **Polygon** (`polygon`)
* **Arbitrum** (`arbitrum`)
* **Optimism** (`optimism`)
* **Avalanche C-Chain** (`avalanche_c_chain`)

### Supported Stablecoins

* **USDC** (`usdc`) - Available on all networks
* **EURC** (`eurc`) - Available on Ethereum, Solana
* **USDT** (`usdt`) - Available on Ethereum, Polygon, Avalanche

### Conversion Types

<Tabs>
  <Tab title="Same Currency, Different Network">
    Convert USDC from Ethereum to USDC on Solana

    * Fastest conversion type
    * Minimal fees
    * No currency exchange rate risk
  </Tab>

  <Tab title="Different Currency, Same Network">
    Convert USDC to EURC on Ethereum

    * Currency exchange applied
    * Current market rates
    * Single network transaction
  </Tab>

  <Tab title="Different Currency, Different Network">
    Convert USDC on Ethereum to EURC on Solana

    * Cross-chain + currency conversion
    * Highest complexity
    * Market rates + network fees
  </Tab>
</Tabs>

## Response

### Success Response (201 Created)

<CodeGroup>
  ```json Response theme={null}
  {
    "id": "tc_1234567890abcdef",
    "state": "processing",
    "conversion_type": "cross_chain_conversion",
    "source": {
      "wallet_id": "550e8400-e29b-41d4-a716-446655440000",
      "network": "ethereum",
      "currency": "usdc",
      "amount": "1000.50",
      "address": "0x742d35Cc6Ff82a8C2D8D1Da9da17c7eDfD5bE0a3"
    },
    "destination": {
      "wallet_id": "660f9500-f30c-52e5-b827-557766551111",
      "network": "solana",
      "currency": "usdc",
      "estimated_amount": "998.75",
      "address": "7xKXKRoBrJgCXVb2KhxZZzPHxYMJ4DpHWGQ8RvxS6JEq"
    },
    "exchange_rate": {
      "rate": "1.0000",
      "source_currency": "usdc",
      "destination_currency": "usdc",
      "rate_expires_at": "2024-01-20T10:35:00Z"
    },
    "fees": {
      "network_fee_source": "2.50",
      "network_fee_destination": "0.01",
      "conversion_fee": "0.8",
      "developer_fee": "8.00",
      "total_fees": "11.31"
    },
    "estimated_completion": "2024-01-20T10:33:00Z",
    "transaction_hashes": {
      "source_tx": null,
      "destination_tx": null
    },
    "created_at": "2024-01-20T10:30:00Z",
    "updated_at": "2024-01-20T10:30:00Z"
  }
  ```
</CodeGroup>

### Response Fields

| Field                 | Type   | Description                                      |
| --------------------- | ------ | ------------------------------------------------ |
| id                    | string | Unique conversion identifier                     |
| state                 | string | Conversion state (processing, completed, failed) |
| conversion\_type      | string | Type of conversion being performed               |
| source                | object | Source wallet and transaction details            |
| destination           | object | Destination wallet and estimated amounts         |
| exchange\_rate        | object | Current exchange rate information                |
| fees                  | object | Breakdown of all fees                            |
| estimated\_completion | string | Estimated completion timestamp                   |
| transaction\_hashes   | object | Blockchain transaction hashes (when available)   |

## Conversion Process

### 1. Rate Quote and Validation

When you submit a conversion request:

* System validates wallet ownership and balances
* Retrieves current exchange rates (if needed)
* Calculates all fees and estimated amounts
* Reserves funds from source wallet

### 2. Cross-Chain Execution

For cross-chain conversions:

* Initiates withdrawal from source network
* Routes through Devdraft's liquidity pools
* Executes currency conversion (if needed)
* Deposits to destination network

### 3. Completion and Settlement

Once conversion completes:

* Funds appear in destination wallet
* Transaction hashes are recorded
* Conversion receipt is generated
* State is updated to `completed`

## Conversion States

| State      | Description                                 | Next Action                 |
| ---------- | ------------------------------------------- | --------------------------- |
| processing | Conversion is being executed                | Monitor for completion      |
| completed  | Conversion successful                       | Check destination wallet    |
| failed     | Conversion failed                           | Check failure reason, retry |
| refunded   | Failed conversion, funds returned to source | Funds back in source wallet |

## Fee Structure

<AccordionGroup>
  <Accordion title="Network Fees" icon="link">
    * **Source network fee**: Gas/transaction fee on source blockchain
    * **Destination network fee**: Gas/transaction fee on destination blockchain
    * **Variable by network**: Ethereum fees higher than Solana
  </Accordion>

  <Accordion title="Conversion Fees" icon="exchange">
    * **Same currency conversions**: 0.1% - 0.3%
    * **Cross-currency conversions**: 0.3% - 0.8%
    * **Based on liquidity**: Lower fees for high-liquidity pairs
  </Accordion>

  <Accordion title="Developer Fees" icon="percent">
    * **Standard rate**: 0.8% of conversion amount
    * **Calculated on source amount**: Before other fees
    * **Transparent pricing**: No hidden fees
  </Accordion>
</AccordionGroup>

## Exchange Rates

<Tabs>
  <Tab title="Real-Time Rates">
    Exchange rates are fetched in real-time from multiple sources:

    * Major cryptocurrency exchanges
    * DeFi liquidity pools
    * Aggregated pricing feeds
    * Updated every 30 seconds
  </Tab>

  <Tab title="Rate Protection">
    Your quoted rate is protected for 5 minutes:

    * Rate locked when conversion is initiated
    * No slippage during execution
    * Automatic refund if rate expires
  </Tab>

  <Tab title="Rate Components">
    Factors affecting exchange rates:

    * Market volatility
    * Network congestion
    * Liquidity availability
    * Time of day/week
  </Tab>
</Tabs>

## Example Requests

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://api.devdraft.ai/api/v0/transfers/stablecoin-conversion" \
    -H "Content-Type: application/json" \
    -H "x-client-key: your_client_key_here" \
    -H "x-client-secret: your_client_secret_here" \
    -d '{
      "sourceWalletId": "550e8400-e29b-41d4-a716-446655440000",
      "destinationWalletId": "660f9500-f30c-52e5-b827-557766551111",
      "sourceNetwork": "ethereum",
      "destinationNetwork": "solana",
      "sourceCurrency": "usdc",
      "destinationCurrency": "usdc",
      "amount": 1000.50
    }'
  ```

  ```javascript JavaScript theme={null}
  const conversionData = {
    sourceWalletId: '550e8400-e29b-41d4-a716-446655440000',
    destinationWalletId: '660f9500-f30c-52e5-b827-557766551111',
    sourceNetwork: 'ethereum',
    destinationNetwork: 'solana',
    sourceCurrency: 'usdc',
    destinationCurrency: 'usdc',
    amount: 1000.50
  };

  const response = await fetch('https://api.devdraft.ai/api/v0/transfers/stablecoin-conversion', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'x-client-key': 'your_client_key_here',
      'x-client-secret': 'your_client_secret_here'
    },
    body: JSON.stringify(conversionData)
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  const conversion = await response.json();

  // Monitor conversion progress
  console.log('Conversion ID:', conversion.id);
  console.log('Status:', conversion.state);
  console.log('Estimated completion:', conversion.estimated_completion);
  console.log('Total fees:', conversion.fees.total_fees);
  ```

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

  url = "https://api.devdraft.ai/api/v0/transfers/stablecoin-conversion"
  headers = {
      'Content-Type': 'application/json',
      'x-client-key': 'your_client_key_here',
      'x-client-secret': 'your_client_secret_here'
  }

  data = {
      'sourceWalletId': '550e8400-e29b-41d4-a716-446655440000',
      'destinationWalletId': '660f9500-f30c-52e5-b827-557766551111',
      'sourceNetwork': 'ethereum',
      'destinationNetwork': 'solana',
      'sourceCurrency': 'usdc',
      'destinationCurrency': 'usdc',
      'amount': 1000.50
  }

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

  if response.status_code == 201:
      conversion = response.json()
      
      print(f"Conversion ID: {conversion['id']}")
      print(f"Status: {conversion['state']}")
      print(f"Estimated completion: {conversion['estimated_completion']}")
      print(f"Total fees: {conversion['fees']['total_fees']}")
  else:
      print(f"Error: {response.status_code}")
      print(response.text)
  ```

  ```php PHP theme={null}
  <?php
  $data = [
      'sourceWalletId' => '550e8400-e29b-41d4-a716-446655440000',
      'destinationWalletId' => '660f9500-f30c-52e5-b827-557766551111',
      'sourceNetwork' => 'ethereum',
      'destinationNetwork' => 'solana',
      'sourceCurrency' => 'usdc',
      'destinationCurrency' => 'usdc',
      'amount' => 1000.50
  ];

  $curl = curl_init();

  curl_setopt_array($curl, [
      CURLOPT_URL => 'https://api.devdraft.ai/api/v0/transfers/stablecoin-conversion',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_POSTFIELDS => json_encode($data),
      CURLOPT_HTTPHEADER => [
          'Content-Type: application/json',
          'x-client-key: your_client_key_here',
          'x-client-secret: your_client_secret_here'
      ],
  ]);

  $response = curl_exec($curl);
  $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  curl_close($curl);

  if ($httpCode === 201) {
      $conversion = json_decode($response, true);
      
      echo "Conversion ID: {$conversion['id']}\n";
      echo "Status: {$conversion['state']}\n";
      echo "Estimated completion: {$conversion['estimated_completion']}\n";
      echo "Total fees: {$conversion['fees']['total_fees']}\n";
  } else {
      echo "Error: $httpCode\n";
      echo $response;
  }
  ?>
  ```
</CodeGroup>

## Error Responses

<CodeGroup>
  ```json 400 Bad Request theme={null}
  {
    "statusCode": 400,
    "message": "Insufficient balance in source wallet",
    "error": "Bad Request"
  }
  ```

  ```json 404 Not Found theme={null}
  {
    "statusCode": 404,
    "message": "Source wallet not found with ID: 550e8400-e29b-41d4-a716-446655440000",
    "error": "Not Found"
  }
  ```

  ```json 422 Unprocessable Entity theme={null}
  {
    "statusCode": 422,
    "message": "EURC is not supported on Arbitrum network",
    "error": "Unprocessable Entity"
  }
  ```
</CodeGroup>

## Advanced Features

<AccordionGroup>
  <Accordion title="Batch Conversions" icon="layer-group">
    * Convert multiple amounts in a single request
    * Optimize fees across multiple conversions
    * Atomic execution for related conversions
  </Accordion>

  <Accordion title="Scheduled Conversions" icon="calendar-clock">
    * Set future execution times
    * Dollar-cost averaging strategies
    * Automated recurring conversions
  </Accordion>

  <Accordion title="Rate Alerts" icon="bell">
    * Set target exchange rates
    * Automatic execution when rates hit
    * SMS and email notifications
  </Accordion>

  <Accordion title="Liquidity Management" icon="droplet">
    * Automatic rebalancing between networks
    * Optimize for lowest fees
    * Smart routing through best liquidity pools
  </Accordion>
</AccordionGroup>

## Use Cases

<CardGroup cols={2}>
  <Card title="Portfolio Rebalancing" icon="scale-balanced">
    Automatically rebalance stablecoin holdings across networks
  </Card>

  <Card title="Arbitrage Opportunities" icon="chart-line">
    Take advantage of price differences between networks
  </Card>

  <Card title="Gas Optimization" icon="gauge">
    Move funds to networks with lower transaction fees
  </Card>

  <Card title="Multi-Currency Treasury" icon="coins">
    Manage treasury across different stablecoins and networks
  </Card>

  <Card title="Cross-Border Payments" icon="globe">
    Convert currencies for international transactions
  </Card>

  <Card title="DeFi Strategy Execution" icon="chart-mixed">
    Position funds across networks for DeFi opportunities
  </Card>
</CardGroup>

## Best Practices

<Steps>
  <Step title="Monitor Network Conditions">
    Check gas prices and network congestion before conversions
  </Step>

  <Step title="Consider Timing">
    Execute conversions during low-traffic periods for better rates
  </Step>

  <Step title="Use Rate Protection">
    Lock in favorable rates for time-sensitive conversions
  </Step>

  <Step title="Batch When Possible">
    Combine multiple conversions to reduce overall fees
  </Step>

  <Step title="Monitor Completion">
    Use webhooks to track conversion progress automatically
  </Step>
</Steps>

## Related Endpoints

* `GET /api/v0/wallets` - List your Devdraft wallets
* `GET /api/v0/transfers/{id}` - Check conversion status
* `GET /api/v0/exchange-rates` - Get current exchange rates
* `POST /api/v0/transfers/direct-wallet` - Create wallet-to-wallet transfer
