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

# Meld buy, sell, and transfer

> Use portal.ramps.meld in the Android SDK to quote Meld's ramp providers, open their hosted widget, and follow the resulting transactions.

Portal's Android SDK lets your users buy, sell and transfer crypto through [Meld](https://docs.portalhq.io/integrations/On-Off-Ramp/meld.md)'s network of ramp providers, such as Transak, with the `portal.ramps.meld` API. Each method calls Portal's Meld integration on the Portal API with the client's credential; your app never calls Meld's servers directly.

Meld requires Portal Android SDK `11.0.0` or later.

> [!NOTE]
>
> For one-time dashboard setup and webhooks, see the [Meld integration overview](https://docs.portalhq.io/integrations/On-Off-Ramp/meld.md). For the HTTP flow, see the [White-Label API guide](https://docs.portalhq.io/integrations/On-Off-Ramp/meld-widget.md).

## Overview

With `portal.ramps.meld` you can:

* **Quote** a purchase or sale across the providers, and compare their prices and fees
* **Open** a provider's hosted widget, where the user pays and completes any KYC
* **Follow** the resulting transactions
* **Describe** what each provider supports, where and for how much, with the Network Partner methods
* **Create** or find the client's Meld customer

Every method is a `suspend` function that returns a `Result` of the Portal API response, whose `data` holds the result (`null` from `getNetworkPartnerCountryDefaults` when Meld has no defaults for the country). A failed request is returned in the `Result`, not thrown; see [Handling errors](#handling-errors). The request and response types are in `io.portalhq.android.api.data.meld`, and `MeldApiError` and `MeldException` in `io.portalhq.android.ramps.meld`.

The same methods are also on `portal.api.meld`. Prefer `portal.ramps.meld`: when the calling coroutine is cancelled, for example because its screen closed, `portal.ramps.meld` throws the `CancellationException` instead of returning it as a failed `Result`, so a closed screen isn't reported as a Meld error.

## Prerequisites

Before using Meld, ensure you have:

* A properly initialized Portal client with a wallet (see [Getting started](https://docs.portalhq.io/sdks/android/guide/getting-started.md) and [Create a wallet](https://docs.portalhq.io/sdks/android/guide/create-a-wallet.md))
* Meld enabled for your environment in the Portal Dashboard (see [Meld integration overview](https://docs.portalhq.io/integrations/On-Off-Ramp/meld.md))

The examples in this guide use a `meld` value, from inside a coroutine:

```kotlin theme={null}
// `portal` is your initialized Portal instance.
val meld = portal.ramps.meld
```

## Buying crypto with the widget

This guide walks through a purchase. A sale (`MeldSessionType.SELL`) uses the same quote and widget methods, with crypto as the `sourceCurrencyCode`, but `portal.ramps.meld` sends nothing and the widget can't use the Portal wallet, so your app sends the crypto itself. Transfers (`MeldSessionType.TRANSFER`) follow a different Meld flow, without quotes, and aren't covered here.

> [!WARNING]
>
> In a sale, `walletAddress` is the user's own Portal address on the chain of `sourceCurrencyCode`. After the widget, read the address to send to from `getRetailTransactionBySession(sessionId)` as `cryptoDetails?.destinationWalletAddress`, never `sourceWalletAddress` or `sessionWalletAddress`, and don't send while it is `null`. Check that `cryptoDetails?.chainId` and the transaction's `sourceCurrencyCode` match what the user sold, then send exactly the transaction's `sourceAmount`, and don't send while it is `null`. `sourceAmount` is a `Double`: pass it as `BigDecimal.valueOf(sourceAmount).toPlainString()`, not `toString()`, which can give `5.0E-4` (see [Send tokens](https://docs.portalhq.io/sdks/android/guide/send-tokens.md)): a wrong address or amount means lost funds. See the off-ramp section of Meld's [White-Label API guide](https://docs.meld.io/docs/stablecoins/white-label-api-integration/whitelabel-api-guide#off-ramp-flow-sell).

A purchase takes five steps:

1. **Choose** the currency and the wallet address on its chain.
2. **Quote** the purchase with `getRetailQuote(request)` and let the user pick a provider.
3. **Create a widget session** at that provider with `createRetailWidget(request)`.
4. **Open** the session's `widgetUrl` in a Custom Tab, where the user pays.
5. **Follow** the transaction with `getRetailTransactionBySession(sessionId)`, or with [webhooks](https://docs.portalhq.io/integrations/On-Off-Ramp/meld-webhooks.md) to your backend.

### Choosing the currency and wallet address

Each Meld crypto code names one asset on one chain: `USDC` is USDC on Ethereum, and `USDC_BASE` is USDC on Base. Use the same code in the quote and in the session, and pass a wallet address on that chain, or the purchase settles somewhere the user doesn't expect.

`getNetworkPartnerCurrencies(params)` returns each currency's `chainId`. That is Meld's own number: the EVM chain id for an EVM currency (`"1"`, `"8453"`), but other chains have one too (Solana's is `"101"`). Build an `eip155:` chain ID only for an EVM currency, one whose `chainId` is all digits and whose `contract` is a `0x` address of 40 hex digits (native ETH has the zero address).

Map other chains yourself from `chainCode`, for example Solana to `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`.

`getAddress` returns the wallet's address for any `eip155:` chain, so offer only currencies on chains your app supports. For an [account abstraction](https://docs.portalhq.io/resources/account-abstraction.md#supported-networks) enabled client, offer only the networks Portal supports for it: its smart contract address exists only there.

```kotlin theme={null}
import io.portalhq.android.api.data.meld.MeldCategory
import io.portalhq.android.api.data.meld.MeldCurrencyType
import io.portalhq.android.api.data.meld.MeldGetNetworkPartnerCurrenciesParams

val currencies = meld.getNetworkPartnerCurrencies(
  MeldGetNetworkPartnerCurrenciesParams(
    category = MeldCategory.CRYPTO_ONRAMP,
    country = "US",
    type = MeldCurrencyType.CRYPTO,
  ),
).getOrThrow().data.currencies

val usdc = currencies.firstOrNull { it.currencyCode == "USDC" }
val chainId = usdc?.chainId
val contract = usdc?.contract
// An EVM currency: an all-digit chainId and a 0x contract address of 40 hex digits.
val isEvm = !chainId.isNullOrEmpty() && chainId.all { it in '0'..'9' } &&
  contract != null && Regex("^0x[0-9a-fA-F]{40}$").matches(contract)

val walletAddress = (if (isEvm) portal.getAddress("eip155:$chainId") else null)
  ?: throw MyAppException("No wallet address for USDC")
```

`MyAppException` in these examples stands for your app's own exception type. They call `getOrThrow()` to keep the flow short; if you catch the exceptions it throws with `catch (e: Exception)`, rethrow `CancellationException` first.

### Quoting

`getRetailQuote(request)` prices the purchase at every provider that can serve it, and returns one `MeldQuote` per provider.

```kotlin theme={null}
import android.util.Log
import io.portalhq.android.api.data.meld.MeldGetRetailQuoteRequest
import java.math.BigDecimal

// The amount the user entered (see sourceAmount under "Creating a widget session").
val amount = BigDecimal("100")

val result = meld.getRetailQuote(
  MeldGetRetailQuoteRequest(
    countryCode = "US",
    sourceCurrencyCode = "USD",
    destinationCurrencyCode = "USDC",
    sourceAmount = amount.toDouble(),
    walletAddress = walletAddress,
  ),
).getOrThrow().data

for (option in result.quotes) {
  Log.d("Meld", "${option.serviceProvider}: ${option.destinationAmount} ${option.destinationCurrencyCode}, fee ${option.totalFee} ${option.sourceCurrencyCode}")
}
// Here the first quote; let the user choose in your UI.
val quote = result.quotes.firstOrNull()
  ?: throw MyAppException("No quote: ${result.error ?: result.message}")
```

`MeldGetRetailQuoteRequest` takes:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `countryCode` | `String` | Yes | ISO 3166-1 alpha-2 country code, for example `"US"`. |
| `sourceCurrencyCode` | `String` | Yes | The currency the user pays with: fiat for a purchase, a Meld crypto code for a sale. |
| `destinationCurrencyCode` | `String` | Yes | The currency the user receives, as a [Meld code](https://www.meld.io/coverage/cryptocurrencies) for crypto. |
| `sourceAmount` | `Double` | Yes | The amount of `sourceCurrencyCode` to convert. The quote takes a number, and the widget session a string. |
| `walletAddress` | `String?` | No | The destination wallet address, on the chain of `destinationCurrencyCode`; on a sale, the user's own address on the chain of `sourceCurrencyCode`. Meld uses it for Ramp Intelligence (`rampScore`, `previouslyUsed`). |
| `customerId` | `String?` | No | The Meld customer id, from `createCustomer` or `searchCustomer`. |
| `paymentMethodType` | `String?` | No | Quote only this payment method, for example `"CREDIT_DEBIT_CARD"`. |
| `serviceProviders` | `List<String>?` | No | Quote only these providers. |
| `subdivision` | `String?` | No | The ISO 3166-2 code of the state or region, where the country needs one, for example `"US-NY"`, as `getNetworkPartnerCountries` returns in `subdivisions`. |

The result holds `quotes`, and `error` or `message` when no provider can serve the purchase. A currency pair Meld doesn't support is refused with a `400` (`Meld API error: …`) rather than an empty `quotes`. Each quote carries its `serviceProvider`, `transactionType`, the source and destination amounts and currencies, `exchangeRate`, `transactionFee`, `networkFee`, `partnerFee`, `totalFee` and `paymentMethodType`. `rampIntelligence` can add a `rampScore`, `lowKyc` and `previouslyUsed`, when the customer last used the provider, as an ISO 8601 date-time string.

### Creating a widget session

`createRetailWidget(request)` starts a session at one provider and returns its `widgetUrl`. Pass the `serviceProvider` and `paymentMethodType` of the quote the user picked, so the widget opens at the provider and with the method they chose; the provider prices the purchase again in the widget.

```kotlin theme={null}
import android.util.Log
import io.portalhq.android.api.data.meld.MeldCreateRetailWidgetRequest
import io.portalhq.android.api.data.meld.MeldLockField
import io.portalhq.android.api.data.meld.MeldSessionData
import io.portalhq.android.api.data.meld.MeldSessionType

val session = meld.createRetailWidget(
  MeldCreateRetailWidgetRequest(
    sessionType = MeldSessionType.BUY,
    sessionData = MeldSessionData(
      countryCode = "US",
      serviceProvider = quote.serviceProvider,
      sourceCurrencyCode = "USD",
      sourceAmount = amount.toPlainString(), // a plain decimal string
      destinationCurrencyCode = "USDC",
      walletAddress = walletAddress,
      paymentMethodType = quote.paymentMethodType,
      // Where the provider supports locking.
      lockFields = listOf(MeldLockField.SOURCE_AMOUNT, MeldLockField.DESTINATION_CURRENCY_CODE, MeldLockField.WALLET_ADDRESS),
    ),
  ),
).getOrThrow().data

Log.d("Meld", session.id) // never log widgetUrl or token: they carry the session secret
```

`MeldCreateRetailWidgetRequest` takes:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `sessionType` | `MeldSessionType` | Yes | `MeldSessionType.BUY`, `SELL` or `TRANSFER`. |
| `sessionData` | `MeldSessionData` | Yes | The session's configuration (see below). |
| `externalSessionId` | `String?` | No | Your own reference for the session, recorded on Meld's transaction. Must be unique per session. It helps match a webhook to the session. |
| `customerId` | `String?` | No | The Meld customer id, from `createCustomer` or `searchCustomer`. |
| `bypassKyc` | `Boolean?` | No | Reuse the customer's approved KYC: Meld looks up the customer's KYC status and issues a share token when it is approved, for providers that accept one. Meld needs a customer it can resolve; Portal always sends the client's `externalCustomerId`. |

`MeldSessionData` takes:

| Field | Type | Required | Description |
| - | - | - | - |
| `countryCode` | `String` | Yes | ISO 3166-1 alpha-2 country code. |
| `serviceProvider` | `String` | Yes | The provider, as a quote returned it. |
| `sourceCurrencyCode` | `String` | Yes | The currency the user pays with. |
| `sourceAmount` | `String` | Yes | The amount, as a plain decimal string such as `"99.5"`. Keep the amount as a `BigDecimal`, parsed from the user's input string rather than from a `Double` where you can, and send `toPlainString()`. `Double.toString()` gives `1.0E7` for 10,000,000, `BigDecimal.toString()` can use an exponent too, and formatting with the device locale can give `99,5`. `BigDecimal(String)` accepts only `.` as the decimal separator, so parse the user's input with the device locale, for example with a `DecimalFormat` whose `isParseBigDecimal` is `true`. |
| `destinationCurrencyCode` | `String` | Yes | The currency the user receives. |
| `walletAddress` | `String?` | No | On a purchase, the destination wallet address, on the chain of `destinationCurrencyCode`. Pre-fills the widget. |
| `walletTag` | `String?` | No | A memo or destination tag, for chains that need one. |
| `paymentMethodType` | `String?` | No | Pre-selects the payment method. |
| `redirectUrl` | `String?` | No | Where the widget sends the user when they finish. Some providers need its domain allowlisted with Meld. |
| `lockFields` | `List<String>?` | No | Fields to lock in the widget, from the `MeldLockField` constants, for example `listOf(MeldLockField.SOURCE_AMOUNT, MeldLockField.DESTINATION_CURRENCY_CODE, MeldLockField.WALLET_ADDRESS)`. Only some providers support locking each field; Meld's [White-Label customization](https://docs.meld.io/docs/stablecoins/white-label-api-integration/whitelabel-api-guide/white-label-customization) guide lists which providers lock the crypto currency and the wallet address. To be sure, quote only providers that lock the wallet address, with `serviceProviders`. |
| `clientIpAddress` | `String?` | No | The user's public IPv4 or IPv6 address, which some providers, such as Transak, need to open a session. Leave it out: Portal uses the public IP address the request came from, which is the user's when the SDK calls from the device. Pass it only when Portal's requests don't come straight from the device, for example when your app sends them through your own server. |

The session carries its `id`, `token`, `widgetUrl`, `customerId`, `externalCustomerId` and `externalSessionId` (empty or `null` when you didn't pass one).

> [!WARNING]
>
> `widgetUrl` embeds a single-use session token. Open it once, and don't log, store or reuse it, including in saved instance state. Create a new session for each purchase.

### Opening the widget

Open `widgetUrl` in a [Custom Tab](https://developer.chrome.com/docs/android/custom-tabs), or the browser, rather than in a `WebView`: the provider's page runs its payment, KYC and 3-D Secure steps in the browser. Custom Tabs come from the AndroidX Browser library:

```groovy theme={null}
// In your app/build.gradle file
dependencies {
    implementation "androidx.browser:browser:1.8.0"
}
```

`CustomTabsIntent.launchUrl` doesn't tell your app when the user closes the tab, so read the transaction when your screen comes back to the foreground, in `onResume`. Keep the session's `id`, not its `widgetUrl`, in saved instance state: Android can end your app's process while the user is in the widget, and recreate your screen when they come back. Launch the Custom Tab on the main thread while your screen is in the foreground, for example inside `lifecycle.withResumed { openWidget(session) }` after creating the session: Android 10 and later can block an activity start from the background, and the single-use URL would be lost.

```kotlin theme={null}
import android.content.ActivityNotFoundException
import android.net.Uri
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.browser.customtabs.CustomTabsIntent
import androidx.lifecycle.lifecycleScope
import io.portalhq.android.Portal
import io.portalhq.android.api.data.meld.MeldWidgetSession
import io.portalhq.android.ramps.meld.MeldApiError
import kotlinx.coroutines.launch

class BuyCryptoActivity : ComponentActivity() { // or AppCompatActivity
  private lateinit var portal: Portal // your initialized Portal instance

  // Kept across process death, unlike widgetUrl, which is single use.
  private var openedSessionId: String? = null
  private var awaitingWidgetReturn = false

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // Set `portal` here, for example from your Application: after process death this is a new instance,
    // and with Client Auth, restore the session first (see Restore the session on launch).
    openedSessionId = savedInstanceState?.getString(STATE_SESSION_ID)
    awaitingWidgetReturn = savedInstanceState?.getBoolean(STATE_AWAITING_RETURN) ?: false
  }

  override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)
    outState.putString(STATE_SESSION_ID, openedSessionId)
    outState.putBoolean(STATE_AWAITING_RETURN, awaitingWidgetReturn)
  }

  /** Opens the session's widget in a Custom Tab. Call it on the main thread. */
  fun openWidget(session: MeldWidgetSession) {
    val uri = Uri.parse(session.widgetUrl)
    if (uri.scheme != "https") return // not a URL to open
    openedSessionId = session.id
    awaitingWidgetReturn = true
    try {
      CustomTabsIntent.Builder().build().launchUrl(this, uri)
    } catch (e: ActivityNotFoundException) {
      awaitingWidgetReturn = false
      // No browser can open it. Don't log or copy the URL: it carries the session token.
    }
  }

  override fun onResume() {
    super.onResume()
    val sessionId = openedSessionId
    if (!awaitingWidgetReturn || sessionId == null) return
    lifecycleScope.launch {
      portal.ramps.meld.getRetailTransactionBySession(sessionId)
        .onSuccess { response ->
          awaitingWidgetReturn = false // read: cleared only now, so a failed or interrupted read is redone
          val transaction = response.data.transaction
          Log.d("Meld", "${transaction.status} ${transaction.destinationAmount} ${transaction.destinationCurrencyCode}")
        }
        .onFailure { error ->
          // Keep the session pending: a 404 (no transaction yet), a network error or a 5xx can clear up,
          // so the next onResume reads again. Offer the user a retry too, or rely on webhooks.
          if (MeldApiError.from(error)?.status == 404) {
            Log.d("Meld", "No transaction for this session yet.")
          } else {
            Log.e("Meld", "Couldn't read the transaction", error)
          }
        }
    }
  }

  private companion object {
    const val STATE_SESSION_ID = "meldSessionId"
    const val STATE_AWAITING_RETURN = "meldAwaitingWidgetReturn"
  }
}
```

See [Launch the provider UI](https://docs.meld.io/docs/stablecoins/white-label-api-integration/whitelabel-api-guide#launch-the-provider-ui) in Meld's docs for how each provider's page can be shown. Portal returns only `widgetUrl`, not the `serviceProviderWidgetUrl` that section mentions.

### Following the transaction

`getRetailTransactionBySession(sessionId)` returns the session's transaction once Meld has created it, when the user starts the purchase or sale; until then it fails with a `404`, as it does for a session that doesn't exist or isn't this client's. The `onResume` above reads it once when the user comes back; if the user closed the widget before starting the purchase, that read gets the `404`.

The transaction's fields are described under [Transactions](#transactions). Since not every provider locks the fields you asked it to, check that the transaction's `destinationCurrencyCode`, and `cryptoDetails?.destinationWalletAddress` and `chainId`, match what you requested.

> [!NOTE]
>
> Prefer [Meld webhooks](https://docs.portalhq.io/integrations/On-Off-Ramp/meld-webhooks.md), delivered to your backend, to repeated reads for transaction updates.

## Transactions

`searchRetailTransactions(params)` lists the client's transactions, ordered by creation date, and `getRetailTransaction(transactionId)` returns one.

```kotlin theme={null}
import android.util.Log
import io.portalhq.android.api.data.meld.MeldSearchRetailTransactionsParams
import io.portalhq.android.api.data.meld.MeldTransactionStatus

val page = meld.searchRetailTransactions(
  MeldSearchRetailTransactionsParams(
    statuses = listOf(MeldTransactionStatus.SETTLED, MeldTransactionStatus.PENDING),
    limit = 20,
  ),
).getOrThrow().data
Log.d("Meld", "${page.count} of ${page.totalCount} transactions")

for (transaction in page.transactions) {
  Log.d("Meld", "${transaction.id} ${transaction.status} ${transaction.transactionType} ${transaction.serviceProvider}")
}

page.transactions.firstOrNull()?.let { first ->
  val transaction = meld.getRetailTransaction(first.id).getOrThrow().data.transaction
  Log.d("Meld", transaction.cryptoDetails?.blockchainTransactionId ?: "no on-chain transaction yet")
}
```

`MeldSearchRetailTransactionsParams` filters by `statuses`, `types`, `serviceProviders`, `sessionIds`, `externalSessionIds`, `serviceProviderTransactionId`, `amountFrom` and `amountTo`, and `from` and `to`, as ISO 8601 dates or date-times. The SDK sends each list comma-separated, and leaves out `null` and empty values; `searchRetailTransactions()` without arguments lists the client's transactions. `limit` caps the result (Meld's default is 10, and the most it returns is 100), and the SDK doesn't expose Meld's paging cursors: `remaining` says how many more match, so narrow the filters to see them.

A transaction carries its `id`, `sessionId`, `status`, `transactionType`, `serviceProvider`, `createdAt` and `updatedAt`, and, when Meld has them, the source and destination amounts and currencies and `paymentMethodType`. Its on-chain details are in `cryptoDetails` (`MeldTransactionCryptoDetails`), which can be `null`, and each of its fields is nullable: `blockchainTransactionId`, `chainId`, `destinationWalletAddress`, `sourceWalletAddress`, `sessionWalletAddress`, `institution` and the fees. `serviceProviderDetails` is an untyped map that differs by provider.

## Customers

A Meld customer is optional: the widget collects the user's identity itself, and Portal identifies the client to Meld with the same `externalCustomerId` on every quote and session. Create one when you want to give Meld the user's details up front.

```kotlin theme={null}
import android.util.Log
import io.portalhq.android.api.data.meld.MeldCreateCustomerRequest
import io.portalhq.android.api.data.meld.MeldCustomerName
import io.portalhq.android.api.data.meld.MeldCustomerType
import io.portalhq.android.ramps.meld.MeldApiError

val customerId = meld.createCustomer(
  MeldCreateCustomerRequest(
    name = MeldCustomerName(firstName = "Jane", lastName = "Doe"),
    email = "jane@example.com",
    type = MeldCustomerType.INDIVIDUAL,
  ),
).fold(
  onSuccess = { response -> response.data.id },
  onFailure = { error ->
    val apiError = MeldApiError.from(error)
    if (apiError?.status != 409) throw error
    // The client already has a customer.
    apiError.meldCustomerId
      ?: meld.searchCustomer().getOrThrow().data.customers.firstOrNull()?.id
  },
)
Log.d("Meld", "customer $customerId") // pass as customerId on getRetailQuote and createRetailWidget
```

The client has at most one Meld customer: a second `createCustomer` fails with a `409`, whose `meldCustomerId` is the existing customer's id when Portal has it on record. Otherwise, `searchCustomer()` returns it in `customers`, and finding it also records it in Portal. Pass as `customerId` only an id from `createCustomer` or `searchCustomer`: Portal doesn't record the `customerId` of a widget session, so that id is refused with a `404` (`Meld customer does not exist.`) until `searchCustomer()` has found it.

`createCustomer()` without arguments creates a customer with no details. `MeldCreateCustomerRequest` takes an optional `name`, `email`, `phone`, `dateOfBirth` (as `YYYY-MM-DD`; any other format is refused with a `400`) and `type`, `MeldCustomerType.INDIVIDUAL` or `MeldCustomerType.BUSINESS`. The SDK and Portal don't set a `type` when you leave it out.

## Network Partners

The Network Partner methods describe what each provider (partner) supports, where and for how much. Use them to build a country, currency or payment-method picker before you quote.

| Method | `data` |
| - | - |
| `getNetworkPartners(params)` | A list of providers, with their `status`, `categories` and capabilities. |
| `getNetworkPartnerCountries(params)` | `countries`: the countries the providers serve, with their `subdivisions`. |
| `getNetworkPartnerCurrencies(params)` | `currencies`: the fiat and crypto currencies they support, with each crypto currency's `chainId`. |
| `getNetworkPartnerPaymentMethods(params)` | A list of payment methods. |
| `getNetworkPartnerFiatLimits(params)` | `fiatLimits`: the minimum and maximum fiat amounts. |
| `getNetworkPartnerKycLimits(params)` | `kycLimits`: the amounts allowed at each KYC level. |
| `getNetworkPartnerRoutes(params)` | A list of routes from a source to a destination currency in one country, with their payment methods and KYC limits. |
| `getNetworkPartnerCountryDefaults(countryCode, category)` | The country's default fiat currency and payment methods. `data` is `null` when Meld has none. |

```kotlin theme={null}
import android.util.Log
import io.portalhq.android.api.data.meld.MeldCategory
import io.portalhq.android.api.data.meld.MeldGetNetworkPartnerRoutesParams
import io.portalhq.android.api.data.meld.MeldGetNetworkPartnersParams

val partners = meld.getNetworkPartners(
  MeldGetNetworkPartnersParams(category = MeldCategory.CRYPTO_ONRAMP, country = "US"),
).getOrThrow().data
for (partner in partners) {
  Log.d("Meld", "${partner.serviceProvider} ${partner.name} ${partner.status}")
}

val routes = meld.getNetworkPartnerRoutes(
  MeldGetNetworkPartnerRoutesParams(
    category = MeldCategory.CRYPTO_ONRAMP,
    countryCode = "US",
    sourceCurrencyCode = "USD",
    destinationCurrencyCode = "USDC",
  ),
).getOrThrow().data
Log.d("Meld", routes.joinToString { it.partner })

val defaults = meld.getNetworkPartnerCountryDefaults(countryCode = "US", category = MeldCategory.CRYPTO_ONRAMP)
  .getOrThrow().data
if (defaults != null) {
  Log.d("Meld", "${defaults.currencyCode}: ${defaults.paymentMethods}")
}
```

The SDK requires none of the filters of six of these methods, which you can also call without arguments, but Meld's guide lists some filters as required, `category` and `country` among them, so pass `category` and, where the method takes them, `country`, `type` (currencies) and `currencyCode` (payment methods). `getNetworkPartnerRoutes` requires the `category`, `countryCode` and both currencies. Most methods name the country `country`, and routes and country defaults `countryCode`; a filter named `partner` takes one provider, and `partners` several. The `category` is one of the `MeldCategory` constants, such as `MeldCategory.CRYPTO_ONRAMP`, `CRYPTO_OFFRAMP` or `CRYPTO_TRANSFER`; Portal refuses any other value for routes and country defaults with a `400`.

## Handling errors

A failed request is returned in the `Result`. Read it with `onFailure`, `fold` or `exceptionOrNull()`. Besides network failures (`java.io.IOException`) and decoding failures (`com.google.gson.JsonParseException`), three kinds of failure reach your app:

* **Portal API errors**: `PortalException.Api.HttpBadRequest` for a `400`, `PortalException.Api.HttpUnauthorized` for a `401` and `PortalException.Api.HttpRequestFailed` for any other status. `MeldApiError.from(error)` reads the HTTP `status` (`null` when no HTTP status was received), Portal's `id` and the `message`, and, on the `409` from `createCustomer`, the existing customer's `meldCustomerId`. It returns `null` for a failure that isn't an HTTP failure. A `401` has no `message`: the SDK doesn't read its body.
* **`MeldException.EmptyIdentifier`**, before any request is sent, when a value that goes in the request path is empty: `transactionId`, `sessionId`, the `category`, `countryCode`, `sourceCurrencyCode` or `destinationCurrencyCode` of `getNetworkPartnerRoutes`, or the `countryCode` or `category` of `getNetworkPartnerCountryDefaults`. Its `name` is the parameter's name. A path value of `.` or `..` fails with an `IllegalArgumentException`.
* **`PortalException.Credentials.PortalCredentialError`**, before the request is sent, when the credential can't supply a token, for example with [Client Auth](https://docs.portalhq.io/sdks/android/guide/client-auth.md) after the session ended.

```kotlin theme={null}
import android.util.Log
import io.portalhq.android.exceptions.PortalException
import io.portalhq.android.ramps.meld.MeldApiError
import io.portalhq.android.ramps.meld.MeldException

meld.getRetailTransaction(transactionId)
  .onSuccess { response -> Log.d("Meld", response.data.transaction.status) }
  .onFailure { error ->
    val apiError = MeldApiError.from(error)
    when {
      apiError != null -> Log.e("Meld", "HTTP ${apiError.status ?: "no status"} ${apiError.id.orEmpty()}: ${apiError.message.orEmpty()}")
      error is MeldException.EmptyIdentifier -> Log.e("Meld", "Missing ${error.name}")
      error is PortalException.Credentials.PortalCredentialError -> Log.e("Meld", "No credential: ${error.reason}")
      else -> Log.e("Meld", "Meld request failed", error)
    }
  }
```

The statuses to expect. The text after `Meld API error:` is Meld's own wording and may change: show it to the user, but don't match on it.

* `400`: an invalid request, with the reason in `message`, including a provider that needs the user's IP address and didn't get one (`Meld API error: …`), or Meld not enabled or not configured for the environment (`Meld integration is not enabled…`, `Meld API key is not configured…`), or Meld rejected the environment's Meld API key (`Meld rejected the configured API key…`). Check that each environment has the matching Meld sandbox or production key before you ship.
* `401`: the client's credential was rejected. With [Client Auth](https://docs.portalhq.io/sdks/android/guide/client-auth.md#handle-session-invalidation), this ends the session: the `Portal` instance's `onSessionInvalidated` listeners fire, and later calls fail with a `PortalCredentialError` whose `reason` is `SESSION_INVALIDATED`.
* `403` or `422`: Meld refused the request (`Meld API error: …`).
* `404`: `Meld customer does not exist.`, `Meld transaction does not exist.` or Meld's own `Meld API error: …`, and from `getRetailTransactionBySession`, usually a session whose user hasn't started paying yet.
* `409`: `createCustomer` for a client that already has a customer, or Meld's own `Meld API error: …`.
* `502`: any other Meld failure, rate limits included.

## Values Meld may add

Statuses, categories, payment types, transaction types and the other Meld enumerations are plain `String` fields (or `List<String>`), with the values known today as constants in objects such as `MeldTransactionStatus`, `MeldTransactionType`, `MeldCategory`, `MeldPaymentType`, `MeldLockField` and `MeldCustomerType`. A value Meld adds later reaches your app as its string instead of failing the response. Compare against the constants, such as `MeldTransactionStatus.SETTLED`, and give a `when` over one an `else` branch. `MeldSessionType` is a closed enum, because Portal accepts only its three values.

## Testing

`Meld`, the class of `portal.ramps.meld`, is an open class whose methods are open, as is `MeldApi`, the class of `portal.api.meld`. Pass a `Meld` to the code that uses it rather than the whole `Portal`, and a test can give it a subclass or a mock instead.

## Related documentation

* [Meld integration overview](https://docs.portalhq.io/integrations/On-Off-Ramp/meld.md): dashboard setup
* [White-Label API guide](https://docs.portalhq.io/integrations/On-Off-Ramp/meld-widget.md): the HTTP flow
* [Meld webhooks](https://docs.portalhq.io/integrations/On-Off-Ramp/meld-webhooks.md): transaction updates
* [Error handling](https://docs.portalhq.io/sdks/android/guide/error-handling.md): the Android SDK's exception types


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.