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

# Currency Swap

> Convert balances between your wallets instantly at the live exchange rate

Currency swap lets you convert funds between any two currency wallets you hold in your Yativo account — for example, moving USD to BRL, EUR to MXN, or CLP to USD — without sending to an external beneficiary.

The flow is two steps: first **initiate** to preview the rate and terms, then **process** to execute the conversion and move the balance.

***

## How it works

```
1. POST /swap/init    → preview rate, receive swap details
2. POST /swap/process → debit from_currency wallet, credit to_currency wallet
```

Both wallets must exist before swapping. Create missing wallets with `POST /wallet/create`.

***

## Step 1: Initiate Swap

Preview the exchange rate and resulting converted amount before committing.

```
POST https://api.yativo.com/api/v1/swap/init
```

<Note>
  Requires `Idempotency-Key` header.
</Note>

<ParamField body="from_currency" type="string" required>
  The source wallet currency code (ISO 4217), e.g. `"USD"`, `"EUR"`.
</ParamField>

<ParamField body="to_currency" type="string" required>
  The target wallet currency code (ISO 4217), e.g. `"BRL"`, `"MXN"`, `"CLP"`.
</ParamField>

<ParamField body="amount" type="number" required>
  Amount in the source currency to convert.
</ParamField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST 'https://api.yativo.com/api/v1/swap/init' \
    -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
    -H 'Content-Type: application/json' \
    -H 'Idempotency-Key: swap-init-usd-brl-001' \
    -d '{
      "from_currency": "USD",
      "to_currency": "BRL",
      "amount": 500
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://api.yativo.com/api/v1/swap/init', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
      'Idempotency-Key': `swap-init-${Date.now()}`,
    },
    body: JSON.stringify({
      from_currency: 'USD',
      to_currency: 'BRL',
      amount: 500,
    }),
  });
  const data = await response.json();
  ```
</RequestExample>

<ResponseExample>
  ```json Success theme={null}
  {
    "status": "success",
    "status_code": 200,
    "message": "Request successful",
    "data": {
      "from_currency": "USD",
      "to_currency": "BRL",
      "from_amount": "500.00",
      "to_amount": "2491.00",
      "exchange_rate": "4.9820",
      "fee": "5.00",
      "fee_currency": "USD"
    }
  }
  ```

  ```json Insufficient balance theme={null}
  {
    "status": "error",
    "status_code": 400,
    "message": "Insufficient wallet balance"
  }
  ```

  ```json Invalid currencies theme={null}
  {
    "status": "error",
    "status_code": 422,
    "message": "Invalid currencies supplied"
  }
  ```
</ResponseExample>

***

## Step 2: Process Swap

Execute the conversion. Funds are debited from the `from_currency` wallet and credited to the `to_currency` wallet at the live rate.

```
POST https://api.yativo.com/api/v1/swap/process
```

<Note>
  Requires `Idempotency-Key` header. Use a **new, unique key** for the process step — reusing the init key will be rejected.
</Note>

<ParamField body="from_currency" type="string" required>
  The source wallet currency code.
</ParamField>

<ParamField body="to_currency" type="string" required>
  The target wallet currency code.
</ParamField>

<ParamField body="amount" type="number" required>
  Amount in the source currency to convert.
</ParamField>

<ParamField body="transaction_purpose" type="string">
  Optional description for this swap, recorded on the transaction record.
</ParamField>

<RequestExample>
  ```bash cURL theme={null}
  curl -X POST 'https://api.yativo.com/api/v1/swap/process' \
    -H 'Authorization: Bearer YOUR_ACCESS_TOKEN' \
    -H 'Content-Type: application/json' \
    -H 'Idempotency-Key: swap-process-usd-brl-001' \
    -d '{
      "from_currency": "USD",
      "to_currency": "BRL",
      "amount": 500
    }'
  ```

  ```javascript Node.js theme={null}
  const response = await fetch('https://api.yativo.com/api/v1/swap/process', {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json',
      'Idempotency-Key': `swap-process-${Date.now()}`,
    },
    body: JSON.stringify({
      from_currency: 'USD',
      to_currency: 'BRL',
      amount: 500,
      transaction_purpose: 'Fund BRL wallet for local payouts',
    }),
  });
  const data = await response.json();
  ```

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

  response = requests.post(
      'https://api.yativo.com/api/v1/swap/process',
      headers={
          'Authorization': f'Bearer {token}',
          'Content-Type': 'application/json',
          'Idempotency-Key': f'swap-process-{int(time.time())}',
      },
      json={
          'from_currency': 'USD',
          'to_currency': 'BRL',
          'amount': 500,
      }
  )
  ```
</RequestExample>

<ResponseExample>
  ```json Success theme={null}
  {
    "status": "success",
    "status_code": 200,
    "message": "Request successful",
    "data": {
      "from_currency": "USD",
      "to_currency": "BRL",
      "from_amount": "500.00",
      "to_amount": "2491.00",
      "exchange_rate": "4.9820",
      "transaction_type": "currency_swap",
      "gateway_id": "currency_swap",
      "swap_from_currency": "USD",
      "swap_to_currency": "BRL",
      "transaction_purpose": "Fund BRL wallet for local payouts",
      "created_at": "2026-06-01T10:00:00.000000Z"
    }
  }
  ```
</ResponseExample>

***

## Full example

```javascript Node.js — complete swap flow theme={null}
async function swapCurrency(token, fromCurrency, toCurrency, amount) {
  const BASE = 'https://api.yativo.com/api/v1';
  const headers = {
    'Authorization': `Bearer ${token}`,
    'Content-Type': 'application/json',
  };

  // Step 1: Preview the rate
  const initRes = await fetch(`${BASE}/swap/init`, {
    method: 'POST',
    headers: { ...headers, 'Idempotency-Key': `swap-init-${Date.now()}` },
    body: JSON.stringify({ from_currency: fromCurrency, to_currency: toCurrency, amount }),
  });
  const preview = await initRes.json();
  console.log(`Rate: ${preview.data.exchange_rate} — you receive ${preview.data.to_amount} ${toCurrency}`);

  // Step 2: Execute
  const processRes = await fetch(`${BASE}/swap/process`, {
    method: 'POST',
    headers: { ...headers, 'Idempotency-Key': `swap-process-${Date.now()}` },
    body: JSON.stringify({ from_currency: fromCurrency, to_currency: toCurrency, amount }),
  });
  return processRes.json();
}

// Usage
const result = await swapCurrency(token, 'USD', 'BRL', 500);
console.log('Swap complete:', result.data);
```

***

## Notes

* Both wallets must exist before swapping. Create them with `POST /wallet/create` if needed.
* The live rate is fetched at execution time — rates are not locked between `/init` and `/process`. Use `/init` to show the customer a preview, then execute `/process` promptly.
* Swaps are recorded as `currency_swap` transactions and appear in your transaction history.
* Check available wallet balances with `GET /wallet/balance` before initiating.
