> ## 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 iOS SDK to quote Meld's ramp providers, open their hosted widget, and follow the resulting transactions.

Portal's iOS 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 PortalSwift `8.2.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 returns the Portal API response, a `MeldResponse` whose `data` holds the result (a `MeldNullableResponse`, whose `data` can be `nil`, for `getNetworkPartnerCountryDefaults`). The same methods are also on `portal.api.meld`.

## Prerequisites

Before using Meld, ensure you have:

* A properly initialized Portal client with a wallet (see [Getting started](https://docs.portalhq.io/sdks/ios/guide/getting-started.md) and [Create a wallet](https://docs.portalhq.io/sdks/ios/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 `portal` instance:

```swift theme={null}
import PortalSwift

let portal = try Portal("CLIENT_API_KEY_OR_CLIENT_SESSION_TOKEN")
let meld = portal.ramps.meld
```

## Buying crypto with the widget

This guide walks through a purchase. A sale (`.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 (`.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 `nil`. Check that `cryptoDetails?.chainId` and the transaction's `sourceCurrencyCode` match what the user sold, then send exactly the transaction's `sourceAmount` (see [Send tokens](https://docs.portalhq.io/sdks/ios/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 the browser, 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) enabled client, offer only the networks Portal supports for it: its smart contract address exists only there.

```swift theme={null}
let currencies = try await meld.getNetworkPartnerCurrencies(params: MeldGetNetworkPartnerCurrenciesParams(
  category: .cryptoOnramp,
  country: "US",
  type: .crypto
)).data.currencies

guard let usdc = currencies.first(where: { $0.currencyCode == "USDC" }),
      let chainId = usdc.chainId, !chainId.isEmpty, chainId.allSatisfy(\.isASCII), chainId.allSatisfy(\.isNumber),
      let contract = usdc.contract,
      contract.range(of: "^0x[0-9a-fA-F]{40}$", options: .regularExpression) != nil, // an EVM currency
      let walletAddress = await portal.getAddress("eip155:\(chainId)") else {
  throw MyAppError.noWalletForCurrency("USDC")
}
```

`MyAppError` in these examples stands for your app's own error type.

### Quoting

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

```swift theme={null}
let result = try await meld.getRetailQuote(request: MeldGetRetailQuoteRequest(
  countryCode: "US",
  sourceCurrencyCode: "USD",
  destinationCurrencyCode: "USDC",
  sourceAmount: 100,
  walletAddress: walletAddress
)).data

for option in result.quotes {
  print("\(option.serviceProvider): \(option.destinationAmount) \(option.destinationCurrencyCode), fee \(option.totalFee) \(option.sourceCurrencyCode)")
}
// Here the first quote; let the user choose in your UI.
guard let quote = result.quotes.first else {
  throw MyAppError.noQuote(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. |
| `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` | `[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.

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

```swift theme={null}
let session = try await meld.createRetailWidget(request: MeldCreateRetailWidgetRequest(
  sessionType: .buy,
  sessionData: MeldSessionData(
    countryCode: "US",
    serviceProvider: quote.serviceProvider,
    sourceCurrencyCode: "USD",
    sourceAmount: "100", // a plain decimal string
    destinationCurrencyCode: "USDC",
    walletAddress: walletAddress,
    paymentMethodType: quote.paymentMethodType,
    lockFields: [.sourceAmount, .destinationCurrencyCode, .walletAddress] // where the provider supports locking
  )
)).data

print(session.id) // never log widgetUrl or token: they carry the session secret
```

`MeldCreateRetailWidgetRequest` takes:

| Parameter | Type | Required | Description |
| - | - | - | - |
| `sessionType` | `MeldSessionType` | Yes | `.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` | `Bool?` | No | Reuse the customer's approved KYC, where the provider supports it: Meld issues a share token. 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"`. Build a `Decimal` from the user's input string with `Decimal(string:locale:)`, not from a `Double`, or use a `NumberFormatter` with the `en_US_POSIX` locale, `numberStyle = .decimal` and `maximumFractionDigits` set. A `Double`'s description can give `1e+16`, and the device locale can give `99,5`. |
| `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` | `[MeldLockField]?` | No | Fields to lock in the widget, for example `[.sourceAmount, .destinationCurrencyCode, .walletAddress]`. 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 `nil` 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. Create a new session for each purchase.

### Opening the widget

Open `widgetUrl` in the browser, for example in an `SFSafariViewController`, rather than in a `WKWebView`: the provider's page runs its payment and KYC steps in the browser. Present it on the main actor:

```swift theme={null}
import SafariServices
import UIKit

@MainActor
func presentWidget(_ session: MeldWidgetSession, from viewController: UIViewController & SFSafariViewControllerDelegate) {
  guard let url = URL(string: session.widgetUrl), url.scheme == "https" else {
    return // not a URL to open
  }
  let safari = SFSafariViewController(url: url)
  safari.delegate = viewController // read the transaction in safariViewControllerDidFinish(_:)
  viewController.present(safari, animated: true)
}
```

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

When the user closes the widget, `safariViewControllerDidFinish(_:)` is called: read the session's transaction then. `getRetailTransactionBySession(sessionId:)` returns it 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.

```swift theme={null}
// In your SFSafariViewControllerDelegate, with the session id you kept when you created the session.
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
  guard let sessionId = openedSessionId else { return }
  Task {
    do {
      let transaction = try await meld.getRetailTransactionBySession(sessionId: sessionId).data.transaction
      print(transaction.status, transaction.destinationAmount ?? 0, transaction.destinationCurrencyCode ?? "")
    } catch where MeldApiError.from(error)?.status == 404 {
      print("No transaction for this session yet.")
    } catch {
      print("Couldn't read the transaction: \(error)")
    }
  }
}
```

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.

```swift theme={null}
let page = try await meld.searchRetailTransactions(params: MeldSearchRetailTransactionsParams(
  statuses: [.settled, .pending],
  limit: 20
)).data
print("\(page.count) of \(page.totalCount) transactions")

for transaction in page.transactions {
  print(transaction.id, transaction.status, transaction.transactionType, transaction.serviceProvider)
}

if let first = page.transactions.first {
  let transaction = try await meld.getRetailTransaction(transactionId: first.id).data.transaction
  print(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. A list filter matches any of its 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 `nil`, and each of its fields is optional: `blockchainTransactionId`, `chainId`, `destinationWalletAddress`, `sourceWalletAddress`, `sessionWalletAddress`, `institution` and the fees.

## 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 pre-fill KYC fields.

```swift theme={null}
do {
  let customer = try await meld.createCustomer(request: MeldCreateCustomerRequest(
    name: MeldCustomerName(firstName: "Jane", lastName: "Doe"),
    email: "jane@example.com",
    type: .individual
  )).data
  print(customer.id) // pass as customerId on getRetailQuote and createRetailWidget
} catch {
  guard let apiError = MeldApiError.from(error), apiError.status == 409 else {
    throw error
  }
  // The client already has a customer.
  if let existingId = apiError.meldCustomerId {
    print(existingId)
  } else {
    let found = try await meld.searchCustomer().data
    print(found.customers.first?.id ?? "no customer")
  }
}
```

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`, `.individual` or `.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:)` | An array 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:)` | An array of payment methods. |
| `getNetworkPartnerFiatLimits(params:)` | `fiatLimits`: the minimum and maximum fiat amounts. |
| `getNetworkPartnerKycLimits(params:)` | `kycLimits`: the amounts allowed at each KYC level. |
| `getNetworkPartnerRoutes(params:)` | An array 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 `nil` when Meld has none. |

```swift theme={null}
let partners = try await meld.getNetworkPartners(params: MeldGetNetworkPartnersParams(
  category: .cryptoOnramp,
  country: "US"
)).data
for partner in partners {
  print(partner.serviceProvider, partner.name, partner.status)
}

let routes = try await meld.getNetworkPartnerRoutes(params: MeldGetNetworkPartnerRoutesParams(
  category: .cryptoOnramp,
  countryCode: "US",
  sourceCurrencyCode: "USD",
  destinationCurrencyCode: "USDC"
)).data
print(routes.map(\.partner))

if let defaults = try await meld.getNetworkPartnerCountryDefaults(countryCode: "US", category: .cryptoOnramp).data {
  print(defaults)
}
```

The SDK requires none of the filters of six of these methods, which also have an overload without arguments, but Meld's guide lists `category` and `country` as required for most of them, so pass them. `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 a `MeldCategory`, such as `.cryptoOnramp`, `.cryptoOfframp` or `.cryptoTransfer`.

## Handling errors

Besides transport and decoding errors, three kinds of error reach your app:

* **Portal API errors**, thrown as `PortalRequestsError`. `MeldApiError.from(_:)` reads the HTTP `status`, Portal's `id` and the `message`, and, on the `409` from `createCustomer`, the existing customer's `meldCustomerId`. It returns `nil` for an error that isn't an HTTP failure.
* **`MeldError.emptyIdentifier(name:)`**, thrown before any request is sent when an id that goes in the request path, such as `transactionId` or `sessionId`, is empty.
* **`PortalCredentialError`**, with [Client Auth](https://docs.portalhq.io/sdks/ios/guide/client-auth.md), when the session is gone before the request is sent.

```swift theme={null}
do {
  _ = try await meld.getRetailTransaction(transactionId: transactionId)
} catch {
  if let apiError = MeldApiError.from(error) {
    print(apiError.status ?? 0, apiError.id ?? "", apiError.message ?? "")
  } else {
    print(error.localizedDescription)
  }
}
```

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…`).
* `401`: the client's credential was rejected, or Meld rejected the environment's Meld API key (`PortalRequestsError.unauthorized`). With [Client Auth](https://docs.portalhq.io/sdks/ios/guide/client-auth.md#handle-session-invalidation), either 401 ends the session: `onSessionInvalidated` fires and later calls throw `PortalCredentialError.sessionInvalidated`. Check that each environment has the matching Meld sandbox or production key before you ship.
* `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 open values: structs that conform to `MeldOpenValue`, with a `rawValue` and a static constant for each known value, such as `MeldTransactionStatus.settled`. A value Meld adds later still decodes, with its `rawValue`, instead of failing the response. Compare against the known constants, and give a `switch` over one a `default` case. `MeldSessionType` is a closed Swift enum.

## Testing

`portal.ramps.meld` is a `MeldProtocol`, and `PortalApiProtocol` also exposes the methods as `meld`. To use your own implementation in a `PortalProtocol` test double, build the namespace around your `NoahProtocol` and `MeldProtocol` conformances with `Ramps(noah:meld:)`; `Meld(api:)` wraps a fake `PortalMeldApiProtocol`. If you conform to `PortalApiProtocol` yourself, add its new `meld` member.

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


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